repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/modules/pacmanpkg.py | _uninstall | def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different pacman commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
remove_arg = '-Rsc' if action == 'purge' else '-R'
cmd = []
if salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(['pacman', remove_arg, '--noprogressbar', '--noconfirm'])
cmd.extend(targets)
if 'root' in kwargs:
cmd.extend(('-r', kwargs['root']))
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret | python | def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different pacman commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
remove_arg = '-Rsc' if action == 'purge' else '-R'
cmd = []
if salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(['pacman', remove_arg, '--noprogressbar', '--noconfirm'])
cmd.extend(targets)
if 'root' in kwargs:
cmd.extend(('-r', kwargs['root']))
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret | [
"def",
"_uninstall",
"(",
"action",
"=",
"'remove'",
",",
"name",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"pkg_params",
"=",
"__salt__",
"[",
"'pkg_resource.parse_targets'",
"]",
"(",
"name",
",",
"pkgs",
"... | remove and purge do identical things but with different pacman commands,
this function performs the common logic. | [
"remove",
"and",
"purge",
"do",
"identical",
"things",
"but",
"with",
"different",
"pacman",
"commands",
"this",
"function",
"performs",
"the",
"common",
"logic",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pacmanpkg.py#L706-L754 | train |
saltstack/salt | salt/modules/pacmanpkg.py | file_list | def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = []
cmd = ['pacman', '-Ql']
if packages and os.path.exists(packages[0]):
packages = list(packages)
cmd.extend(('-r', packages.pop(0)))
cmd.extend(packages)
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('error'):
errors.append(line)
else:
comps = line.split()
ret.append(' '.join(comps[1:]))
return {'errors': errors, 'files': ret} | python | def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = []
cmd = ['pacman', '-Ql']
if packages and os.path.exists(packages[0]):
packages = list(packages)
cmd.extend(('-r', packages.pop(0)))
cmd.extend(packages)
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('error'):
errors.append(line)
else:
comps = line.split()
ret.append(' '.join(comps[1:]))
return {'errors': errors, 'files': ret} | [
"def",
"file_list",
"(",
"*",
"packages",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"[",
"]",
"ret",
"=",
"[",
"]",
"cmd",
"=",
"[",
"'pacman'",
",",
"'-Ql'",
"]",
"if",
"packages",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"packages"... | List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list | [
"List",
"the",
"files",
"that",
"belong",
"to",
"a",
"package",
".",
"Not",
"specifying",
"any",
"packages",
"will",
"return",
"a",
"list",
"of",
"_every_",
"file",
"on",
"the",
"system",
"s",
"package",
"database",
"(",
"not",
"generally",
"recommended",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pacmanpkg.py#L846-L877 | train |
saltstack/salt | salt/modules/pacmanpkg.py | list_repo_pkgs | def list_repo_pkgs(*args, **kwargs):
'''
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.4.005-2'],
'nginx': ['1.10.2-2']
}
# With byrepo=True
{
'core': {
'bash': ['4.4.005-2']
},
'extra': {
'nginx': ['1.10.2-2']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
refresh : False
When ``True``, the package database will be refreshed (i.e. ``pacman
-Sy``) before checking for available versions.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'samba4*' fromrepo=base,updates
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
fromrepo = kwargs.pop('fromrepo', '') or ''
byrepo = kwargs.pop('byrepo', False)
refresh = kwargs.pop('refresh', False)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if fromrepo:
try:
repos = [x.strip() for x in fromrepo.split(',')]
except AttributeError:
repos = [x.strip() for x in six.text_type(fromrepo).split(',')]
else:
repos = []
if refresh:
refresh_db()
out = __salt__['cmd.run_all'](
['pacman', '-Sl'],
output_loglevel='trace',
ignore_retcode=True,
python_shell=False
)
ret = {}
for line in salt.utils.itertools.split(out['stdout'], '\n'):
try:
repo, pkg_name, pkg_ver = line.strip().split()[:3]
except ValueError:
continue
if repos and repo not in repos:
continue
if args:
for arg in args:
if fnmatch.fnmatch(pkg_name, arg):
skip_pkg = False
break
else:
# Package doesn't match any of the passed args, skip it
continue
ret.setdefault(repo, {}).setdefault(pkg_name, []).append(pkg_ver)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[_LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[_LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret | python | def list_repo_pkgs(*args, **kwargs):
'''
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.4.005-2'],
'nginx': ['1.10.2-2']
}
# With byrepo=True
{
'core': {
'bash': ['4.4.005-2']
},
'extra': {
'nginx': ['1.10.2-2']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
refresh : False
When ``True``, the package database will be refreshed (i.e. ``pacman
-Sy``) before checking for available versions.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'samba4*' fromrepo=base,updates
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
fromrepo = kwargs.pop('fromrepo', '') or ''
byrepo = kwargs.pop('byrepo', False)
refresh = kwargs.pop('refresh', False)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if fromrepo:
try:
repos = [x.strip() for x in fromrepo.split(',')]
except AttributeError:
repos = [x.strip() for x in six.text_type(fromrepo).split(',')]
else:
repos = []
if refresh:
refresh_db()
out = __salt__['cmd.run_all'](
['pacman', '-Sl'],
output_loglevel='trace',
ignore_retcode=True,
python_shell=False
)
ret = {}
for line in salt.utils.itertools.split(out['stdout'], '\n'):
try:
repo, pkg_name, pkg_ver = line.strip().split()[:3]
except ValueError:
continue
if repos and repo not in repos:
continue
if args:
for arg in args:
if fnmatch.fnmatch(pkg_name, arg):
skip_pkg = False
break
else:
# Package doesn't match any of the passed args, skip it
continue
ret.setdefault(repo, {}).setdefault(pkg_name, []).append(pkg_ver)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[_LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[_LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret | [
"def",
"list_repo_pkgs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"fromrepo",
"=",
"kwargs",
".",
"pop",
"(",
"'fromrepo'",
",",
"''",
... | Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.4.005-2'],
'nginx': ['1.10.2-2']
}
# With byrepo=True
{
'core': {
'bash': ['4.4.005-2']
},
'extra': {
'nginx': ['1.10.2-2']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
refresh : False
When ``True``, the package database will be refreshed (i.e. ``pacman
-Sy``) before checking for available versions.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'samba4*' fromrepo=base,updates
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True | [
"Returns",
"all",
"available",
"packages",
".",
"Optionally",
"package",
"names",
"(",
"and",
"name",
"globs",
")",
"can",
"be",
"passed",
"and",
"the",
"results",
"will",
"be",
"filtered",
"to",
"packages",
"matching",
"those",
"names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pacmanpkg.py#L946-L1066 | train |
saltstack/salt | salt/cli/spm.py | SPM.run | def run(self):
'''
Run the api
'''
ui = salt.spm.SPMCmdlineInterface()
self.parse_args()
self.setup_logfile_logger()
v_dirs = [
self.config['spm_cache_dir'],
]
verify_env(v_dirs,
self.config['user'],
root_dir=self.config['root_dir'],
)
verify_log(self.config)
client = salt.spm.SPMClient(ui, self.config)
client.run(self.args) | python | def run(self):
'''
Run the api
'''
ui = salt.spm.SPMCmdlineInterface()
self.parse_args()
self.setup_logfile_logger()
v_dirs = [
self.config['spm_cache_dir'],
]
verify_env(v_dirs,
self.config['user'],
root_dir=self.config['root_dir'],
)
verify_log(self.config)
client = salt.spm.SPMClient(ui, self.config)
client.run(self.args) | [
"def",
"run",
"(",
"self",
")",
":",
"ui",
"=",
"salt",
".",
"spm",
".",
"SPMCmdlineInterface",
"(",
")",
"self",
".",
"parse_args",
"(",
")",
"self",
".",
"setup_logfile_logger",
"(",
")",
"v_dirs",
"=",
"[",
"self",
".",
"config",
"[",
"'spm_cache_di... | Run the api | [
"Run",
"the",
"api"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/spm.py#L25-L41 | train |
saltstack/salt | salt/pillar/sql_base.py | SqlBaseExtPillar.extract_queries | def extract_queries(self, args, kwargs):
'''
This function normalizes the config block into a set of queries we
can use. The return is a list of consistently laid out dicts.
'''
# Please note the function signature is NOT an error. Neither args, nor
# kwargs should have asterisks. We are passing in a list and dict,
# rather than receiving variable args. Adding asterisks WILL BREAK the
# function completely.
# First, this is the query buffer. Contains lists of [base,sql]
qbuffer = []
# Add on the non-keywords...
qbuffer.extend([[None, s] for s in args])
# And then the keywords...
# They aren't in definition order, but they can't conflict each other.
klist = list(kwargs.keys())
klist.sort()
qbuffer.extend([[k, kwargs[k]] for k in klist])
# Filter out values that don't have queries.
qbuffer = [x for x in qbuffer if (
(isinstance(x[1], six.string_types) and len(x[1]))
or
(isinstance(x[1], (list, tuple)) and (len(x[1]) > 0) and x[1][0])
or
(isinstance(x[1], dict) and 'query' in x[1] and len(x[1]['query']))
)]
# Next, turn the whole buffer into full dicts.
for qb in qbuffer:
defaults = {'query': '',
'depth': 0,
'as_list': False,
'with_lists': None,
'ignore_null': False
}
if isinstance(qb[1], six.string_types):
defaults['query'] = qb[1]
elif isinstance(qb[1], (list, tuple)):
defaults['query'] = qb[1][0]
if len(qb[1]) > 1:
defaults['depth'] = qb[1][1]
# May set 'as_list' from qb[1][2].
else:
defaults.update(qb[1])
if defaults['with_lists'] and isinstance(defaults['with_lists'], six.string_types):
defaults['with_lists'] = [
int(i) for i in defaults['with_lists'].split(',')
]
qb[1] = defaults
return qbuffer | python | def extract_queries(self, args, kwargs):
'''
This function normalizes the config block into a set of queries we
can use. The return is a list of consistently laid out dicts.
'''
# Please note the function signature is NOT an error. Neither args, nor
# kwargs should have asterisks. We are passing in a list and dict,
# rather than receiving variable args. Adding asterisks WILL BREAK the
# function completely.
# First, this is the query buffer. Contains lists of [base,sql]
qbuffer = []
# Add on the non-keywords...
qbuffer.extend([[None, s] for s in args])
# And then the keywords...
# They aren't in definition order, but they can't conflict each other.
klist = list(kwargs.keys())
klist.sort()
qbuffer.extend([[k, kwargs[k]] for k in klist])
# Filter out values that don't have queries.
qbuffer = [x for x in qbuffer if (
(isinstance(x[1], six.string_types) and len(x[1]))
or
(isinstance(x[1], (list, tuple)) and (len(x[1]) > 0) and x[1][0])
or
(isinstance(x[1], dict) and 'query' in x[1] and len(x[1]['query']))
)]
# Next, turn the whole buffer into full dicts.
for qb in qbuffer:
defaults = {'query': '',
'depth': 0,
'as_list': False,
'with_lists': None,
'ignore_null': False
}
if isinstance(qb[1], six.string_types):
defaults['query'] = qb[1]
elif isinstance(qb[1], (list, tuple)):
defaults['query'] = qb[1][0]
if len(qb[1]) > 1:
defaults['depth'] = qb[1][1]
# May set 'as_list' from qb[1][2].
else:
defaults.update(qb[1])
if defaults['with_lists'] and isinstance(defaults['with_lists'], six.string_types):
defaults['with_lists'] = [
int(i) for i in defaults['with_lists'].split(',')
]
qb[1] = defaults
return qbuffer | [
"def",
"extract_queries",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"# Please note the function signature is NOT an error. Neither args, nor",
"# kwargs should have asterisks. We are passing in a list and dict,",
"# rather than receiving variable args. Adding asterisks WILL BREAK... | This function normalizes the config block into a set of queries we
can use. The return is a list of consistently laid out dicts. | [
"This",
"function",
"normalizes",
"the",
"config",
"block",
"into",
"a",
"set",
"of",
"queries",
"we",
"can",
"use",
".",
"The",
"return",
"is",
"a",
"list",
"of",
"consistently",
"laid",
"out",
"dicts",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/sql_base.py#L230-L284 | train |
saltstack/salt | salt/pillar/sql_base.py | SqlBaseExtPillar.enter_root | def enter_root(self, root):
'''
Set self.focus for kwarg queries
'''
# There is no collision protection on root name isolation
if root:
self.result[root] = self.focus = {}
else:
self.focus = self.result | python | def enter_root(self, root):
'''
Set self.focus for kwarg queries
'''
# There is no collision protection on root name isolation
if root:
self.result[root] = self.focus = {}
else:
self.focus = self.result | [
"def",
"enter_root",
"(",
"self",
",",
"root",
")",
":",
"# There is no collision protection on root name isolation",
"if",
"root",
":",
"self",
".",
"result",
"[",
"root",
"]",
"=",
"self",
".",
"focus",
"=",
"{",
"}",
"else",
":",
"self",
".",
"focus",
"... | Set self.focus for kwarg queries | [
"Set",
"self",
".",
"focus",
"for",
"kwarg",
"queries"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/sql_base.py#L286-L294 | train |
saltstack/salt | salt/pillar/sql_base.py | SqlBaseExtPillar.process_fields | def process_fields(self, field_names, depth):
'''
The primary purpose of this function is to store the sql field list
and the depth to which we process.
'''
# List of field names in correct order.
self.field_names = field_names
# number of fields.
self.num_fields = len(field_names)
# Constrain depth.
if (depth == 0) or (depth >= self.num_fields):
self.depth = self.num_fields - 1
else:
self.depth = depth | python | def process_fields(self, field_names, depth):
'''
The primary purpose of this function is to store the sql field list
and the depth to which we process.
'''
# List of field names in correct order.
self.field_names = field_names
# number of fields.
self.num_fields = len(field_names)
# Constrain depth.
if (depth == 0) or (depth >= self.num_fields):
self.depth = self.num_fields - 1
else:
self.depth = depth | [
"def",
"process_fields",
"(",
"self",
",",
"field_names",
",",
"depth",
")",
":",
"# List of field names in correct order.",
"self",
".",
"field_names",
"=",
"field_names",
"# number of fields.",
"self",
".",
"num_fields",
"=",
"len",
"(",
"field_names",
")",
"# Con... | The primary purpose of this function is to store the sql field list
and the depth to which we process. | [
"The",
"primary",
"purpose",
"of",
"this",
"function",
"is",
"to",
"store",
"the",
"sql",
"field",
"list",
"and",
"the",
"depth",
"to",
"which",
"we",
"process",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/sql_base.py#L296-L309 | train |
saltstack/salt | salt/pillar/sql_base.py | SqlBaseExtPillar.process_results | def process_results(self, rows):
'''
This function takes a list of database results and iterates over,
merging them into a dict form.
'''
listify = OrderedDict()
listify_dicts = OrderedDict()
for ret in rows:
# crd is the Current Return Data level, to make this non-recursive.
crd = self.focus
# Walk and create dicts above the final layer
for i in range(0, self.depth-1):
# At the end we'll use listify to find values to make a list of
if i+1 in self.with_lists:
if id(crd) not in listify:
listify[id(crd)] = []
listify_dicts[id(crd)] = crd
if ret[i] not in listify[id(crd)]:
listify[id(crd)].append(ret[i])
if ret[i] not in crd:
# Key missing
crd[ret[i]] = {}
crd = crd[ret[i]]
else:
# Check type of collision
ty = type(crd[ret[i]])
if ty is list:
# Already made list
temp = {}
crd[ret[i]].append(temp)
crd = temp
elif ty is not dict:
# Not a list, not a dict
if self.as_list:
# Make list
temp = {}
crd[ret[i]] = [crd[ret[i]], temp]
crd = temp
else:
# Overwrite
crd[ret[i]] = {}
crd = crd[ret[i]]
else:
# dict, descend.
crd = crd[ret[i]]
# If this test is true, the penultimate field is the key
if self.depth == self.num_fields - 1:
nk = self.num_fields-2 # Aka, self.depth-1
# Should we and will we have a list at the end?
if ((self.as_list and (ret[nk] in crd)) or
(nk+1 in self.with_lists)):
if ret[nk] in crd:
if not isinstance(crd[ret[nk]], list):
crd[ret[nk]] = [crd[ret[nk]]]
# if it's already a list, do nothing
else:
crd[ret[nk]] = []
crd[ret[nk]].append(ret[self.num_fields-1])
else:
if not self.ignore_null or ret[self.num_fields-1] is not None:
crd[ret[nk]] = ret[self.num_fields-1]
else:
# Otherwise, the field name is the key but we have a spare.
# The spare results because of {c: d} vs {c: {"d": d, "e": e }}
# So, make that last dict
if ret[self.depth-1] not in crd:
crd[ret[self.depth-1]] = {}
# This bit doesn't escape listify
if self.depth in self.with_lists:
if id(crd) not in listify:
listify[id(crd)] = []
listify_dicts[id(crd)] = crd
if ret[self.depth-1] not in listify[id(crd)]:
listify[id(crd)].append(ret[self.depth-1])
crd = crd[ret[self.depth-1]]
# Now for the remaining keys, we put them into the dict
for i in range(self.depth, self.num_fields):
nk = self.field_names[i]
# Listify
if i+1 in self.with_lists:
if id(crd) not in listify:
listify[id(crd)] = []
listify_dicts[id(crd)] = crd
if nk not in listify[id(crd)]:
listify[id(crd)].append(nk)
# Collision detection
if self.as_list and (nk in crd):
# Same as before...
if isinstance(crd[nk], list):
crd[nk].append(ret[i])
else:
crd[nk] = [crd[nk], ret[i]]
else:
if not self.ignore_null or ret[i] is not None:
crd[nk] = ret[i]
# Get key list and work backwards. This is inner-out processing
ks = list(listify_dicts.keys())
ks.reverse()
for i in ks:
d = listify_dicts[i]
for k in listify[i]:
if isinstance(d[k], dict):
d[k] = list(d[k].values())
elif isinstance(d[k], list):
d[k] = [d[k]] | python | def process_results(self, rows):
'''
This function takes a list of database results and iterates over,
merging them into a dict form.
'''
listify = OrderedDict()
listify_dicts = OrderedDict()
for ret in rows:
# crd is the Current Return Data level, to make this non-recursive.
crd = self.focus
# Walk and create dicts above the final layer
for i in range(0, self.depth-1):
# At the end we'll use listify to find values to make a list of
if i+1 in self.with_lists:
if id(crd) not in listify:
listify[id(crd)] = []
listify_dicts[id(crd)] = crd
if ret[i] not in listify[id(crd)]:
listify[id(crd)].append(ret[i])
if ret[i] not in crd:
# Key missing
crd[ret[i]] = {}
crd = crd[ret[i]]
else:
# Check type of collision
ty = type(crd[ret[i]])
if ty is list:
# Already made list
temp = {}
crd[ret[i]].append(temp)
crd = temp
elif ty is not dict:
# Not a list, not a dict
if self.as_list:
# Make list
temp = {}
crd[ret[i]] = [crd[ret[i]], temp]
crd = temp
else:
# Overwrite
crd[ret[i]] = {}
crd = crd[ret[i]]
else:
# dict, descend.
crd = crd[ret[i]]
# If this test is true, the penultimate field is the key
if self.depth == self.num_fields - 1:
nk = self.num_fields-2 # Aka, self.depth-1
# Should we and will we have a list at the end?
if ((self.as_list and (ret[nk] in crd)) or
(nk+1 in self.with_lists)):
if ret[nk] in crd:
if not isinstance(crd[ret[nk]], list):
crd[ret[nk]] = [crd[ret[nk]]]
# if it's already a list, do nothing
else:
crd[ret[nk]] = []
crd[ret[nk]].append(ret[self.num_fields-1])
else:
if not self.ignore_null or ret[self.num_fields-1] is not None:
crd[ret[nk]] = ret[self.num_fields-1]
else:
# Otherwise, the field name is the key but we have a spare.
# The spare results because of {c: d} vs {c: {"d": d, "e": e }}
# So, make that last dict
if ret[self.depth-1] not in crd:
crd[ret[self.depth-1]] = {}
# This bit doesn't escape listify
if self.depth in self.with_lists:
if id(crd) not in listify:
listify[id(crd)] = []
listify_dicts[id(crd)] = crd
if ret[self.depth-1] not in listify[id(crd)]:
listify[id(crd)].append(ret[self.depth-1])
crd = crd[ret[self.depth-1]]
# Now for the remaining keys, we put them into the dict
for i in range(self.depth, self.num_fields):
nk = self.field_names[i]
# Listify
if i+1 in self.with_lists:
if id(crd) not in listify:
listify[id(crd)] = []
listify_dicts[id(crd)] = crd
if nk not in listify[id(crd)]:
listify[id(crd)].append(nk)
# Collision detection
if self.as_list and (nk in crd):
# Same as before...
if isinstance(crd[nk], list):
crd[nk].append(ret[i])
else:
crd[nk] = [crd[nk], ret[i]]
else:
if not self.ignore_null or ret[i] is not None:
crd[nk] = ret[i]
# Get key list and work backwards. This is inner-out processing
ks = list(listify_dicts.keys())
ks.reverse()
for i in ks:
d = listify_dicts[i]
for k in listify[i]:
if isinstance(d[k], dict):
d[k] = list(d[k].values())
elif isinstance(d[k], list):
d[k] = [d[k]] | [
"def",
"process_results",
"(",
"self",
",",
"rows",
")",
":",
"listify",
"=",
"OrderedDict",
"(",
")",
"listify_dicts",
"=",
"OrderedDict",
"(",
")",
"for",
"ret",
"in",
"rows",
":",
"# crd is the Current Return Data level, to make this non-recursive.",
"crd",
"=",
... | This function takes a list of database results and iterates over,
merging them into a dict form. | [
"This",
"function",
"takes",
"a",
"list",
"of",
"database",
"results",
"and",
"iterates",
"over",
"merging",
"them",
"into",
"a",
"dict",
"form",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/sql_base.py#L311-L416 | train |
saltstack/salt | salt/pillar/sql_base.py | SqlBaseExtPillar.fetch | def fetch(self,
minion_id,
pillar, # pylint: disable=W0613
*args,
**kwargs):
'''
Execute queries, merge and return as a dict.
'''
db_name = self._db_name()
log.info('Querying %s for information for %s', db_name, minion_id)
#
# log.debug('ext_pillar %s args: %s', db_name, args)
# log.debug('ext_pillar %s kwargs: %s', db_name, kwargs)
#
# Most of the heavy lifting is in this class for ease of testing.
qbuffer = self.extract_queries(args, kwargs)
with self._get_cursor() as cursor:
for root, details in qbuffer:
# Run the query
cursor.execute(details['query'], (minion_id,))
# Extract the field names the db has returned and process them
self.process_fields([row[0] for row in cursor.description], details['depth'])
self.enter_root(root)
self.as_list = details['as_list']
if details['with_lists']:
self.with_lists = details['with_lists']
else:
self.with_lists = []
self.ignore_null = details['ignore_null']
self.process_results(cursor.fetchall())
log.debug('ext_pillar %s: Return data: %s', db_name, self)
return self.result | python | def fetch(self,
minion_id,
pillar, # pylint: disable=W0613
*args,
**kwargs):
'''
Execute queries, merge and return as a dict.
'''
db_name = self._db_name()
log.info('Querying %s for information for %s', db_name, minion_id)
#
# log.debug('ext_pillar %s args: %s', db_name, args)
# log.debug('ext_pillar %s kwargs: %s', db_name, kwargs)
#
# Most of the heavy lifting is in this class for ease of testing.
qbuffer = self.extract_queries(args, kwargs)
with self._get_cursor() as cursor:
for root, details in qbuffer:
# Run the query
cursor.execute(details['query'], (minion_id,))
# Extract the field names the db has returned and process them
self.process_fields([row[0] for row in cursor.description], details['depth'])
self.enter_root(root)
self.as_list = details['as_list']
if details['with_lists']:
self.with_lists = details['with_lists']
else:
self.with_lists = []
self.ignore_null = details['ignore_null']
self.process_results(cursor.fetchall())
log.debug('ext_pillar %s: Return data: %s', db_name, self)
return self.result | [
"def",
"fetch",
"(",
"self",
",",
"minion_id",
",",
"pillar",
",",
"# pylint: disable=W0613",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"db_name",
"=",
"self",
".",
"_db_name",
"(",
")",
"log",
".",
"info",
"(",
"'Querying %s for information for %s'",
... | Execute queries, merge and return as a dict. | [
"Execute",
"queries",
"merge",
"and",
"return",
"as",
"a",
"dict",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/sql_base.py#L418-L451 | train |
saltstack/salt | salt/modules/bridge.py | _linux_brshow | def _linux_brshow(br=None):
'''
Internal, returns bridges and enslaved interfaces (GNU/Linux - brctl)
'''
brctl = _tool_path('brctl')
if br:
cmd = '{0} show {1}'.format(brctl, br)
else:
cmd = '{0} show'.format(brctl)
brs = {}
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
# get rid of first line
if line.startswith('bridge name'):
continue
# get rid of ^\n's
vals = line.split()
if not vals:
continue
# bridge name bridge id STP enabled interfaces
# br0 8000.e4115bac8ddc no eth0
# foo0
# br1 8000.e4115bac8ddc no eth1
if len(vals) > 1:
brname = vals[0]
brs[brname] = {
'id': vals[1],
'stp': vals[2],
}
if len(vals) > 3:
brs[brname]['interfaces'] = [vals[3]]
if len(vals) == 1 and brname:
brs[brname]['interfaces'].append(vals[0])
if br:
try:
return brs[br]
except KeyError:
return None
return brs | python | def _linux_brshow(br=None):
'''
Internal, returns bridges and enslaved interfaces (GNU/Linux - brctl)
'''
brctl = _tool_path('brctl')
if br:
cmd = '{0} show {1}'.format(brctl, br)
else:
cmd = '{0} show'.format(brctl)
brs = {}
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
# get rid of first line
if line.startswith('bridge name'):
continue
# get rid of ^\n's
vals = line.split()
if not vals:
continue
# bridge name bridge id STP enabled interfaces
# br0 8000.e4115bac8ddc no eth0
# foo0
# br1 8000.e4115bac8ddc no eth1
if len(vals) > 1:
brname = vals[0]
brs[brname] = {
'id': vals[1],
'stp': vals[2],
}
if len(vals) > 3:
brs[brname]['interfaces'] = [vals[3]]
if len(vals) == 1 and brname:
brs[brname]['interfaces'].append(vals[0])
if br:
try:
return brs[br]
except KeyError:
return None
return brs | [
"def",
"_linux_brshow",
"(",
"br",
"=",
"None",
")",
":",
"brctl",
"=",
"_tool_path",
"(",
"'brctl'",
")",
"if",
"br",
":",
"cmd",
"=",
"'{0} show {1}'",
".",
"format",
"(",
"brctl",
",",
"br",
")",
"else",
":",
"cmd",
"=",
"'{0} show'",
".",
"format... | Internal, returns bridges and enslaved interfaces (GNU/Linux - brctl) | [
"Internal",
"returns",
"bridges",
"and",
"enslaved",
"interfaces",
"(",
"GNU",
"/",
"Linux",
"-",
"brctl",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L47-L91 | train |
saltstack/salt | salt/modules/bridge.py | _linux_bradd | def _linux_bradd(br):
'''
Internal, creates the bridge
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} addbr {1}'.format(brctl, br),
python_shell=False) | python | def _linux_bradd(br):
'''
Internal, creates the bridge
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} addbr {1}'.format(brctl, br),
python_shell=False) | [
"def",
"_linux_bradd",
"(",
"br",
")",
":",
"brctl",
"=",
"_tool_path",
"(",
"'brctl'",
")",
"return",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'{0} addbr {1}'",
".",
"format",
"(",
"brctl",
",",
"br",
")",
",",
"python_shell",
"=",
"False",
")"
] | Internal, creates the bridge | [
"Internal",
"creates",
"the",
"bridge"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L94-L100 | train |
saltstack/salt | salt/modules/bridge.py | _linux_brdel | def _linux_brdel(br):
'''
Internal, deletes the bridge
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} delbr {1}'.format(brctl, br),
python_shell=False) | python | def _linux_brdel(br):
'''
Internal, deletes the bridge
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} delbr {1}'.format(brctl, br),
python_shell=False) | [
"def",
"_linux_brdel",
"(",
"br",
")",
":",
"brctl",
"=",
"_tool_path",
"(",
"'brctl'",
")",
"return",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'{0} delbr {1}'",
".",
"format",
"(",
"brctl",
",",
"br",
")",
",",
"python_shell",
"=",
"False",
")"
] | Internal, deletes the bridge | [
"Internal",
"deletes",
"the",
"bridge"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L103-L109 | train |
saltstack/salt | salt/modules/bridge.py | _linux_delif | def _linux_delif(br, iface):
'''
Internal, removes an interface from a bridge
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} delif {1} {2}'.format(brctl, br, iface),
python_shell=False) | python | def _linux_delif(br, iface):
'''
Internal, removes an interface from a bridge
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} delif {1} {2}'.format(brctl, br, iface),
python_shell=False) | [
"def",
"_linux_delif",
"(",
"br",
",",
"iface",
")",
":",
"brctl",
"=",
"_tool_path",
"(",
"'brctl'",
")",
"return",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'{0} delif {1} {2}'",
".",
"format",
"(",
"brctl",
",",
"br",
",",
"iface",
")",
",",
"python_sh... | Internal, removes an interface from a bridge | [
"Internal",
"removes",
"an",
"interface",
"from",
"a",
"bridge"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L121-L127 | train |
saltstack/salt | salt/modules/bridge.py | _linux_stp | def _linux_stp(br, state):
'''
Internal, sets STP state
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} stp {1} {2}'.format(brctl, br, state),
python_shell=False) | python | def _linux_stp(br, state):
'''
Internal, sets STP state
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} stp {1} {2}'.format(brctl, br, state),
python_shell=False) | [
"def",
"_linux_stp",
"(",
"br",
",",
"state",
")",
":",
"brctl",
"=",
"_tool_path",
"(",
"'brctl'",
")",
"return",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'{0} stp {1} {2}'",
".",
"format",
"(",
"brctl",
",",
"br",
",",
"state",
")",
",",
"python_shell"... | Internal, sets STP state | [
"Internal",
"sets",
"STP",
"state"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L130-L136 | train |
saltstack/salt | salt/modules/bridge.py | _bsd_brshow | def _bsd_brshow(br=None):
'''
Internal, returns bridges and member interfaces (BSD-like: ifconfig)
'''
if __grains__['kernel'] == 'NetBSD':
return _netbsd_brshow(br)
ifconfig = _tool_path('ifconfig')
ifaces = {}
if br:
ifaces[br] = br
else:
cmd = '{0} -g bridge'.format(ifconfig)
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
ifaces[line] = line
brs = {}
for iface in ifaces:
cmd = '{0} {1}'.format(ifconfig, iface)
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
brs[iface] = {
'interfaces': [],
'stp': 'no'
}
line = line.lstrip()
if line.startswith('member:'):
brs[iface]['interfaces'].append(line.split(' ')[1])
if 'STP' in line:
brs[iface]['stp'] = 'yes'
if br:
return brs[br]
return brs | python | def _bsd_brshow(br=None):
'''
Internal, returns bridges and member interfaces (BSD-like: ifconfig)
'''
if __grains__['kernel'] == 'NetBSD':
return _netbsd_brshow(br)
ifconfig = _tool_path('ifconfig')
ifaces = {}
if br:
ifaces[br] = br
else:
cmd = '{0} -g bridge'.format(ifconfig)
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
ifaces[line] = line
brs = {}
for iface in ifaces:
cmd = '{0} {1}'.format(ifconfig, iface)
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
brs[iface] = {
'interfaces': [],
'stp': 'no'
}
line = line.lstrip()
if line.startswith('member:'):
brs[iface]['interfaces'].append(line.split(' ')[1])
if 'STP' in line:
brs[iface]['stp'] = 'yes'
if br:
return brs[br]
return brs | [
"def",
"_bsd_brshow",
"(",
"br",
"=",
"None",
")",
":",
"if",
"__grains__",
"[",
"'kernel'",
"]",
"==",
"'NetBSD'",
":",
"return",
"_netbsd_brshow",
"(",
"br",
")",
"ifconfig",
"=",
"_tool_path",
"(",
"'ifconfig'",
")",
"ifaces",
"=",
"{",
"}",
"if",
"... | Internal, returns bridges and member interfaces (BSD-like: ifconfig) | [
"Internal",
"returns",
"bridges",
"and",
"member",
"interfaces",
"(",
"BSD",
"-",
"like",
":",
"ifconfig",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L139-L174 | train |
saltstack/salt | salt/modules/bridge.py | _netbsd_brshow | def _netbsd_brshow(br=None):
'''
Internal, returns bridges and enslaved interfaces (NetBSD - brconfig)
'''
brconfig = _tool_path('brconfig')
if br:
cmd = '{0} {1}'.format(brconfig, br)
else:
cmd = '{0} -a'.format(brconfig)
brs = {}
start_int = False
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
if line.startswith('bridge'):
start_int = False
brname = line.split(':')[0] # on NetBSD, always ^bridge([0-9]+):
brs[brname] = {
'interfaces': [],
'stp': 'no'
}
if 'Interfaces:' in line:
start_int = True
continue
if start_int and brname:
m = re.match(r'\s*([a-z0-9]+)\s.*<.*>', line)
if m:
brs[brname]['interfaces'].append(m.group(1))
if 'STP' in line:
brs[brname]['stp'] = 'yes'
if br:
try:
return brs[br]
except KeyError:
return None
return brs | python | def _netbsd_brshow(br=None):
'''
Internal, returns bridges and enslaved interfaces (NetBSD - brconfig)
'''
brconfig = _tool_path('brconfig')
if br:
cmd = '{0} {1}'.format(brconfig, br)
else:
cmd = '{0} -a'.format(brconfig)
brs = {}
start_int = False
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
if line.startswith('bridge'):
start_int = False
brname = line.split(':')[0] # on NetBSD, always ^bridge([0-9]+):
brs[brname] = {
'interfaces': [],
'stp': 'no'
}
if 'Interfaces:' in line:
start_int = True
continue
if start_int and brname:
m = re.match(r'\s*([a-z0-9]+)\s.*<.*>', line)
if m:
brs[brname]['interfaces'].append(m.group(1))
if 'STP' in line:
brs[brname]['stp'] = 'yes'
if br:
try:
return brs[br]
except KeyError:
return None
return brs | [
"def",
"_netbsd_brshow",
"(",
"br",
"=",
"None",
")",
":",
"brconfig",
"=",
"_tool_path",
"(",
"'brconfig'",
")",
"if",
"br",
":",
"cmd",
"=",
"'{0} {1}'",
".",
"format",
"(",
"brconfig",
",",
"br",
")",
"else",
":",
"cmd",
"=",
"'{0} -a'",
".",
"for... | Internal, returns bridges and enslaved interfaces (NetBSD - brconfig) | [
"Internal",
"returns",
"bridges",
"and",
"enslaved",
"interfaces",
"(",
"NetBSD",
"-",
"brconfig",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L177-L214 | train |
saltstack/salt | salt/modules/bridge.py | _bsd_bradd | def _bsd_bradd(br):
'''
Internal, creates the bridge
'''
kernel = __grains__['kernel']
ifconfig = _tool_path('ifconfig')
if not br:
return False
if __salt__['cmd.retcode']('{0} {1} create up'.format(ifconfig, br),
python_shell=False) != 0:
return False
# NetBSD is two cmds
if kernel == 'NetBSD':
brconfig = _tool_path('brconfig')
if __salt__['cmd.retcode']('{0} {1} up'.format(brconfig, br),
python_shell=False) != 0:
return False
return True | python | def _bsd_bradd(br):
'''
Internal, creates the bridge
'''
kernel = __grains__['kernel']
ifconfig = _tool_path('ifconfig')
if not br:
return False
if __salt__['cmd.retcode']('{0} {1} create up'.format(ifconfig, br),
python_shell=False) != 0:
return False
# NetBSD is two cmds
if kernel == 'NetBSD':
brconfig = _tool_path('brconfig')
if __salt__['cmd.retcode']('{0} {1} up'.format(brconfig, br),
python_shell=False) != 0:
return False
return True | [
"def",
"_bsd_bradd",
"(",
"br",
")",
":",
"kernel",
"=",
"__grains__",
"[",
"'kernel'",
"]",
"ifconfig",
"=",
"_tool_path",
"(",
"'ifconfig'",
")",
"if",
"not",
"br",
":",
"return",
"False",
"if",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"'{0} {1} creat... | Internal, creates the bridge | [
"Internal",
"creates",
"the",
"bridge"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L217-L238 | train |
saltstack/salt | salt/modules/bridge.py | _bsd_brdel | def _bsd_brdel(br):
'''
Internal, deletes the bridge
'''
ifconfig = _tool_path('ifconfig')
if not br:
return False
return __salt__['cmd.run']('{0} {1} destroy'.format(ifconfig, br),
python_shell=False) | python | def _bsd_brdel(br):
'''
Internal, deletes the bridge
'''
ifconfig = _tool_path('ifconfig')
if not br:
return False
return __salt__['cmd.run']('{0} {1} destroy'.format(ifconfig, br),
python_shell=False) | [
"def",
"_bsd_brdel",
"(",
"br",
")",
":",
"ifconfig",
"=",
"_tool_path",
"(",
"'ifconfig'",
")",
"if",
"not",
"br",
":",
"return",
"False",
"return",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'{0} {1} destroy'",
".",
"format",
"(",
"ifconfig",
",",
"br",
... | Internal, deletes the bridge | [
"Internal",
"deletes",
"the",
"bridge"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L241-L249 | train |
saltstack/salt | salt/modules/bridge.py | _bsd_addif | def _bsd_addif(br, iface):
'''
Internal, adds an interface to a bridge
'''
kernel = __grains__['kernel']
if kernel == 'NetBSD':
cmd = _tool_path('brconfig')
brcmd = 'add'
else:
cmd = _tool_path('ifconfig')
brcmd = 'addem'
if not br or not iface:
return False
return __salt__['cmd.run']('{0} {1} {2} {3}'.format(cmd, br, brcmd, iface),
python_shell=False) | python | def _bsd_addif(br, iface):
'''
Internal, adds an interface to a bridge
'''
kernel = __grains__['kernel']
if kernel == 'NetBSD':
cmd = _tool_path('brconfig')
brcmd = 'add'
else:
cmd = _tool_path('ifconfig')
brcmd = 'addem'
if not br or not iface:
return False
return __salt__['cmd.run']('{0} {1} {2} {3}'.format(cmd, br, brcmd, iface),
python_shell=False) | [
"def",
"_bsd_addif",
"(",
"br",
",",
"iface",
")",
":",
"kernel",
"=",
"__grains__",
"[",
"'kernel'",
"]",
"if",
"kernel",
"==",
"'NetBSD'",
":",
"cmd",
"=",
"_tool_path",
"(",
"'brconfig'",
")",
"brcmd",
"=",
"'add'",
"else",
":",
"cmd",
"=",
"_tool_p... | Internal, adds an interface to a bridge | [
"Internal",
"adds",
"an",
"interface",
"to",
"a",
"bridge"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L252-L268 | train |
saltstack/salt | salt/modules/bridge.py | _bsd_stp | def _bsd_stp(br, state, iface):
'''
Internal, sets STP state. On BSD-like, it is required to specify the
STP physical interface
'''
kernel = __grains__['kernel']
if kernel == 'NetBSD':
cmd = _tool_path('brconfig')
else:
cmd = _tool_path('ifconfig')
if not br or not iface:
return False
return __salt__['cmd.run']('{0} {1} {2} {3}'.format(cmd, br, state, iface),
python_shell=False) | python | def _bsd_stp(br, state, iface):
'''
Internal, sets STP state. On BSD-like, it is required to specify the
STP physical interface
'''
kernel = __grains__['kernel']
if kernel == 'NetBSD':
cmd = _tool_path('brconfig')
else:
cmd = _tool_path('ifconfig')
if not br or not iface:
return False
return __salt__['cmd.run']('{0} {1} {2} {3}'.format(cmd, br, state, iface),
python_shell=False) | [
"def",
"_bsd_stp",
"(",
"br",
",",
"state",
",",
"iface",
")",
":",
"kernel",
"=",
"__grains__",
"[",
"'kernel'",
"]",
"if",
"kernel",
"==",
"'NetBSD'",
":",
"cmd",
"=",
"_tool_path",
"(",
"'brconfig'",
")",
"else",
":",
"cmd",
"=",
"_tool_path",
"(",
... | Internal, sets STP state. On BSD-like, it is required to specify the
STP physical interface | [
"Internal",
"sets",
"STP",
"state",
".",
"On",
"BSD",
"-",
"like",
"it",
"is",
"required",
"to",
"specify",
"the",
"STP",
"physical",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L290-L305 | train |
saltstack/salt | salt/modules/bridge.py | _os_dispatch | def _os_dispatch(func, *args, **kwargs):
'''
Internal, dispatches functions by operating system
'''
if __grains__['kernel'] in SUPPORTED_BSD_LIKE:
kernel = 'bsd'
else:
kernel = __grains__['kernel'].lower()
_os_func = getattr(sys.modules[__name__], '_{0}_{1}'.format(kernel, func))
if callable(_os_func):
return _os_func(*args, **kwargs) | python | def _os_dispatch(func, *args, **kwargs):
'''
Internal, dispatches functions by operating system
'''
if __grains__['kernel'] in SUPPORTED_BSD_LIKE:
kernel = 'bsd'
else:
kernel = __grains__['kernel'].lower()
_os_func = getattr(sys.modules[__name__], '_{0}_{1}'.format(kernel, func))
if callable(_os_func):
return _os_func(*args, **kwargs) | [
"def",
"_os_dispatch",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"__grains__",
"[",
"'kernel'",
"]",
"in",
"SUPPORTED_BSD_LIKE",
":",
"kernel",
"=",
"'bsd'",
"else",
":",
"kernel",
"=",
"__grains__",
"[",
"'kernel'",
"]",
... | Internal, dispatches functions by operating system | [
"Internal",
"dispatches",
"functions",
"by",
"operating",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L308-L320 | train |
saltstack/salt | salt/modules/bridge.py | list_ | def list_():
'''
Returns the machine's bridges list
CLI Example:
.. code-block:: bash
salt '*' bridge.list
'''
brs = _os_dispatch('brshow')
if not brs:
return None
brlist = []
for br in brs:
brlist.append(br)
return brlist | python | def list_():
'''
Returns the machine's bridges list
CLI Example:
.. code-block:: bash
salt '*' bridge.list
'''
brs = _os_dispatch('brshow')
if not brs:
return None
brlist = []
for br in brs:
brlist.append(br)
return brlist | [
"def",
"list_",
"(",
")",
":",
"brs",
"=",
"_os_dispatch",
"(",
"'brshow'",
")",
"if",
"not",
"brs",
":",
"return",
"None",
"brlist",
"=",
"[",
"]",
"for",
"br",
"in",
"brs",
":",
"brlist",
".",
"append",
"(",
"br",
")",
"return",
"brlist"
] | Returns the machine's bridges list
CLI Example:
.. code-block:: bash
salt '*' bridge.list | [
"Returns",
"the",
"machine",
"s",
"bridges",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L342-L359 | train |
saltstack/salt | salt/modules/bridge.py | find_interfaces | def find_interfaces(*args):
'''
Returns the bridge to which the interfaces are bond to
CLI Example:
.. code-block:: bash
salt '*' bridge.find_interfaces eth0 [eth1...]
'''
brs = _os_dispatch('brshow')
if not brs:
return None
iflist = {}
for iface in args:
for br in brs:
try: # a bridge may not contain interfaces
if iface in brs[br]['interfaces']:
iflist[iface] = br
except Exception:
pass
return iflist | python | def find_interfaces(*args):
'''
Returns the bridge to which the interfaces are bond to
CLI Example:
.. code-block:: bash
salt '*' bridge.find_interfaces eth0 [eth1...]
'''
brs = _os_dispatch('brshow')
if not brs:
return None
iflist = {}
for iface in args:
for br in brs:
try: # a bridge may not contain interfaces
if iface in brs[br]['interfaces']:
iflist[iface] = br
except Exception:
pass
return iflist | [
"def",
"find_interfaces",
"(",
"*",
"args",
")",
":",
"brs",
"=",
"_os_dispatch",
"(",
"'brshow'",
")",
"if",
"not",
"brs",
":",
"return",
"None",
"iflist",
"=",
"{",
"}",
"for",
"iface",
"in",
"args",
":",
"for",
"br",
"in",
"brs",
":",
"try",
":"... | Returns the bridge to which the interfaces are bond to
CLI Example:
.. code-block:: bash
salt '*' bridge.find_interfaces eth0 [eth1...] | [
"Returns",
"the",
"bridge",
"to",
"which",
"the",
"interfaces",
"are",
"bond",
"to"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L380-L404 | train |
saltstack/salt | salt/modules/bridge.py | stp | def stp(br=None, state='disable', iface=None):
'''
Sets Spanning Tree Protocol state for a bridge
CLI Example:
.. code-block:: bash
salt '*' bridge.stp br0 enable
salt '*' bridge.stp br0 disable
For BSD-like operating systems, it is required to add the interface on
which to enable the STP.
CLI Example:
.. code-block:: bash
salt '*' bridge.stp bridge0 enable fxp0
salt '*' bridge.stp bridge0 disable fxp0
'''
kernel = __grains__['kernel']
if kernel == 'Linux':
states = {'enable': 'on', 'disable': 'off'}
return _os_dispatch('stp', br, states[state])
elif kernel in SUPPORTED_BSD_LIKE:
states = {'enable': 'stp', 'disable': '-stp'}
return _os_dispatch('stp', br, states[state], iface)
else:
return False | python | def stp(br=None, state='disable', iface=None):
'''
Sets Spanning Tree Protocol state for a bridge
CLI Example:
.. code-block:: bash
salt '*' bridge.stp br0 enable
salt '*' bridge.stp br0 disable
For BSD-like operating systems, it is required to add the interface on
which to enable the STP.
CLI Example:
.. code-block:: bash
salt '*' bridge.stp bridge0 enable fxp0
salt '*' bridge.stp bridge0 disable fxp0
'''
kernel = __grains__['kernel']
if kernel == 'Linux':
states = {'enable': 'on', 'disable': 'off'}
return _os_dispatch('stp', br, states[state])
elif kernel in SUPPORTED_BSD_LIKE:
states = {'enable': 'stp', 'disable': '-stp'}
return _os_dispatch('stp', br, states[state], iface)
else:
return False | [
"def",
"stp",
"(",
"br",
"=",
"None",
",",
"state",
"=",
"'disable'",
",",
"iface",
"=",
"None",
")",
":",
"kernel",
"=",
"__grains__",
"[",
"'kernel'",
"]",
"if",
"kernel",
"==",
"'Linux'",
":",
"states",
"=",
"{",
"'enable'",
":",
"'on'",
",",
"'... | Sets Spanning Tree Protocol state for a bridge
CLI Example:
.. code-block:: bash
salt '*' bridge.stp br0 enable
salt '*' bridge.stp br0 disable
For BSD-like operating systems, it is required to add the interface on
which to enable the STP.
CLI Example:
.. code-block:: bash
salt '*' bridge.stp bridge0 enable fxp0
salt '*' bridge.stp bridge0 disable fxp0 | [
"Sets",
"Spanning",
"Tree",
"Protocol",
"state",
"for",
"a",
"bridge"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bridge.py#L459-L488 | train |
saltstack/salt | salt/utils/decorators/state.py | OutputUnifier.content_check | def content_check(self, result):
'''
Checks for specific types in the state output.
Raises an Exception in case particular rule is broken.
:param result:
:return:
'''
if not isinstance(result, dict):
err_msg = 'Malformed state return. Data must be a dictionary type.'
elif not isinstance(result.get('changes'), dict):
err_msg = "'Changes' should be a dictionary."
else:
missing = []
for val in ['name', 'result', 'changes', 'comment']:
if val not in result:
missing.append(val)
if missing:
err_msg = 'The following keys were not present in the state return: {0}.'.format(', '.join(missing))
else:
err_msg = None
if err_msg:
raise SaltException(err_msg)
return result | python | def content_check(self, result):
'''
Checks for specific types in the state output.
Raises an Exception in case particular rule is broken.
:param result:
:return:
'''
if not isinstance(result, dict):
err_msg = 'Malformed state return. Data must be a dictionary type.'
elif not isinstance(result.get('changes'), dict):
err_msg = "'Changes' should be a dictionary."
else:
missing = []
for val in ['name', 'result', 'changes', 'comment']:
if val not in result:
missing.append(val)
if missing:
err_msg = 'The following keys were not present in the state return: {0}.'.format(', '.join(missing))
else:
err_msg = None
if err_msg:
raise SaltException(err_msg)
return result | [
"def",
"content_check",
"(",
"self",
",",
"result",
")",
":",
"if",
"not",
"isinstance",
"(",
"result",
",",
"dict",
")",
":",
"err_msg",
"=",
"'Malformed state return. Data must be a dictionary type.'",
"elif",
"not",
"isinstance",
"(",
"result",
".",
"get",
"(... | Checks for specific types in the state output.
Raises an Exception in case particular rule is broken.
:param result:
:return: | [
"Checks",
"for",
"specific",
"types",
"in",
"the",
"state",
"output",
".",
"Raises",
"an",
"Exception",
"in",
"case",
"particular",
"rule",
"is",
"broken",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/state.py#L48-L73 | train |
saltstack/salt | salt/utils/decorators/state.py | OutputUnifier.unify | def unify(self, result):
'''
While comments as a list are allowed,
comments needs to be strings for backward compatibility.
See such claim here: https://github.com/saltstack/salt/pull/43070
Rules applied:
- 'comment' is joined into a multi-line string, in case the value is a list.
- 'result' should be always either True, False or None.
:param result:
:return:
'''
if isinstance(result.get('comment'), list):
result['comment'] = u'\n'.join([
salt.utils.stringutils.to_unicode(elm) for elm in result['comment']
])
if result.get('result') is not None:
result['result'] = bool(result['result'])
return result | python | def unify(self, result):
'''
While comments as a list are allowed,
comments needs to be strings for backward compatibility.
See such claim here: https://github.com/saltstack/salt/pull/43070
Rules applied:
- 'comment' is joined into a multi-line string, in case the value is a list.
- 'result' should be always either True, False or None.
:param result:
:return:
'''
if isinstance(result.get('comment'), list):
result['comment'] = u'\n'.join([
salt.utils.stringutils.to_unicode(elm) for elm in result['comment']
])
if result.get('result') is not None:
result['result'] = bool(result['result'])
return result | [
"def",
"unify",
"(",
"self",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
".",
"get",
"(",
"'comment'",
")",
",",
"list",
")",
":",
"result",
"[",
"'comment'",
"]",
"=",
"u'\\n'",
".",
"join",
"(",
"[",
"salt",
".",
"utils",
".",
"... | While comments as a list are allowed,
comments needs to be strings for backward compatibility.
See such claim here: https://github.com/saltstack/salt/pull/43070
Rules applied:
- 'comment' is joined into a multi-line string, in case the value is a list.
- 'result' should be always either True, False or None.
:param result:
:return: | [
"While",
"comments",
"as",
"a",
"list",
"are",
"allowed",
"comments",
"needs",
"to",
"be",
"strings",
"for",
"backward",
"compatibility",
".",
"See",
"such",
"claim",
"here",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"saltstack",
"/",
"salt",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/state.py#L75-L95 | train |
saltstack/salt | salt/modules/mac_xattr.py | list_ | def list_(path, **kwargs):
'''
List all of the extended attributes on the given file/directory
:param str path: The file(s) to get attributes from
:param bool hex: Return the values with forced hexadecimal values
:return: A dictionary containing extended attributes and values for the
given file
:rtype: dict
:raises: CommandExecutionError on file not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.list /path/to/file
salt '*' xattr.list /path/to/file hex=True
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
hex_ = kwargs.pop('hex', False)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
cmd = ['xattr', path]
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'No such file' in exc.strerror:
raise CommandExecutionError('File not found: {0}'.format(path))
raise CommandExecutionError('Unknown Error: {0}'.format(exc.strerror))
if not ret:
return {}
attrs_ids = ret.split("\n")
attrs = {}
for id_ in attrs_ids:
attrs[id_] = read(path, id_, **{'hex': hex_})
return attrs | python | def list_(path, **kwargs):
'''
List all of the extended attributes on the given file/directory
:param str path: The file(s) to get attributes from
:param bool hex: Return the values with forced hexadecimal values
:return: A dictionary containing extended attributes and values for the
given file
:rtype: dict
:raises: CommandExecutionError on file not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.list /path/to/file
salt '*' xattr.list /path/to/file hex=True
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
hex_ = kwargs.pop('hex', False)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
cmd = ['xattr', path]
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'No such file' in exc.strerror:
raise CommandExecutionError('File not found: {0}'.format(path))
raise CommandExecutionError('Unknown Error: {0}'.format(exc.strerror))
if not ret:
return {}
attrs_ids = ret.split("\n")
attrs = {}
for id_ in attrs_ids:
attrs[id_] = read(path, id_, **{'hex': hex_})
return attrs | [
"def",
"list_",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"hex_",
"=",
"kwargs",
".",
"pop",
"(",
"'hex'",
",",
"False",
")",
"if",
"kwargs... | List all of the extended attributes on the given file/directory
:param str path: The file(s) to get attributes from
:param bool hex: Return the values with forced hexadecimal values
:return: A dictionary containing extended attributes and values for the
given file
:rtype: dict
:raises: CommandExecutionError on file not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.list /path/to/file
salt '*' xattr.list /path/to/file hex=True | [
"List",
"all",
"of",
"the",
"extended",
"attributes",
"on",
"the",
"given",
"file",
"/",
"directory"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_xattr.py#L36-L79 | train |
saltstack/salt | salt/modules/mac_xattr.py | read | def read(path, attribute, **kwargs):
'''
Read the given attributes on the given file/directory
:param str path: The file to get attributes from
:param str attribute: The attribute to read
:param bool hex: Return the values with forced hexadecimal values
:return: A string containing the value of the named attribute
:rtype: str
:raises: CommandExecutionError on file not found, attribute not found, and
any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.read /path/to/file com.test.attr
salt '*' xattr.read /path/to/file com.test.attr hex=True
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
hex_ = kwargs.pop('hex', False)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
cmd = ['xattr', '-p']
if hex_:
cmd.append('-x')
cmd.extend([attribute, path])
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'No such file' in exc.strerror:
raise CommandExecutionError('File not found: {0}'.format(path))
if 'No such xattr' in exc.strerror:
raise CommandExecutionError('Attribute not found: {0}'.format(attribute))
raise CommandExecutionError('Unknown Error: {0}'.format(exc.strerror))
return ret | python | def read(path, attribute, **kwargs):
'''
Read the given attributes on the given file/directory
:param str path: The file to get attributes from
:param str attribute: The attribute to read
:param bool hex: Return the values with forced hexadecimal values
:return: A string containing the value of the named attribute
:rtype: str
:raises: CommandExecutionError on file not found, attribute not found, and
any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.read /path/to/file com.test.attr
salt '*' xattr.read /path/to/file com.test.attr hex=True
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
hex_ = kwargs.pop('hex', False)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
cmd = ['xattr', '-p']
if hex_:
cmd.append('-x')
cmd.extend([attribute, path])
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'No such file' in exc.strerror:
raise CommandExecutionError('File not found: {0}'.format(path))
if 'No such xattr' in exc.strerror:
raise CommandExecutionError('Attribute not found: {0}'.format(attribute))
raise CommandExecutionError('Unknown Error: {0}'.format(exc.strerror))
return ret | [
"def",
"read",
"(",
"path",
",",
"attribute",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"hex_",
"=",
"kwargs",
".",
"pop",
"(",
"'hex'",
",",
"False",
"... | Read the given attributes on the given file/directory
:param str path: The file to get attributes from
:param str attribute: The attribute to read
:param bool hex: Return the values with forced hexadecimal values
:return: A string containing the value of the named attribute
:rtype: str
:raises: CommandExecutionError on file not found, attribute not found, and
any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.read /path/to/file com.test.attr
salt '*' xattr.read /path/to/file com.test.attr hex=True | [
"Read",
"the",
"given",
"attributes",
"on",
"the",
"given",
"file",
"/",
"directory"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_xattr.py#L82-L124 | train |
saltstack/salt | salt/modules/mac_xattr.py | delete | def delete(path, attribute):
'''
Removes the given attribute from the file
:param str path: The file(s) to get attributes from
:param str attribute: The attribute name to be deleted from the
file/directory
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on file not found, attribute not found, and
any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.delete /path/to/file "com.test.attr"
'''
cmd = 'xattr -d "{0}" "{1}"'.format(attribute, path)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'No such file' in exc.strerror:
raise CommandExecutionError('File not found: {0}'.format(path))
if 'No such xattr' in exc.strerror:
raise CommandExecutionError('Attribute not found: {0}'.format(attribute))
raise CommandExecutionError('Unknown Error: {0}'.format(exc.strerror))
return attribute not in list_(path) | python | def delete(path, attribute):
'''
Removes the given attribute from the file
:param str path: The file(s) to get attributes from
:param str attribute: The attribute name to be deleted from the
file/directory
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on file not found, attribute not found, and
any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.delete /path/to/file "com.test.attr"
'''
cmd = 'xattr -d "{0}" "{1}"'.format(attribute, path)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'No such file' in exc.strerror:
raise CommandExecutionError('File not found: {0}'.format(path))
if 'No such xattr' in exc.strerror:
raise CommandExecutionError('Attribute not found: {0}'.format(attribute))
raise CommandExecutionError('Unknown Error: {0}'.format(exc.strerror))
return attribute not in list_(path) | [
"def",
"delete",
"(",
"path",
",",
"attribute",
")",
":",
"cmd",
"=",
"'xattr -d \"{0}\" \"{1}\"'",
".",
"format",
"(",
"attribute",
",",
"path",
")",
"try",
":",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
"(",
"cmd",
")",
"exce... | Removes the given attribute from the file
:param str path: The file(s) to get attributes from
:param str attribute: The attribute name to be deleted from the
file/directory
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on file not found, attribute not found, and
any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.delete /path/to/file "com.test.attr" | [
"Removes",
"the",
"given",
"attribute",
"from",
"the",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_xattr.py#L171-L202 | train |
saltstack/salt | salt/modules/mac_xattr.py | clear | def clear(path):
'''
Causes the all attributes on the file/directory to be removed
:param str path: The file(s) to get attributes from
:return: True if successful, otherwise False
:raises: CommandExecutionError on file not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.delete /path/to/file "com.test.attr"
'''
cmd = 'xattr -c "{0}"'.format(path)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'No such file' in exc.strerror:
raise CommandExecutionError('File not found: {0}'.format(path))
raise CommandExecutionError('Unknown Error: {0}'.format(exc.strerror))
return list_(path) == {} | python | def clear(path):
'''
Causes the all attributes on the file/directory to be removed
:param str path: The file(s) to get attributes from
:return: True if successful, otherwise False
:raises: CommandExecutionError on file not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.delete /path/to/file "com.test.attr"
'''
cmd = 'xattr -c "{0}"'.format(path)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'No such file' in exc.strerror:
raise CommandExecutionError('File not found: {0}'.format(path))
raise CommandExecutionError('Unknown Error: {0}'.format(exc.strerror))
return list_(path) == {} | [
"def",
"clear",
"(",
"path",
")",
":",
"cmd",
"=",
"'xattr -c \"{0}\"'",
".",
"format",
"(",
"path",
")",
"try",
":",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
"(",
"cmd",
")",
"except",
"CommandExecutionError",
"as",
"exc",
":... | Causes the all attributes on the file/directory to be removed
:param str path: The file(s) to get attributes from
:return: True if successful, otherwise False
:raises: CommandExecutionError on file not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' xattr.delete /path/to/file "com.test.attr" | [
"Causes",
"the",
"all",
"attributes",
"on",
"the",
"file",
"/",
"directory",
"to",
"be",
"removed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_xattr.py#L205-L229 | train |
saltstack/salt | salt/modules/rallydev.py | _get_token | def _get_token():
'''
Get an auth token
'''
username = __opts__.get('rallydev', {}).get('username', None)
password = __opts__.get('rallydev', {}).get('password', None)
path = 'https://rally1.rallydev.com/slm/webservice/v2.0/security/authorize'
result = salt.utils.http.query(
path,
decode=True,
decode_type='json',
text=True,
status=True,
username=username,
password=password,
cookies=True,
persist_session=True,
opts=__opts__,
)
if 'dict' not in result:
return None
return result['dict']['OperationResult']['SecurityToken'] | python | def _get_token():
'''
Get an auth token
'''
username = __opts__.get('rallydev', {}).get('username', None)
password = __opts__.get('rallydev', {}).get('password', None)
path = 'https://rally1.rallydev.com/slm/webservice/v2.0/security/authorize'
result = salt.utils.http.query(
path,
decode=True,
decode_type='json',
text=True,
status=True,
username=username,
password=password,
cookies=True,
persist_session=True,
opts=__opts__,
)
if 'dict' not in result:
return None
return result['dict']['OperationResult']['SecurityToken'] | [
"def",
"_get_token",
"(",
")",
":",
"username",
"=",
"__opts__",
".",
"get",
"(",
"'rallydev'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'username'",
",",
"None",
")",
"password",
"=",
"__opts__",
".",
"get",
"(",
"'rallydev'",
",",
"{",
"}",
")",
"."... | Get an auth token | [
"Get",
"an",
"auth",
"token"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rallydev.py#L39-L61 | train |
saltstack/salt | salt/modules/rallydev.py | _query | def _query(action=None,
command=None,
args=None,
method='GET',
header_dict=None,
data=None):
'''
Make a web call to RallyDev.
'''
token = _get_token()
username = __opts__.get('rallydev', {}).get('username', None)
password = __opts__.get('rallydev', {}).get('password', None)
path = 'https://rally1.rallydev.com/slm/webservice/v2.0/'
if action:
path += action
if command:
path += '/{0}'.format(command)
log.debug('RallyDev URL: %s', path)
if not isinstance(args, dict):
args = {}
args['key'] = token
if header_dict is None:
header_dict = {'Content-type': 'application/json'}
if method != 'POST':
header_dict['Accept'] = 'application/json'
decode = True
if method == 'DELETE':
decode = False
return_content = None
result = salt.utils.http.query(
path,
method,
params=args,
data=data,
header_dict=header_dict,
decode=decode,
decode_type='json',
text=True,
status=True,
username=username,
password=password,
cookies=True,
persist_session=True,
opts=__opts__,
)
log.debug('RallyDev Response Status Code: %s', result['status'])
if 'error' in result:
log.error(result['error'])
return [result['status'], result['error']]
return [result['status'], result.get('dict', {})] | python | def _query(action=None,
command=None,
args=None,
method='GET',
header_dict=None,
data=None):
'''
Make a web call to RallyDev.
'''
token = _get_token()
username = __opts__.get('rallydev', {}).get('username', None)
password = __opts__.get('rallydev', {}).get('password', None)
path = 'https://rally1.rallydev.com/slm/webservice/v2.0/'
if action:
path += action
if command:
path += '/{0}'.format(command)
log.debug('RallyDev URL: %s', path)
if not isinstance(args, dict):
args = {}
args['key'] = token
if header_dict is None:
header_dict = {'Content-type': 'application/json'}
if method != 'POST':
header_dict['Accept'] = 'application/json'
decode = True
if method == 'DELETE':
decode = False
return_content = None
result = salt.utils.http.query(
path,
method,
params=args,
data=data,
header_dict=header_dict,
decode=decode,
decode_type='json',
text=True,
status=True,
username=username,
password=password,
cookies=True,
persist_session=True,
opts=__opts__,
)
log.debug('RallyDev Response Status Code: %s', result['status'])
if 'error' in result:
log.error(result['error'])
return [result['status'], result['error']]
return [result['status'], result.get('dict', {})] | [
"def",
"_query",
"(",
"action",
"=",
"None",
",",
"command",
"=",
"None",
",",
"args",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"header_dict",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"token",
"=",
"_get_token",
"(",
")",
"username",
... | Make a web call to RallyDev. | [
"Make",
"a",
"web",
"call",
"to",
"RallyDev",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rallydev.py#L64-L123 | train |
saltstack/salt | salt/modules/rallydev.py | query_item | def query_item(name, query_string, order='Rank'):
'''
Query a type of record for one or more items. Requires a valid query string.
See https://rally1.rallydev.com/slm/doc/webservice/introduction.jsp for
information on query syntax.
CLI Example:
.. code-block:: bash
salt myminion rallydev.query_<item name> <query string> [<order>]
salt myminion rallydev.query_task '(Name contains github)'
salt myminion rallydev.query_task '(Name contains reactor)' Rank
'''
status, result = _query(
action=name,
args={'query': query_string,
'order': order}
)
return result | python | def query_item(name, query_string, order='Rank'):
'''
Query a type of record for one or more items. Requires a valid query string.
See https://rally1.rallydev.com/slm/doc/webservice/introduction.jsp for
information on query syntax.
CLI Example:
.. code-block:: bash
salt myminion rallydev.query_<item name> <query string> [<order>]
salt myminion rallydev.query_task '(Name contains github)'
salt myminion rallydev.query_task '(Name contains reactor)' Rank
'''
status, result = _query(
action=name,
args={'query': query_string,
'order': order}
)
return result | [
"def",
"query_item",
"(",
"name",
",",
"query_string",
",",
"order",
"=",
"'Rank'",
")",
":",
"status",
",",
"result",
"=",
"_query",
"(",
"action",
"=",
"name",
",",
"args",
"=",
"{",
"'query'",
":",
"query_string",
",",
"'order'",
":",
"order",
"}",
... | Query a type of record for one or more items. Requires a valid query string.
See https://rally1.rallydev.com/slm/doc/webservice/introduction.jsp for
information on query syntax.
CLI Example:
.. code-block:: bash
salt myminion rallydev.query_<item name> <query string> [<order>]
salt myminion rallydev.query_task '(Name contains github)'
salt myminion rallydev.query_task '(Name contains reactor)' Rank | [
"Query",
"a",
"type",
"of",
"record",
"for",
"one",
"or",
"more",
"items",
".",
"Requires",
"a",
"valid",
"query",
"string",
".",
"See",
"https",
":",
"//",
"rally1",
".",
"rallydev",
".",
"com",
"/",
"slm",
"/",
"doc",
"/",
"webservice",
"/",
"intro... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rallydev.py#L142-L161 | train |
saltstack/salt | salt/modules/rallydev.py | show_item | def show_item(name, id_):
'''
Show an item
CLI Example:
.. code-block:: bash
salt myminion rallydev.show_<item name> <item id>
'''
status, result = _query(action=name, command=id_)
return result | python | def show_item(name, id_):
'''
Show an item
CLI Example:
.. code-block:: bash
salt myminion rallydev.show_<item name> <item id>
'''
status, result = _query(action=name, command=id_)
return result | [
"def",
"show_item",
"(",
"name",
",",
"id_",
")",
":",
"status",
",",
"result",
"=",
"_query",
"(",
"action",
"=",
"name",
",",
"command",
"=",
"id_",
")",
"return",
"result"
] | Show an item
CLI Example:
.. code-block:: bash
salt myminion rallydev.show_<item name> <item id> | [
"Show",
"an",
"item"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rallydev.py#L164-L175 | train |
saltstack/salt | salt/modules/rallydev.py | update_item | def update_item(name, id_, field=None, value=None, postdata=None):
'''
Update an item. Either a field and a value, or a chunk of POST data, may be
used, but not both.
CLI Example:
.. code-block:: bash
salt myminion rallydev.update_<item name> <item id> field=<field> value=<value>
salt myminion rallydev.update_<item name> <item id> postdata=<post data>
'''
if field and value:
if postdata:
raise SaltInvocationError('Either a field and a value, or a chunk '
'of POST data, may be specified, but not both.')
postdata = {name.title(): {field: value}}
if postdata is None:
raise SaltInvocationError('Either a field and a value, or a chunk of '
'POST data must be specified.')
status, result = _query(
action=name,
command=id_,
method='POST',
data=salt.utils.json.dumps(postdata),
)
return result | python | def update_item(name, id_, field=None, value=None, postdata=None):
'''
Update an item. Either a field and a value, or a chunk of POST data, may be
used, but not both.
CLI Example:
.. code-block:: bash
salt myminion rallydev.update_<item name> <item id> field=<field> value=<value>
salt myminion rallydev.update_<item name> <item id> postdata=<post data>
'''
if field and value:
if postdata:
raise SaltInvocationError('Either a field and a value, or a chunk '
'of POST data, may be specified, but not both.')
postdata = {name.title(): {field: value}}
if postdata is None:
raise SaltInvocationError('Either a field and a value, or a chunk of '
'POST data must be specified.')
status, result = _query(
action=name,
command=id_,
method='POST',
data=salt.utils.json.dumps(postdata),
)
return result | [
"def",
"update_item",
"(",
"name",
",",
"id_",
",",
"field",
"=",
"None",
",",
"value",
"=",
"None",
",",
"postdata",
"=",
"None",
")",
":",
"if",
"field",
"and",
"value",
":",
"if",
"postdata",
":",
"raise",
"SaltInvocationError",
"(",
"'Either a field ... | Update an item. Either a field and a value, or a chunk of POST data, may be
used, but not both.
CLI Example:
.. code-block:: bash
salt myminion rallydev.update_<item name> <item id> field=<field> value=<value>
salt myminion rallydev.update_<item name> <item id> postdata=<post data> | [
"Update",
"an",
"item",
".",
"Either",
"a",
"field",
"and",
"a",
"value",
"or",
"a",
"chunk",
"of",
"POST",
"data",
"may",
"be",
"used",
"but",
"not",
"both",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rallydev.py#L178-L207 | train |
saltstack/salt | salt/_compat.py | text_ | def text_(s, encoding='latin-1', errors='strict'):
'''
If ``s`` is an instance of ``binary_type``, return
``s.decode(encoding, errors)``, otherwise return ``s``
'''
return s.decode(encoding, errors) if isinstance(s, binary_type) else s | python | def text_(s, encoding='latin-1', errors='strict'):
'''
If ``s`` is an instance of ``binary_type``, return
``s.decode(encoding, errors)``, otherwise return ``s``
'''
return s.decode(encoding, errors) if isinstance(s, binary_type) else s | [
"def",
"text_",
"(",
"s",
",",
"encoding",
"=",
"'latin-1'",
",",
"errors",
"=",
"'strict'",
")",
":",
"return",
"s",
".",
"decode",
"(",
"encoding",
",",
"errors",
")",
"if",
"isinstance",
"(",
"s",
",",
"binary_type",
")",
"else",
"s"
] | If ``s`` is an instance of ``binary_type``, return
``s.decode(encoding, errors)``, otherwise return ``s`` | [
"If",
"s",
"is",
"an",
"instance",
"of",
"binary_type",
"return",
"s",
".",
"decode",
"(",
"encoding",
"errors",
")",
"otherwise",
"return",
"s"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/_compat.py#L60-L65 | train |
saltstack/salt | salt/_compat.py | ascii_native_ | def ascii_native_(s):
'''
Python 3: If ``s`` is an instance of ``text_type``, return
``s.encode('ascii')``, otherwise return ``str(s, 'ascii', 'strict')``
Python 2: If ``s`` is an instance of ``text_type``, return
``s.encode('ascii')``, otherwise return ``str(s)``
'''
if isinstance(s, text_type):
s = s.encode('ascii')
return str(s, 'ascii', 'strict') if PY3 else s | python | def ascii_native_(s):
'''
Python 3: If ``s`` is an instance of ``text_type``, return
``s.encode('ascii')``, otherwise return ``str(s, 'ascii', 'strict')``
Python 2: If ``s`` is an instance of ``text_type``, return
``s.encode('ascii')``, otherwise return ``str(s)``
'''
if isinstance(s, text_type):
s = s.encode('ascii')
return str(s, 'ascii', 'strict') if PY3 else s | [
"def",
"ascii_native_",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"'ascii'",
")",
"return",
"str",
"(",
"s",
",",
"'ascii'",
",",
"'strict'",
")",
"if",
"PY3",
"else",
"s"
] | Python 3: If ``s`` is an instance of ``text_type``, return
``s.encode('ascii')``, otherwise return ``str(s, 'ascii', 'strict')``
Python 2: If ``s`` is an instance of ``text_type``, return
``s.encode('ascii')``, otherwise return ``str(s)`` | [
"Python",
"3",
":",
"If",
"s",
"is",
"an",
"instance",
"of",
"text_type",
"return",
"s",
".",
"encode",
"(",
"ascii",
")",
"otherwise",
"return",
"str",
"(",
"s",
"ascii",
"strict",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/_compat.py#L76-L87 | train |
saltstack/salt | salt/_compat.py | native_ | def native_(s, encoding='latin-1', errors='strict'):
'''
Python 3: If ``s`` is an instance of ``text_type``, return ``s``, otherwise
return ``str(s, encoding, errors)``
Python 2: If ``s`` is an instance of ``text_type``, return
``s.encode(encoding, errors)``, otherwise return ``str(s)``
'''
if PY3:
out = s if isinstance(s, text_type) else str(s, encoding, errors)
else:
out = s.encode(encoding, errors) if isinstance(s, text_type) else str(s)
return out | python | def native_(s, encoding='latin-1', errors='strict'):
'''
Python 3: If ``s`` is an instance of ``text_type``, return ``s``, otherwise
return ``str(s, encoding, errors)``
Python 2: If ``s`` is an instance of ``text_type``, return
``s.encode(encoding, errors)``, otherwise return ``str(s)``
'''
if PY3:
out = s if isinstance(s, text_type) else str(s, encoding, errors)
else:
out = s.encode(encoding, errors) if isinstance(s, text_type) else str(s)
return out | [
"def",
"native_",
"(",
"s",
",",
"encoding",
"=",
"'latin-1'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"PY3",
":",
"out",
"=",
"s",
"if",
"isinstance",
"(",
"s",
",",
"text_type",
")",
"else",
"str",
"(",
"s",
",",
"encoding",
",",
"errors"... | Python 3: If ``s`` is an instance of ``text_type``, return ``s``, otherwise
return ``str(s, encoding, errors)``
Python 2: If ``s`` is an instance of ``text_type``, return
``s.encode(encoding, errors)``, otherwise return ``str(s)`` | [
"Python",
"3",
":",
"If",
"s",
"is",
"an",
"instance",
"of",
"text_type",
"return",
"s",
"otherwise",
"return",
"str",
"(",
"s",
"encoding",
"errors",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/_compat.py#L90-L103 | train |
saltstack/salt | salt/_compat.py | IPv6AddressScoped._is_packed_binary | def _is_packed_binary(self, data):
'''
Check if data is hexadecimal packed
:param data:
:return:
'''
packed = False
if isinstance(data, bytes) and len(data) == 16 and b':' not in data:
try:
packed = bool(int(binascii.hexlify(data), 16))
except (ValueError, TypeError):
pass
return packed | python | def _is_packed_binary(self, data):
'''
Check if data is hexadecimal packed
:param data:
:return:
'''
packed = False
if isinstance(data, bytes) and len(data) == 16 and b':' not in data:
try:
packed = bool(int(binascii.hexlify(data), 16))
except (ValueError, TypeError):
pass
return packed | [
"def",
"_is_packed_binary",
"(",
"self",
",",
"data",
")",
":",
"packed",
"=",
"False",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"and",
"len",
"(",
"data",
")",
"==",
"16",
"and",
"b':'",
"not",
"in",
"data",
":",
"try",
":",
"packed",
"... | Check if data is hexadecimal packed
:param data:
:return: | [
"Check",
"if",
"data",
"is",
"hexadecimal",
"packed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/_compat.py#L183-L197 | train |
saltstack/salt | salt/modules/win_iis.py | _get_binding_info | def _get_binding_info(host_header='', ip_address='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation
format. Binding Information specifies information to communicate with a
site. It includes the IP address, the port number, and an optional host
header (usually a host name) to communicate with the site.
Args:
host_header (str): Usually a hostname
ip_address (str): The IP address
port (int): The port
Returns:
str: A properly formatted bindingInformation string (IP:port:hostheader)
eg: 192.168.0.12:80:www.contoso.com
'''
return ':'.join([ip_address, six.text_type(port),
host_header.replace(' ', '')]) | python | def _get_binding_info(host_header='', ip_address='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation
format. Binding Information specifies information to communicate with a
site. It includes the IP address, the port number, and an optional host
header (usually a host name) to communicate with the site.
Args:
host_header (str): Usually a hostname
ip_address (str): The IP address
port (int): The port
Returns:
str: A properly formatted bindingInformation string (IP:port:hostheader)
eg: 192.168.0.12:80:www.contoso.com
'''
return ':'.join([ip_address, six.text_type(port),
host_header.replace(' ', '')]) | [
"def",
"_get_binding_info",
"(",
"host_header",
"=",
"''",
",",
"ip_address",
"=",
"'*'",
",",
"port",
"=",
"80",
")",
":",
"return",
"':'",
".",
"join",
"(",
"[",
"ip_address",
",",
"six",
".",
"text_type",
"(",
"port",
")",
",",
"host_header",
".",
... | Combine the host header, IP address, and TCP port into bindingInformation
format. Binding Information specifies information to communicate with a
site. It includes the IP address, the port number, and an optional host
header (usually a host name) to communicate with the site.
Args:
host_header (str): Usually a hostname
ip_address (str): The IP address
port (int): The port
Returns:
str: A properly formatted bindingInformation string (IP:port:hostheader)
eg: 192.168.0.12:80:www.contoso.com | [
"Combine",
"the",
"host",
"header",
"IP",
"address",
"and",
"TCP",
"port",
"into",
"bindingInformation",
"format",
".",
"Binding",
"Information",
"specifies",
"information",
"to",
"communicate",
"with",
"a",
"site",
".",
"It",
"includes",
"the",
"IP",
"address",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L56-L73 | train |
saltstack/salt | salt/modules/win_iis.py | _list_certs | def _list_certs(certificate_store='My'):
'''
List details of available certificates in the LocalMachine certificate
store.
Args:
certificate_store (str): The name of the certificate store on the local
machine.
Returns:
dict: A dictionary of certificates found in the store
'''
ret = dict()
blacklist_keys = ['DnsNameList', 'Thumbprint']
ps_cmd = ['Get-ChildItem',
'-Path', r"'Cert:\LocalMachine\{0}'".format(certificate_store),
'|',
'Select-Object DnsNameList, SerialNumber, Subject, Thumbprint, Version']
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
cert_info = dict()
for key in item:
if key not in blacklist_keys:
cert_info[key.lower()] = item[key]
cert_info['dnsnames'] = []
if item['DnsNameList']:
cert_info['dnsnames'] = [name['Unicode'] for name in item['DnsNameList']]
ret[item['Thumbprint']] = cert_info
return ret | python | def _list_certs(certificate_store='My'):
'''
List details of available certificates in the LocalMachine certificate
store.
Args:
certificate_store (str): The name of the certificate store on the local
machine.
Returns:
dict: A dictionary of certificates found in the store
'''
ret = dict()
blacklist_keys = ['DnsNameList', 'Thumbprint']
ps_cmd = ['Get-ChildItem',
'-Path', r"'Cert:\LocalMachine\{0}'".format(certificate_store),
'|',
'Select-Object DnsNameList, SerialNumber, Subject, Thumbprint, Version']
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
cert_info = dict()
for key in item:
if key not in blacklist_keys:
cert_info[key.lower()] = item[key]
cert_info['dnsnames'] = []
if item['DnsNameList']:
cert_info['dnsnames'] = [name['Unicode'] for name in item['DnsNameList']]
ret[item['Thumbprint']] = cert_info
return ret | [
"def",
"_list_certs",
"(",
"certificate_store",
"=",
"'My'",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"blacklist_keys",
"=",
"[",
"'DnsNameList'",
",",
"'Thumbprint'",
"]",
"ps_cmd",
"=",
"[",
"'Get-ChildItem'",
",",
"'-Path'",
",",
"r\"'Cert:\\LocalMachine\\{0}'... | List details of available certificates in the LocalMachine certificate
store.
Args:
certificate_store (str): The name of the certificate store on the local
machine.
Returns:
dict: A dictionary of certificates found in the store | [
"List",
"details",
"of",
"available",
"certificates",
"in",
"the",
"LocalMachine",
"certificate",
"store",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L76-L116 | train |
saltstack/salt | salt/modules/win_iis.py | _srvmgr | def _srvmgr(cmd, return_json=False):
'''
Execute a powershell command from the WebAdministration PS module.
Args:
cmd (list): The command to execute in a list
return_json (bool): True formats the return in JSON, False just returns
the output of the command.
Returns:
str: The output from the command
'''
if isinstance(cmd, list):
cmd = ' '.join(cmd)
if return_json:
cmd = 'ConvertTo-Json -Compress -Depth 4 -InputObject @({0})' \
''.format(cmd)
cmd = 'Import-Module WebAdministration; {0}'.format(cmd)
ret = __salt__['cmd.run_all'](cmd, shell='powershell', python_shell=True)
if ret['retcode'] != 0:
msg = 'Unable to execute command: {0}\nError: {1}' \
''.format(cmd, ret['stderr'])
log.error(msg)
return ret | python | def _srvmgr(cmd, return_json=False):
'''
Execute a powershell command from the WebAdministration PS module.
Args:
cmd (list): The command to execute in a list
return_json (bool): True formats the return in JSON, False just returns
the output of the command.
Returns:
str: The output from the command
'''
if isinstance(cmd, list):
cmd = ' '.join(cmd)
if return_json:
cmd = 'ConvertTo-Json -Compress -Depth 4 -InputObject @({0})' \
''.format(cmd)
cmd = 'Import-Module WebAdministration; {0}'.format(cmd)
ret = __salt__['cmd.run_all'](cmd, shell='powershell', python_shell=True)
if ret['retcode'] != 0:
msg = 'Unable to execute command: {0}\nError: {1}' \
''.format(cmd, ret['stderr'])
log.error(msg)
return ret | [
"def",
"_srvmgr",
"(",
"cmd",
",",
"return_json",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"cmd",
",",
"list",
")",
":",
"cmd",
"=",
"' '",
".",
"join",
"(",
"cmd",
")",
"if",
"return_json",
":",
"cmd",
"=",
"'ConvertTo-Json -Compress -Depth 4 -I... | Execute a powershell command from the WebAdministration PS module.
Args:
cmd (list): The command to execute in a list
return_json (bool): True formats the return in JSON, False just returns
the output of the command.
Returns:
str: The output from the command | [
"Execute",
"a",
"powershell",
"command",
"from",
"the",
"WebAdministration",
"PS",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L135-L163 | train |
saltstack/salt | salt/modules/win_iis.py | _collection_match_to_index | def _collection_match_to_index(pspath, colfilter, name, match):
'''
Returns index of collection item matching the match dictionary.
'''
collection = get_webconfiguration_settings(pspath, [{'name': name, 'filter': colfilter}])[0]['value']
for idx, collect_dict in enumerate(collection):
if all(item in collect_dict.items() for item in match.items()):
return idx
return -1 | python | def _collection_match_to_index(pspath, colfilter, name, match):
'''
Returns index of collection item matching the match dictionary.
'''
collection = get_webconfiguration_settings(pspath, [{'name': name, 'filter': colfilter}])[0]['value']
for idx, collect_dict in enumerate(collection):
if all(item in collect_dict.items() for item in match.items()):
return idx
return -1 | [
"def",
"_collection_match_to_index",
"(",
"pspath",
",",
"colfilter",
",",
"name",
",",
"match",
")",
":",
"collection",
"=",
"get_webconfiguration_settings",
"(",
"pspath",
",",
"[",
"{",
"'name'",
":",
"name",
",",
"'filter'",
":",
"colfilter",
"}",
"]",
"... | Returns index of collection item matching the match dictionary. | [
"Returns",
"index",
"of",
"collection",
"item",
"matching",
"the",
"match",
"dictionary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L166-L174 | train |
saltstack/salt | salt/modules/win_iis.py | _prepare_settings | def _prepare_settings(pspath, settings):
'''
Prepare settings before execution with get or set functions.
Removes settings with a match parameter when index is not found.
'''
prepared_settings = []
for setting in settings:
match = re.search(r'Collection\[(\{.*\})\]', setting['name'])
if match:
name = setting['name'][:match.start(1)-1]
match_dict = yaml.load(match.group(1))
index = _collection_match_to_index(pspath, setting['filter'], name, match_dict)
if index != -1:
setting['name'] = setting['name'].replace(match.group(1), str(index))
prepared_settings.append(setting)
else:
prepared_settings.append(setting)
return prepared_settings | python | def _prepare_settings(pspath, settings):
'''
Prepare settings before execution with get or set functions.
Removes settings with a match parameter when index is not found.
'''
prepared_settings = []
for setting in settings:
match = re.search(r'Collection\[(\{.*\})\]', setting['name'])
if match:
name = setting['name'][:match.start(1)-1]
match_dict = yaml.load(match.group(1))
index = _collection_match_to_index(pspath, setting['filter'], name, match_dict)
if index != -1:
setting['name'] = setting['name'].replace(match.group(1), str(index))
prepared_settings.append(setting)
else:
prepared_settings.append(setting)
return prepared_settings | [
"def",
"_prepare_settings",
"(",
"pspath",
",",
"settings",
")",
":",
"prepared_settings",
"=",
"[",
"]",
"for",
"setting",
"in",
"settings",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'Collection\\[(\\{.*\\})\\]'",
",",
"setting",
"[",
"'name'",
"]",
")... | Prepare settings before execution with get or set functions.
Removes settings with a match parameter when index is not found. | [
"Prepare",
"settings",
"before",
"execution",
"with",
"get",
"or",
"set",
"functions",
".",
"Removes",
"settings",
"with",
"a",
"match",
"parameter",
"when",
"index",
"is",
"not",
"found",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L177-L194 | train |
saltstack/salt | salt/modules/win_iis.py | list_sites | def list_sites():
'''
List all the currently deployed websites.
Returns:
dict: A dictionary of the IIS sites and their properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_sites
'''
ret = dict()
ps_cmd = ['Get-ChildItem',
'-Path', r"'IIS:\Sites'",
'|',
'Select-Object applicationPool, applicationDefaults, Bindings, ID, Name, PhysicalPath, State']
keep_keys = ('certificateHash', 'certificateStoreName', 'protocol', 'sslFlags')
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
bindings = dict()
for binding in item['bindings']['Collection']:
# Ignore bindings which do not have host names
if binding['protocol'] not in ['http', 'https']:
continue
filtered_binding = dict()
for key in binding:
if key in keep_keys:
filtered_binding.update({key.lower(): binding[key]})
binding_info = binding['bindingInformation'].split(':', 2)
ipaddress, port, hostheader = [element.strip() for element in binding_info]
filtered_binding.update({'hostheader': hostheader,
'ipaddress': ipaddress,
'port': port})
bindings[binding['bindingInformation']] = filtered_binding
# ApplicationDefaults
application_defaults = dict()
for attribute in item['applicationDefaults']['Attributes']:
application_defaults.update({attribute['Name']: attribute['Value']})
# ApplicationDefaults
ret[item['name']] = {'apppool': item['applicationPool'],
'bindings': bindings,
'applicationDefaults': application_defaults,
'id': item['id'],
'state': item['state'],
'sourcepath': item['physicalPath']}
if not ret:
log.warning('No sites found in output: %s', cmd_ret['stdout'])
return ret | python | def list_sites():
'''
List all the currently deployed websites.
Returns:
dict: A dictionary of the IIS sites and their properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_sites
'''
ret = dict()
ps_cmd = ['Get-ChildItem',
'-Path', r"'IIS:\Sites'",
'|',
'Select-Object applicationPool, applicationDefaults, Bindings, ID, Name, PhysicalPath, State']
keep_keys = ('certificateHash', 'certificateStoreName', 'protocol', 'sslFlags')
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
bindings = dict()
for binding in item['bindings']['Collection']:
# Ignore bindings which do not have host names
if binding['protocol'] not in ['http', 'https']:
continue
filtered_binding = dict()
for key in binding:
if key in keep_keys:
filtered_binding.update({key.lower(): binding[key]})
binding_info = binding['bindingInformation'].split(':', 2)
ipaddress, port, hostheader = [element.strip() for element in binding_info]
filtered_binding.update({'hostheader': hostheader,
'ipaddress': ipaddress,
'port': port})
bindings[binding['bindingInformation']] = filtered_binding
# ApplicationDefaults
application_defaults = dict()
for attribute in item['applicationDefaults']['Attributes']:
application_defaults.update({attribute['Name']: attribute['Value']})
# ApplicationDefaults
ret[item['name']] = {'apppool': item['applicationPool'],
'bindings': bindings,
'applicationDefaults': application_defaults,
'id': item['id'],
'state': item['state'],
'sourcepath': item['physicalPath']}
if not ret:
log.warning('No sites found in output: %s', cmd_ret['stdout'])
return ret | [
"def",
"list_sites",
"(",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"ps_cmd",
"=",
"[",
"'Get-ChildItem'",
",",
"'-Path'",
",",
"r\"'IIS:\\Sites'\"",
",",
"'|'",
",",
"'Select-Object applicationPool, applicationDefaults, Bindings, ID, Name, PhysicalPath, State'",
"]",
"ke... | List all the currently deployed websites.
Returns:
dict: A dictionary of the IIS sites and their properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_sites | [
"List",
"all",
"the",
"currently",
"deployed",
"websites",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L197-L264 | train |
saltstack/salt | salt/modules/win_iis.py | create_site | def create_site(name, sourcepath, apppool='', hostheader='',
ipaddress='*', port=80, protocol='http', preload=''):
'''
Create a basic website in IIS.
.. note::
This function only validates against the site name, and will return True
even if the site already exists with a different configuration. It will
not modify the configuration of an existing site.
Args:
name (str): The IIS site name.
sourcepath (str): The physical path of the IIS site.
apppool (str): The name of the IIS application pool.
hostheader (str): The host header of the binding. Usually the hostname
or website name, ie: www.contoso.com
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
protocol (str): The application protocol of the binding. (http, https,
etc.)
preload (bool): Whether preloading should be enabled
Returns:
bool: True if successful, otherwise False.
.. note::
If an application pool is specified, and that application pool does not
already exist, it will be created.
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_site name='My Test Site' sourcepath='c:\\stage' apppool='TestPool' preload=True
'''
protocol = six.text_type(protocol).lower()
site_path = r'IIS:\Sites\{0}'.format(name)
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_sites = list_sites()
if name in current_sites:
log.debug("Site '%s' already present.", name)
return True
if protocol not in _VALID_PROTOCOLS:
message = ("Invalid protocol '{0}' specified. Valid formats:"
' {1}').format(protocol, _VALID_PROTOCOLS)
raise SaltInvocationError(message)
ps_cmd = ['New-Item',
'-Path', r"'{0}'".format(site_path),
'-PhysicalPath', r"'{0}'".format(sourcepath),
'-Bindings', "@{{ protocol='{0}'; bindingInformation='{1}' }};"
"".format(protocol, binding_info)]
if apppool:
if apppool in list_apppools():
log.debug('Utilizing pre-existing application pool: %s',
apppool)
else:
log.debug('Application pool will be created: %s', apppool)
create_apppool(apppool)
ps_cmd.extend(['Set-ItemProperty',
'-Path', "'{0}'".format(site_path),
'-Name', 'ApplicationPool',
'-Value', "'{0}';".format(apppool)])
if preload:
ps_cmd.extend(['Set-ItemProperty',
'-Path', "'{0}'".format(site_path),
'-Name', 'applicationDefaults.preloadEnabled',
'-Value', "{0};".format(preload)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create site: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
log.debug('Site created successfully: %s', name)
return True | python | def create_site(name, sourcepath, apppool='', hostheader='',
ipaddress='*', port=80, protocol='http', preload=''):
'''
Create a basic website in IIS.
.. note::
This function only validates against the site name, and will return True
even if the site already exists with a different configuration. It will
not modify the configuration of an existing site.
Args:
name (str): The IIS site name.
sourcepath (str): The physical path of the IIS site.
apppool (str): The name of the IIS application pool.
hostheader (str): The host header of the binding. Usually the hostname
or website name, ie: www.contoso.com
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
protocol (str): The application protocol of the binding. (http, https,
etc.)
preload (bool): Whether preloading should be enabled
Returns:
bool: True if successful, otherwise False.
.. note::
If an application pool is specified, and that application pool does not
already exist, it will be created.
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_site name='My Test Site' sourcepath='c:\\stage' apppool='TestPool' preload=True
'''
protocol = six.text_type(protocol).lower()
site_path = r'IIS:\Sites\{0}'.format(name)
binding_info = _get_binding_info(hostheader, ipaddress, port)
current_sites = list_sites()
if name in current_sites:
log.debug("Site '%s' already present.", name)
return True
if protocol not in _VALID_PROTOCOLS:
message = ("Invalid protocol '{0}' specified. Valid formats:"
' {1}').format(protocol, _VALID_PROTOCOLS)
raise SaltInvocationError(message)
ps_cmd = ['New-Item',
'-Path', r"'{0}'".format(site_path),
'-PhysicalPath', r"'{0}'".format(sourcepath),
'-Bindings', "@{{ protocol='{0}'; bindingInformation='{1}' }};"
"".format(protocol, binding_info)]
if apppool:
if apppool in list_apppools():
log.debug('Utilizing pre-existing application pool: %s',
apppool)
else:
log.debug('Application pool will be created: %s', apppool)
create_apppool(apppool)
ps_cmd.extend(['Set-ItemProperty',
'-Path', "'{0}'".format(site_path),
'-Name', 'ApplicationPool',
'-Value', "'{0}';".format(apppool)])
if preload:
ps_cmd.extend(['Set-ItemProperty',
'-Path', "'{0}'".format(site_path),
'-Name', 'applicationDefaults.preloadEnabled',
'-Value', "{0};".format(preload)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create site: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
log.debug('Site created successfully: %s', name)
return True | [
"def",
"create_site",
"(",
"name",
",",
"sourcepath",
",",
"apppool",
"=",
"''",
",",
"hostheader",
"=",
"''",
",",
"ipaddress",
"=",
"'*'",
",",
"port",
"=",
"80",
",",
"protocol",
"=",
"'http'",
",",
"preload",
"=",
"''",
")",
":",
"protocol",
"=",... | Create a basic website in IIS.
.. note::
This function only validates against the site name, and will return True
even if the site already exists with a different configuration. It will
not modify the configuration of an existing site.
Args:
name (str): The IIS site name.
sourcepath (str): The physical path of the IIS site.
apppool (str): The name of the IIS application pool.
hostheader (str): The host header of the binding. Usually the hostname
or website name, ie: www.contoso.com
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
protocol (str): The application protocol of the binding. (http, https,
etc.)
preload (bool): Whether preloading should be enabled
Returns:
bool: True if successful, otherwise False.
.. note::
If an application pool is specified, and that application pool does not
already exist, it will be created.
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_site name='My Test Site' sourcepath='c:\\stage' apppool='TestPool' preload=True | [
"Create",
"a",
"basic",
"website",
"in",
"IIS",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L267-L351 | train |
saltstack/salt | salt/modules/win_iis.py | modify_site | def modify_site(name, sourcepath=None, apppool=None, preload=None):
'''
Modify a basic website in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The IIS site name.
sourcepath (str): The physical path of the IIS site.
apppool (str): The name of the IIS application pool.
preload (bool): Whether preloading should be enabled
Returns:
bool: True if successful, otherwise False.
.. note::
If an application pool is specified, and that application pool does not
already exist, it will be created.
CLI Example:
.. code-block:: bash
salt '*' win_iis.modify_site name='My Test Site' sourcepath='c:\\new_path' apppool='NewTestPool' preload=True
'''
site_path = r'IIS:\Sites\{0}'.format(name)
current_sites = list_sites()
if name not in current_sites:
log.debug("Site '%s' not defined.", name)
return False
ps_cmd = list()
if sourcepath:
ps_cmd.extend(['Set-ItemProperty',
'-Path', r"'{0}'".format(site_path),
'-Name', 'PhysicalPath',
'-Value', r"'{0}'".format(sourcepath)])
if apppool:
if apppool in list_apppools():
log.debug('Utilizing pre-existing application pool: %s', apppool)
else:
log.debug('Application pool will be created: %s', apppool)
create_apppool(apppool)
# If ps_cmd isn't empty, we need to add a semi-colon to run two commands
if ps_cmd:
ps_cmd.append(';')
ps_cmd.extend(['Set-ItemProperty',
'-Path', r"'{0}'".format(site_path),
'-Name', 'ApplicationPool',
'-Value', r"'{0}'".format(apppool)])
if preload:
ps_cmd.extend(['Set-ItemProperty',
'-Path', "'{0}'".format(site_path),
'-Name', 'applicationDefaults.preloadEnabled',
'-Value', "{0};".format(preload)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to modify site: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
log.debug('Site modified successfully: %s', name)
return True | python | def modify_site(name, sourcepath=None, apppool=None, preload=None):
'''
Modify a basic website in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The IIS site name.
sourcepath (str): The physical path of the IIS site.
apppool (str): The name of the IIS application pool.
preload (bool): Whether preloading should be enabled
Returns:
bool: True if successful, otherwise False.
.. note::
If an application pool is specified, and that application pool does not
already exist, it will be created.
CLI Example:
.. code-block:: bash
salt '*' win_iis.modify_site name='My Test Site' sourcepath='c:\\new_path' apppool='NewTestPool' preload=True
'''
site_path = r'IIS:\Sites\{0}'.format(name)
current_sites = list_sites()
if name not in current_sites:
log.debug("Site '%s' not defined.", name)
return False
ps_cmd = list()
if sourcepath:
ps_cmd.extend(['Set-ItemProperty',
'-Path', r"'{0}'".format(site_path),
'-Name', 'PhysicalPath',
'-Value', r"'{0}'".format(sourcepath)])
if apppool:
if apppool in list_apppools():
log.debug('Utilizing pre-existing application pool: %s', apppool)
else:
log.debug('Application pool will be created: %s', apppool)
create_apppool(apppool)
# If ps_cmd isn't empty, we need to add a semi-colon to run two commands
if ps_cmd:
ps_cmd.append(';')
ps_cmd.extend(['Set-ItemProperty',
'-Path', r"'{0}'".format(site_path),
'-Name', 'ApplicationPool',
'-Value', r"'{0}'".format(apppool)])
if preload:
ps_cmd.extend(['Set-ItemProperty',
'-Path', "'{0}'".format(site_path),
'-Name', 'applicationDefaults.preloadEnabled',
'-Value', "{0};".format(preload)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to modify site: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
log.debug('Site modified successfully: %s', name)
return True | [
"def",
"modify_site",
"(",
"name",
",",
"sourcepath",
"=",
"None",
",",
"apppool",
"=",
"None",
",",
"preload",
"=",
"None",
")",
":",
"site_path",
"=",
"r'IIS:\\Sites\\{0}'",
".",
"format",
"(",
"name",
")",
"current_sites",
"=",
"list_sites",
"(",
")",
... | Modify a basic website in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The IIS site name.
sourcepath (str): The physical path of the IIS site.
apppool (str): The name of the IIS application pool.
preload (bool): Whether preloading should be enabled
Returns:
bool: True if successful, otherwise False.
.. note::
If an application pool is specified, and that application pool does not
already exist, it will be created.
CLI Example:
.. code-block:: bash
salt '*' win_iis.modify_site name='My Test Site' sourcepath='c:\\new_path' apppool='NewTestPool' preload=True | [
"Modify",
"a",
"basic",
"website",
"in",
"IIS",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L354-L426 | train |
saltstack/salt | salt/modules/win_iis.py | remove_site | def remove_site(name):
'''
Delete a website from IIS.
Args:
name (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
.. note::
This will not remove the application pool used by the site.
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_site name='My Test Site'
'''
current_sites = list_sites()
if name not in current_sites:
log.debug('Site already absent: %s', name)
return True
ps_cmd = ['Remove-WebSite', '-Name', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove site: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
log.debug('Site removed successfully: %s', name)
return True | python | def remove_site(name):
'''
Delete a website from IIS.
Args:
name (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
.. note::
This will not remove the application pool used by the site.
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_site name='My Test Site'
'''
current_sites = list_sites()
if name not in current_sites:
log.debug('Site already absent: %s', name)
return True
ps_cmd = ['Remove-WebSite', '-Name', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove site: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
log.debug('Site removed successfully: %s', name)
return True | [
"def",
"remove_site",
"(",
"name",
")",
":",
"current_sites",
"=",
"list_sites",
"(",
")",
"if",
"name",
"not",
"in",
"current_sites",
":",
"log",
".",
"debug",
"(",
"'Site already absent: %s'",
",",
"name",
")",
"return",
"True",
"ps_cmd",
"=",
"[",
"'Rem... | Delete a website from IIS.
Args:
name (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
.. note::
This will not remove the application pool used by the site.
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_site name='My Test Site' | [
"Delete",
"a",
"website",
"from",
"IIS",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L429-L466 | train |
saltstack/salt | salt/modules/win_iis.py | stop_site | def stop_site(name):
'''
Stop a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_site name='My Test Site'
'''
ps_cmd = ['Stop-WebSite', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | python | def stop_site(name):
'''
Stop a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_site name='My Test Site'
'''
ps_cmd = ['Stop-WebSite', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | [
"def",
"stop_site",
"(",
"name",
")",
":",
"ps_cmd",
"=",
"[",
"'Stop-WebSite'",
",",
"r\"'{0}'\"",
".",
"format",
"(",
"name",
")",
"]",
"cmd_ret",
"=",
"_srvmgr",
"(",
"ps_cmd",
")",
"return",
"cmd_ret",
"[",
"'retcode'",
"]",
"==",
"0"
] | Stop a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_site name='My Test Site' | [
"Stop",
"a",
"Web",
"Site",
"in",
"IIS",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L469-L491 | train |
saltstack/salt | salt/modules/win_iis.py | start_site | def start_site(name):
'''
Start a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_site name='My Test Site'
'''
ps_cmd = ['Start-WebSite', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | python | def start_site(name):
'''
Start a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_site name='My Test Site'
'''
ps_cmd = ['Start-WebSite', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | [
"def",
"start_site",
"(",
"name",
")",
":",
"ps_cmd",
"=",
"[",
"'Start-WebSite'",
",",
"r\"'{0}'\"",
".",
"format",
"(",
"name",
")",
"]",
"cmd_ret",
"=",
"_srvmgr",
"(",
"ps_cmd",
")",
"return",
"cmd_ret",
"[",
"'retcode'",
"]",
"==",
"0"
] | Start a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_site name='My Test Site' | [
"Start",
"a",
"Web",
"Site",
"in",
"IIS",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L494-L516 | train |
saltstack/salt | salt/modules/win_iis.py | list_bindings | def list_bindings(site):
'''
Get all configured IIS bindings for the specified site.
Args:
site (str): The name if the IIS Site
Returns:
dict: A dictionary of the binding names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_bindings site
'''
ret = dict()
sites = list_sites()
if site not in sites:
log.warning('Site not found: %s', site)
return ret
ret = sites[site]['bindings']
if not ret:
log.warning('No bindings found for site: %s', site)
return ret | python | def list_bindings(site):
'''
Get all configured IIS bindings for the specified site.
Args:
site (str): The name if the IIS Site
Returns:
dict: A dictionary of the binding names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_bindings site
'''
ret = dict()
sites = list_sites()
if site not in sites:
log.warning('Site not found: %s', site)
return ret
ret = sites[site]['bindings']
if not ret:
log.warning('No bindings found for site: %s', site)
return ret | [
"def",
"list_bindings",
"(",
"site",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"sites",
"=",
"list_sites",
"(",
")",
"if",
"site",
"not",
"in",
"sites",
":",
"log",
".",
"warning",
"(",
"'Site not found: %s'",
",",
"site",
")",
"return",
"ret",
"ret",
... | Get all configured IIS bindings for the specified site.
Args:
site (str): The name if the IIS Site
Returns:
dict: A dictionary of the binding names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_bindings site | [
"Get",
"all",
"configured",
"IIS",
"bindings",
"for",
"the",
"specified",
"site",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L540-L568 | train |
saltstack/salt | salt/modules/win_iis.py | create_binding | def create_binding(site, hostheader='', ipaddress='*', port=80, protocol='http',
sslflags=None):
'''
Create an IIS Web Binding.
.. note::
This function only validates against the binding
ipaddress:port:hostheader combination, and will return True even if the
binding already exists with a different configuration. It will not
modify the configuration of an existing binding.
Args:
site (str): The IIS site name.
hostheader (str): The host header of the binding. Usually a hostname.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
protocol (str): The application protocol of the binding.
sslflags (str): The flags representing certificate type and storage of
the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_binding site='site0' hostheader='example.com' ipaddress='*' port='80'
'''
protocol = six.text_type(protocol).lower()
name = _get_binding_info(hostheader, ipaddress, port)
if protocol not in _VALID_PROTOCOLS:
message = ("Invalid protocol '{0}' specified. Valid formats:"
' {1}').format(protocol, _VALID_PROTOCOLS)
raise SaltInvocationError(message)
if sslflags:
sslflags = int(sslflags)
if sslflags not in _VALID_SSL_FLAGS:
message = ("Invalid sslflags '{0}' specified. Valid sslflags range:"
' {1}..{2}').format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[-1])
raise SaltInvocationError(message)
current_bindings = list_bindings(site)
if name in current_bindings:
log.debug('Binding already present: %s', name)
return True
if sslflags:
ps_cmd = ['New-WebBinding',
'-Name', "'{0}'".format(site),
'-HostHeader', "'{0}'".format(hostheader),
'-IpAddress', "'{0}'".format(ipaddress),
'-Port', "'{0}'".format(port),
'-Protocol', "'{0}'".format(protocol),
'-SslFlags', '{0}'.format(sslflags)]
else:
ps_cmd = ['New-WebBinding',
'-Name', "'{0}'".format(site),
'-HostHeader', "'{0}'".format(hostheader),
'-IpAddress', "'{0}'".format(ipaddress),
'-Port', "'{0}'".format(port),
'-Protocol', "'{0}'".format(protocol)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create binding: {0}\nError: {1}' \
''.format(site, cmd_ret['stderr'])
raise CommandExecutionError(msg)
if name in list_bindings(site):
log.debug('Binding created successfully: %s', site)
return True
log.error('Unable to create binding: %s', site)
return False | python | def create_binding(site, hostheader='', ipaddress='*', port=80, protocol='http',
sslflags=None):
'''
Create an IIS Web Binding.
.. note::
This function only validates against the binding
ipaddress:port:hostheader combination, and will return True even if the
binding already exists with a different configuration. It will not
modify the configuration of an existing binding.
Args:
site (str): The IIS site name.
hostheader (str): The host header of the binding. Usually a hostname.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
protocol (str): The application protocol of the binding.
sslflags (str): The flags representing certificate type and storage of
the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_binding site='site0' hostheader='example.com' ipaddress='*' port='80'
'''
protocol = six.text_type(protocol).lower()
name = _get_binding_info(hostheader, ipaddress, port)
if protocol not in _VALID_PROTOCOLS:
message = ("Invalid protocol '{0}' specified. Valid formats:"
' {1}').format(protocol, _VALID_PROTOCOLS)
raise SaltInvocationError(message)
if sslflags:
sslflags = int(sslflags)
if sslflags not in _VALID_SSL_FLAGS:
message = ("Invalid sslflags '{0}' specified. Valid sslflags range:"
' {1}..{2}').format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[-1])
raise SaltInvocationError(message)
current_bindings = list_bindings(site)
if name in current_bindings:
log.debug('Binding already present: %s', name)
return True
if sslflags:
ps_cmd = ['New-WebBinding',
'-Name', "'{0}'".format(site),
'-HostHeader', "'{0}'".format(hostheader),
'-IpAddress', "'{0}'".format(ipaddress),
'-Port', "'{0}'".format(port),
'-Protocol', "'{0}'".format(protocol),
'-SslFlags', '{0}'.format(sslflags)]
else:
ps_cmd = ['New-WebBinding',
'-Name', "'{0}'".format(site),
'-HostHeader', "'{0}'".format(hostheader),
'-IpAddress', "'{0}'".format(ipaddress),
'-Port', "'{0}'".format(port),
'-Protocol', "'{0}'".format(protocol)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create binding: {0}\nError: {1}' \
''.format(site, cmd_ret['stderr'])
raise CommandExecutionError(msg)
if name in list_bindings(site):
log.debug('Binding created successfully: %s', site)
return True
log.error('Unable to create binding: %s', site)
return False | [
"def",
"create_binding",
"(",
"site",
",",
"hostheader",
"=",
"''",
",",
"ipaddress",
"=",
"'*'",
",",
"port",
"=",
"80",
",",
"protocol",
"=",
"'http'",
",",
"sslflags",
"=",
"None",
")",
":",
"protocol",
"=",
"six",
".",
"text_type",
"(",
"protocol",... | Create an IIS Web Binding.
.. note::
This function only validates against the binding
ipaddress:port:hostheader combination, and will return True even if the
binding already exists with a different configuration. It will not
modify the configuration of an existing binding.
Args:
site (str): The IIS site name.
hostheader (str): The host header of the binding. Usually a hostname.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
protocol (str): The application protocol of the binding.
sslflags (str): The flags representing certificate type and storage of
the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_binding site='site0' hostheader='example.com' ipaddress='*' port='80' | [
"Create",
"an",
"IIS",
"Web",
"Binding",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L571-L650 | train |
saltstack/salt | salt/modules/win_iis.py | modify_binding | def modify_binding(site, binding, hostheader=None, ipaddress=None, port=None,
sslflags=None):
'''
Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the
binding.
.. versionadded:: 2017.7.0
Args:
site (str): The IIS site name.
binding (str): The binding to edit. This is a combination of the
IP address, port, and hostheader. It is in the following format:
ipaddress:port:hostheader. For example, ``*:80:`` or
``*:80:salt.com``
hostheader (str): The host header of the binding. Usually the hostname.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
sslflags (str): The flags representing certificate type and storage of
the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
The following will seat the host header of binding ``*:80:`` for ``site0``
to ``example.com``
.. code-block:: bash
salt '*' win_iis.modify_binding site='site0' binding='*:80:' hostheader='example.com'
'''
if sslflags is not None and sslflags not in _VALID_SSL_FLAGS:
message = ("Invalid sslflags '{0}' specified. Valid sslflags range:"
' {1}..{2}').format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[-1])
raise SaltInvocationError(message)
current_sites = list_sites()
if site not in current_sites:
log.debug("Site '%s' not defined.", site)
return False
current_bindings = list_bindings(site)
if binding not in current_bindings:
log.debug("Binding '%s' not defined.", binding)
return False
# Split out the binding so we can insert new ones
# Use the existing value if not passed
i, p, h = binding.split(':')
new_binding = ':'.join([ipaddress if ipaddress is not None else i,
six.text_type(port) if port is not None else six.text_type(p),
hostheader if hostheader is not None else h])
if new_binding != binding:
ps_cmd = ['Set-WebBinding',
'-Name', "'{0}'".format(site),
'-BindingInformation', "'{0}'".format(binding),
'-PropertyName', 'BindingInformation',
'-Value', "'{0}'".format(new_binding)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to modify binding: {0}\nError: {1}' \
''.format(binding, cmd_ret['stderr'])
raise CommandExecutionError(msg)
if sslflags is not None and \
sslflags != current_sites[site]['bindings'][binding]['sslflags']:
ps_cmd = ['Set-WebBinding',
'-Name', "'{0}'".format(site),
'-BindingInformation', "'{0}'".format(new_binding),
'-PropertyName', 'sslflags',
'-Value', "'{0}'".format(sslflags)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to modify binding SSL Flags: {0}\nError: {1}' \
''.format(sslflags, cmd_ret['stderr'])
raise CommandExecutionError(msg)
log.debug('Binding modified successfully: %s', binding)
return True | python | def modify_binding(site, binding, hostheader=None, ipaddress=None, port=None,
sslflags=None):
'''
Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the
binding.
.. versionadded:: 2017.7.0
Args:
site (str): The IIS site name.
binding (str): The binding to edit. This is a combination of the
IP address, port, and hostheader. It is in the following format:
ipaddress:port:hostheader. For example, ``*:80:`` or
``*:80:salt.com``
hostheader (str): The host header of the binding. Usually the hostname.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
sslflags (str): The flags representing certificate type and storage of
the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
The following will seat the host header of binding ``*:80:`` for ``site0``
to ``example.com``
.. code-block:: bash
salt '*' win_iis.modify_binding site='site0' binding='*:80:' hostheader='example.com'
'''
if sslflags is not None and sslflags not in _VALID_SSL_FLAGS:
message = ("Invalid sslflags '{0}' specified. Valid sslflags range:"
' {1}..{2}').format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[-1])
raise SaltInvocationError(message)
current_sites = list_sites()
if site not in current_sites:
log.debug("Site '%s' not defined.", site)
return False
current_bindings = list_bindings(site)
if binding not in current_bindings:
log.debug("Binding '%s' not defined.", binding)
return False
# Split out the binding so we can insert new ones
# Use the existing value if not passed
i, p, h = binding.split(':')
new_binding = ':'.join([ipaddress if ipaddress is not None else i,
six.text_type(port) if port is not None else six.text_type(p),
hostheader if hostheader is not None else h])
if new_binding != binding:
ps_cmd = ['Set-WebBinding',
'-Name', "'{0}'".format(site),
'-BindingInformation', "'{0}'".format(binding),
'-PropertyName', 'BindingInformation',
'-Value', "'{0}'".format(new_binding)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to modify binding: {0}\nError: {1}' \
''.format(binding, cmd_ret['stderr'])
raise CommandExecutionError(msg)
if sslflags is not None and \
sslflags != current_sites[site]['bindings'][binding]['sslflags']:
ps_cmd = ['Set-WebBinding',
'-Name', "'{0}'".format(site),
'-BindingInformation', "'{0}'".format(new_binding),
'-PropertyName', 'sslflags',
'-Value', "'{0}'".format(sslflags)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to modify binding SSL Flags: {0}\nError: {1}' \
''.format(sslflags, cmd_ret['stderr'])
raise CommandExecutionError(msg)
log.debug('Binding modified successfully: %s', binding)
return True | [
"def",
"modify_binding",
"(",
"site",
",",
"binding",
",",
"hostheader",
"=",
"None",
",",
"ipaddress",
"=",
"None",
",",
"port",
"=",
"None",
",",
"sslflags",
"=",
"None",
")",
":",
"if",
"sslflags",
"is",
"not",
"None",
"and",
"sslflags",
"not",
"in"... | Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the
binding.
.. versionadded:: 2017.7.0
Args:
site (str): The IIS site name.
binding (str): The binding to edit. This is a combination of the
IP address, port, and hostheader. It is in the following format:
ipaddress:port:hostheader. For example, ``*:80:`` or
``*:80:salt.com``
hostheader (str): The host header of the binding. Usually the hostname.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
sslflags (str): The flags representing certificate type and storage of
the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
The following will seat the host header of binding ``*:80:`` for ``site0``
to ``example.com``
.. code-block:: bash
salt '*' win_iis.modify_binding site='site0' binding='*:80:' hostheader='example.com' | [
"Modify",
"an",
"IIS",
"Web",
"Binding",
".",
"Use",
"site",
"and",
"binding",
"to",
"target",
"the",
"binding",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L653-L739 | train |
saltstack/salt | salt/modules/win_iis.py | remove_binding | def remove_binding(site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
Args:
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_binding site='site0' hostheader='example.com' ipaddress='*' port='80'
'''
name = _get_binding_info(hostheader, ipaddress, port)
current_bindings = list_bindings(site)
if name not in current_bindings:
log.debug('Binding already absent: %s', name)
return True
ps_cmd = ['Remove-WebBinding',
'-HostHeader', "'{0}'".format(hostheader),
'-IpAddress', "'{0}'".format(ipaddress),
'-Port', "'{0}'".format(port)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove binding: {0}\nError: {1}' \
''.format(site, cmd_ret['stderr'])
raise CommandExecutionError(msg)
if name not in list_bindings(site):
log.debug('Binding removed successfully: %s', site)
return True
log.error('Unable to remove binding: %s', site)
return False | python | def remove_binding(site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
Args:
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_binding site='site0' hostheader='example.com' ipaddress='*' port='80'
'''
name = _get_binding_info(hostheader, ipaddress, port)
current_bindings = list_bindings(site)
if name not in current_bindings:
log.debug('Binding already absent: %s', name)
return True
ps_cmd = ['Remove-WebBinding',
'-HostHeader', "'{0}'".format(hostheader),
'-IpAddress', "'{0}'".format(ipaddress),
'-Port', "'{0}'".format(port)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove binding: {0}\nError: {1}' \
''.format(site, cmd_ret['stderr'])
raise CommandExecutionError(msg)
if name not in list_bindings(site):
log.debug('Binding removed successfully: %s', site)
return True
log.error('Unable to remove binding: %s', site)
return False | [
"def",
"remove_binding",
"(",
"site",
",",
"hostheader",
"=",
"''",
",",
"ipaddress",
"=",
"'*'",
",",
"port",
"=",
"80",
")",
":",
"name",
"=",
"_get_binding_info",
"(",
"hostheader",
",",
"ipaddress",
",",
"port",
")",
"current_bindings",
"=",
"list_bind... | Remove an IIS binding.
Args:
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_binding site='site0' hostheader='example.com' ipaddress='*' port='80' | [
"Remove",
"an",
"IIS",
"binding",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L742-L784 | train |
saltstack/salt | salt/modules/win_iis.py | list_cert_bindings | def list_cert_bindings(site):
'''
List certificate bindings for an IIS site.
.. versionadded:: 2016.11.0
Args:
site (str): The IIS site name.
Returns:
dict: A dictionary of the binding names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_bindings site
'''
ret = dict()
sites = list_sites()
if site not in sites:
log.warning('Site not found: %s', site)
return ret
for binding in sites[site]['bindings']:
if sites[site]['bindings'][binding]['certificatehash']:
ret[binding] = sites[site]['bindings'][binding]
if not ret:
log.warning('No certificate bindings found for site: %s', site)
return ret | python | def list_cert_bindings(site):
'''
List certificate bindings for an IIS site.
.. versionadded:: 2016.11.0
Args:
site (str): The IIS site name.
Returns:
dict: A dictionary of the binding names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_bindings site
'''
ret = dict()
sites = list_sites()
if site not in sites:
log.warning('Site not found: %s', site)
return ret
for binding in sites[site]['bindings']:
if sites[site]['bindings'][binding]['certificatehash']:
ret[binding] = sites[site]['bindings'][binding]
if not ret:
log.warning('No certificate bindings found for site: %s', site)
return ret | [
"def",
"list_cert_bindings",
"(",
"site",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"sites",
"=",
"list_sites",
"(",
")",
"if",
"site",
"not",
"in",
"sites",
":",
"log",
".",
"warning",
"(",
"'Site not found: %s'",
",",
"site",
")",
"return",
"ret",
"for... | List certificate bindings for an IIS site.
.. versionadded:: 2016.11.0
Args:
site (str): The IIS site name.
Returns:
dict: A dictionary of the binding names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_bindings site | [
"List",
"certificate",
"bindings",
"for",
"an",
"IIS",
"site",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L787-L819 | train |
saltstack/salt | salt/modules/win_iis.py | create_cert_binding | def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443,
sslflags=0):
'''
Assign a certificate to an IIS Web Binding.
.. versionadded:: 2016.11.0
.. note::
The web binding that the certificate is being assigned to must already
exist.
Args:
name (str): The thumbprint of the certificate.
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
sslflags (int): Flags representing certificate type and certificate storage of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'
'''
name = six.text_type(name).upper()
binding_info = _get_binding_info(hostheader, ipaddress, port)
if _iisVersion() < 8:
# IIS 7.5 and earlier don't support SNI for HTTPS, therefore cert bindings don't contain the host header
binding_info = binding_info.rpartition(':')[0] + ':'
binding_path = r"IIS:\SslBindings\{0}".format(binding_info.replace(':', '!'))
if sslflags not in _VALID_SSL_FLAGS:
message = ("Invalid sslflags '{0}' specified. Valid sslflags range: "
"{1}..{2}").format(sslflags, _VALID_SSL_FLAGS[0],
_VALID_SSL_FLAGS[-1])
raise SaltInvocationError(message)
# Verify that the target binding exists.
current_bindings = list_bindings(site)
if binding_info not in current_bindings:
log.error('Binding not present: %s', binding_info)
return False
# Check to see if the certificate is already assigned.
current_name = None
for current_binding in current_bindings:
if binding_info == current_binding:
current_name = current_bindings[current_binding]['certificatehash']
log.debug('Current certificate thumbprint: %s', current_name)
log.debug('New certificate thumbprint: %s', name)
if name == current_name:
log.debug('Certificate already present for binding: %s', name)
return True
# Verify that the certificate exists.
certs = _list_certs()
if name not in certs:
log.error('Certificate not present: %s', name)
return False
if _iisVersion() < 8:
# IIS 7.5 and earlier have different syntax for associating a certificate with a site
# Modify IP spec to IIS 7.5 format
iis7path = binding_path.replace(r"\*!", "\\0.0.0.0!")
# win 2008 uses the following format: ip!port and not ip!port!
if iis7path.endswith("!"):
iis7path = iis7path[:-1]
ps_cmd = ['New-Item',
'-Path', "'{0}'".format(iis7path),
'-Thumbprint', "'{0}'".format(name)]
else:
ps_cmd = ['New-Item',
'-Path', "'{0}'".format(binding_path),
'-Thumbprint', "'{0}'".format(name),
'-SSLFlags', '{0}'.format(sslflags)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create certificate binding: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_cert_bindings = list_cert_bindings(site)
if binding_info not in new_cert_bindings:
log.error('Binding not present: %s', binding_info)
return False
if name == new_cert_bindings[binding_info]['certificatehash']:
log.debug('Certificate binding created successfully: %s', name)
return True
log.error('Unable to create certificate binding: %s', name)
return False | python | def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443,
sslflags=0):
'''
Assign a certificate to an IIS Web Binding.
.. versionadded:: 2016.11.0
.. note::
The web binding that the certificate is being assigned to must already
exist.
Args:
name (str): The thumbprint of the certificate.
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
sslflags (int): Flags representing certificate type and certificate storage of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'
'''
name = six.text_type(name).upper()
binding_info = _get_binding_info(hostheader, ipaddress, port)
if _iisVersion() < 8:
# IIS 7.5 and earlier don't support SNI for HTTPS, therefore cert bindings don't contain the host header
binding_info = binding_info.rpartition(':')[0] + ':'
binding_path = r"IIS:\SslBindings\{0}".format(binding_info.replace(':', '!'))
if sslflags not in _VALID_SSL_FLAGS:
message = ("Invalid sslflags '{0}' specified. Valid sslflags range: "
"{1}..{2}").format(sslflags, _VALID_SSL_FLAGS[0],
_VALID_SSL_FLAGS[-1])
raise SaltInvocationError(message)
# Verify that the target binding exists.
current_bindings = list_bindings(site)
if binding_info not in current_bindings:
log.error('Binding not present: %s', binding_info)
return False
# Check to see if the certificate is already assigned.
current_name = None
for current_binding in current_bindings:
if binding_info == current_binding:
current_name = current_bindings[current_binding]['certificatehash']
log.debug('Current certificate thumbprint: %s', current_name)
log.debug('New certificate thumbprint: %s', name)
if name == current_name:
log.debug('Certificate already present for binding: %s', name)
return True
# Verify that the certificate exists.
certs = _list_certs()
if name not in certs:
log.error('Certificate not present: %s', name)
return False
if _iisVersion() < 8:
# IIS 7.5 and earlier have different syntax for associating a certificate with a site
# Modify IP spec to IIS 7.5 format
iis7path = binding_path.replace(r"\*!", "\\0.0.0.0!")
# win 2008 uses the following format: ip!port and not ip!port!
if iis7path.endswith("!"):
iis7path = iis7path[:-1]
ps_cmd = ['New-Item',
'-Path', "'{0}'".format(iis7path),
'-Thumbprint', "'{0}'".format(name)]
else:
ps_cmd = ['New-Item',
'-Path', "'{0}'".format(binding_path),
'-Thumbprint', "'{0}'".format(name),
'-SSLFlags', '{0}'.format(sslflags)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create certificate binding: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_cert_bindings = list_cert_bindings(site)
if binding_info not in new_cert_bindings:
log.error('Binding not present: %s', binding_info)
return False
if name == new_cert_bindings[binding_info]['certificatehash']:
log.debug('Certificate binding created successfully: %s', name)
return True
log.error('Unable to create certificate binding: %s', name)
return False | [
"def",
"create_cert_binding",
"(",
"name",
",",
"site",
",",
"hostheader",
"=",
"''",
",",
"ipaddress",
"=",
"'*'",
",",
"port",
"=",
"443",
",",
"sslflags",
"=",
"0",
")",
":",
"name",
"=",
"six",
".",
"text_type",
"(",
"name",
")",
".",
"upper",
... | Assign a certificate to an IIS Web Binding.
.. versionadded:: 2016.11.0
.. note::
The web binding that the certificate is being assigned to must already
exist.
Args:
name (str): The thumbprint of the certificate.
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
sslflags (int): Flags representing certificate type and certificate storage of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443' | [
"Assign",
"a",
"certificate",
"to",
"an",
"IIS",
"Web",
"Binding",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L822-L930 | train |
saltstack/salt | salt/modules/win_iis.py | remove_cert_binding | def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS Web Binding.
.. versionadded:: 2016.11.0
.. note::
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
Args:
name (str): The thumbprint of the certificate.
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'
'''
name = six.text_type(name).upper()
binding_info = _get_binding_info(hostheader, ipaddress, port)
# Child items of IIS:\SslBindings do not return populated host header info
# in all circumstances, so it's necessary to use IIS:\Sites instead.
ps_cmd = ['$Site = Get-ChildItem', '-Path', r"'IIS:\Sites'",
'|', 'Where-Object', r" {{ $_.Name -Eq '{0}' }};".format(site),
'$Binding = $Site.Bindings.Collection',
r"| Where-Object { $_.bindingInformation",
r"-Eq '{0}' }};".format(binding_info),
'$Binding.RemoveSslCertificate()']
# Verify that the binding exists for the site, and that the target
# certificate is assigned to the binding.
current_cert_bindings = list_cert_bindings(site)
if binding_info not in current_cert_bindings:
log.warning('Binding not found: %s', binding_info)
return True
if name != current_cert_bindings[binding_info]['certificatehash']:
log.debug('Certificate binding already absent: %s', name)
return True
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove certificate binding: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_cert_bindings = list_cert_bindings(site)
if binding_info not in new_cert_bindings:
log.warning('Binding not found: %s', binding_info)
return True
if name != new_cert_bindings[binding_info]['certificatehash']:
log.debug('Certificate binding removed successfully: %s', name)
return True
log.error('Unable to remove certificate binding: %s', name)
return False | python | def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS Web Binding.
.. versionadded:: 2016.11.0
.. note::
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
Args:
name (str): The thumbprint of the certificate.
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'
'''
name = six.text_type(name).upper()
binding_info = _get_binding_info(hostheader, ipaddress, port)
# Child items of IIS:\SslBindings do not return populated host header info
# in all circumstances, so it's necessary to use IIS:\Sites instead.
ps_cmd = ['$Site = Get-ChildItem', '-Path', r"'IIS:\Sites'",
'|', 'Where-Object', r" {{ $_.Name -Eq '{0}' }};".format(site),
'$Binding = $Site.Bindings.Collection',
r"| Where-Object { $_.bindingInformation",
r"-Eq '{0}' }};".format(binding_info),
'$Binding.RemoveSslCertificate()']
# Verify that the binding exists for the site, and that the target
# certificate is assigned to the binding.
current_cert_bindings = list_cert_bindings(site)
if binding_info not in current_cert_bindings:
log.warning('Binding not found: %s', binding_info)
return True
if name != current_cert_bindings[binding_info]['certificatehash']:
log.debug('Certificate binding already absent: %s', name)
return True
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove certificate binding: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_cert_bindings = list_cert_bindings(site)
if binding_info not in new_cert_bindings:
log.warning('Binding not found: %s', binding_info)
return True
if name != new_cert_bindings[binding_info]['certificatehash']:
log.debug('Certificate binding removed successfully: %s', name)
return True
log.error('Unable to remove certificate binding: %s', name)
return False | [
"def",
"remove_cert_binding",
"(",
"name",
",",
"site",
",",
"hostheader",
"=",
"''",
",",
"ipaddress",
"=",
"'*'",
",",
"port",
"=",
"443",
")",
":",
"name",
"=",
"six",
".",
"text_type",
"(",
"name",
")",
".",
"upper",
"(",
")",
"binding_info",
"="... | Remove a certificate from an IIS Web Binding.
.. versionadded:: 2016.11.0
.. note::
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
Args:
name (str): The thumbprint of the certificate.
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443' | [
"Remove",
"a",
"certificate",
"from",
"an",
"IIS",
"Web",
"Binding",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L933-L1002 | train |
saltstack/salt | salt/modules/win_iis.py | list_apppools | def list_apppools():
'''
List all configured IIS application pools.
Returns:
dict: A dictionary of IIS application pools and their details.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_apppools
'''
ret = dict()
ps_cmd = []
ps_cmd.append(r"Get-ChildItem -Path 'IIS:\AppPools' | Select-Object Name, State")
# Include the equivalent of output from the Applications column, since this
# isn't a normal property, we have to populate it via filtered output from
# the Get-WebConfigurationProperty cmdlet.
ps_cmd.append(r", @{ Name = 'Applications'; Expression = { $AppPool = $_.Name;")
ps_cmd.append("$AppPath = 'machine/webroot/apphost';")
ps_cmd.append("$FilterBase = '/system.applicationHost/sites/site/application';")
ps_cmd.append('$FilterBase += "[@applicationPool = \'$($AppPool)\' and @path";')
ps_cmd.append('$FilterRoot = "$($FilterBase) = \'/\']/parent::*";')
ps_cmd.append('$FilterNonRoot = "$($FilterBase) != \'/\']";')
ps_cmd.append('Get-WebConfigurationProperty -Filter $FilterRoot -PsPath $AppPath -Name Name')
ps_cmd.append(r'| ForEach-Object { $_.Value };')
ps_cmd.append('Get-WebConfigurationProperty -Filter $FilterNonRoot -PsPath $AppPath -Name Path')
ps_cmd.append(r"| ForEach-Object { $_.Value } | Where-Object { $_ -ne '/' }")
ps_cmd.append('} }')
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
applications = list()
# If there are no associated apps, Applications will be an empty dict,
# if there is one app, it will be a string, and if there are multiple,
# it will be a dict with 'Count' and 'value' as the keys.
if isinstance(item['Applications'], dict):
if 'value' in item['Applications']:
applications += item['Applications']['value']
else:
applications.append(item['Applications'])
ret[item['name']] = {'state': item['state'], 'applications': applications}
if not ret:
log.warning('No application pools found in output: %s',
cmd_ret['stdout'])
return ret | python | def list_apppools():
'''
List all configured IIS application pools.
Returns:
dict: A dictionary of IIS application pools and their details.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_apppools
'''
ret = dict()
ps_cmd = []
ps_cmd.append(r"Get-ChildItem -Path 'IIS:\AppPools' | Select-Object Name, State")
# Include the equivalent of output from the Applications column, since this
# isn't a normal property, we have to populate it via filtered output from
# the Get-WebConfigurationProperty cmdlet.
ps_cmd.append(r", @{ Name = 'Applications'; Expression = { $AppPool = $_.Name;")
ps_cmd.append("$AppPath = 'machine/webroot/apphost';")
ps_cmd.append("$FilterBase = '/system.applicationHost/sites/site/application';")
ps_cmd.append('$FilterBase += "[@applicationPool = \'$($AppPool)\' and @path";')
ps_cmd.append('$FilterRoot = "$($FilterBase) = \'/\']/parent::*";')
ps_cmd.append('$FilterNonRoot = "$($FilterBase) != \'/\']";')
ps_cmd.append('Get-WebConfigurationProperty -Filter $FilterRoot -PsPath $AppPath -Name Name')
ps_cmd.append(r'| ForEach-Object { $_.Value };')
ps_cmd.append('Get-WebConfigurationProperty -Filter $FilterNonRoot -PsPath $AppPath -Name Path')
ps_cmd.append(r"| ForEach-Object { $_.Value } | Where-Object { $_ -ne '/' }")
ps_cmd.append('} }')
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
applications = list()
# If there are no associated apps, Applications will be an empty dict,
# if there is one app, it will be a string, and if there are multiple,
# it will be a dict with 'Count' and 'value' as the keys.
if isinstance(item['Applications'], dict):
if 'value' in item['Applications']:
applications += item['Applications']['value']
else:
applications.append(item['Applications'])
ret[item['name']] = {'state': item['state'], 'applications': applications}
if not ret:
log.warning('No application pools found in output: %s',
cmd_ret['stdout'])
return ret | [
"def",
"list_apppools",
"(",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"ps_cmd",
"=",
"[",
"]",
"ps_cmd",
".",
"append",
"(",
"r\"Get-ChildItem -Path 'IIS:\\AppPools' | Select-Object Name, State\"",
")",
"# Include the equivalent of output from the Applications column, since th... | List all configured IIS application pools.
Returns:
dict: A dictionary of IIS application pools and their details.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_apppools | [
"List",
"all",
"configured",
"IIS",
"application",
"pools",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1005-L1063 | train |
saltstack/salt | salt/modules/win_iis.py | create_apppool | def create_apppool(name):
'''
Create an IIS application pool.
.. note::
This function only validates against the application pool name, and will
return True even if the application pool already exists with a different
configuration. It will not modify the configuration of an existing
application pool.
Args:
name (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_apppool name='MyTestPool'
'''
current_apppools = list_apppools()
apppool_path = r'IIS:\AppPools\{0}'.format(name)
if name in current_apppools:
log.debug("Application pool '%s' already present.", name)
return True
ps_cmd = ['New-Item', '-Path', r"'{0}'".format(apppool_path)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create application pool: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
log.debug('Application pool created successfully: %s', name)
return True | python | def create_apppool(name):
'''
Create an IIS application pool.
.. note::
This function only validates against the application pool name, and will
return True even if the application pool already exists with a different
configuration. It will not modify the configuration of an existing
application pool.
Args:
name (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_apppool name='MyTestPool'
'''
current_apppools = list_apppools()
apppool_path = r'IIS:\AppPools\{0}'.format(name)
if name in current_apppools:
log.debug("Application pool '%s' already present.", name)
return True
ps_cmd = ['New-Item', '-Path', r"'{0}'".format(apppool_path)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create application pool: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
log.debug('Application pool created successfully: %s', name)
return True | [
"def",
"create_apppool",
"(",
"name",
")",
":",
"current_apppools",
"=",
"list_apppools",
"(",
")",
"apppool_path",
"=",
"r'IIS:\\AppPools\\{0}'",
".",
"format",
"(",
"name",
")",
"if",
"name",
"in",
"current_apppools",
":",
"log",
".",
"debug",
"(",
"\"Applic... | Create an IIS application pool.
.. note::
This function only validates against the application pool name, and will
return True even if the application pool already exists with a different
configuration. It will not modify the configuration of an existing
application pool.
Args:
name (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_apppool name='MyTestPool' | [
"Create",
"an",
"IIS",
"application",
"pool",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1066-L1106 | train |
saltstack/salt | salt/modules/win_iis.py | stop_apppool | def stop_apppool(name):
'''
Stop an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_apppool name='MyTestPool'
'''
ps_cmd = ['Stop-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | python | def stop_apppool(name):
'''
Stop an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_apppool name='MyTestPool'
'''
ps_cmd = ['Stop-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | [
"def",
"stop_apppool",
"(",
"name",
")",
":",
"ps_cmd",
"=",
"[",
"'Stop-WebAppPool'",
",",
"r\"'{0}'\"",
".",
"format",
"(",
"name",
")",
"]",
"cmd_ret",
"=",
"_srvmgr",
"(",
"ps_cmd",
")",
"return",
"cmd_ret",
"[",
"'retcode'",
"]",
"==",
"0"
] | Stop an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_apppool name='MyTestPool' | [
"Stop",
"an",
"IIS",
"application",
"pool",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1145-L1167 | train |
saltstack/salt | salt/modules/win_iis.py | start_apppool | def start_apppool(name):
'''
Start an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_apppool name='MyTestPool'
'''
ps_cmd = ['Start-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | python | def start_apppool(name):
'''
Start an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_apppool name='MyTestPool'
'''
ps_cmd = ['Start-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | [
"def",
"start_apppool",
"(",
"name",
")",
":",
"ps_cmd",
"=",
"[",
"'Start-WebAppPool'",
",",
"r\"'{0}'\"",
".",
"format",
"(",
"name",
")",
"]",
"cmd_ret",
"=",
"_srvmgr",
"(",
"ps_cmd",
")",
"return",
"cmd_ret",
"[",
"'retcode'",
"]",
"==",
"0"
] | Start an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_apppool name='MyTestPool' | [
"Start",
"an",
"IIS",
"application",
"pool",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1170-L1192 | train |
saltstack/salt | salt/modules/win_iis.py | restart_apppool | def restart_apppool(name):
'''
Restart an IIS application pool.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.restart_apppool name='MyTestPool'
'''
ps_cmd = ['Restart-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | python | def restart_apppool(name):
'''
Restart an IIS application pool.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.restart_apppool name='MyTestPool'
'''
ps_cmd = ['Restart-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | [
"def",
"restart_apppool",
"(",
"name",
")",
":",
"ps_cmd",
"=",
"[",
"'Restart-WebAppPool'",
",",
"r\"'{0}'\"",
".",
"format",
"(",
"name",
")",
"]",
"cmd_ret",
"=",
"_srvmgr",
"(",
"ps_cmd",
")",
"return",
"cmd_ret",
"[",
"'retcode'",
"]",
"==",
"0"
] | Restart an IIS application pool.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.restart_apppool name='MyTestPool' | [
"Restart",
"an",
"IIS",
"application",
"pool",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1195-L1217 | train |
saltstack/salt | salt/modules/win_iis.py | get_container_setting | def get_container_setting(name, container, settings):
'''
Get the value of the setting for the IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, SslBindings
settings (dict): A dictionary of the setting names and their values.
Returns:
dict: A dictionary of the provided settings and their values.
CLI Example:
.. code-block:: bash
salt '*' win_iis.get_container_setting name='MyTestPool' container='AppPools'
settings="['processModel.identityType']"
'''
ret = dict()
ps_cmd = list()
ps_cmd_validate = list()
container_path = r"IIS:\{0}\{1}".format(container, name)
if not settings:
log.warning('No settings provided')
return ret
ps_cmd.append(r'$Settings = @{};')
for setting in settings:
# Build the commands to verify that the property names are valid.
ps_cmd_validate.extend(['Get-ItemProperty',
'-Path', "'{0}'".format(container_path),
'-Name', "'{0}'".format(setting),
'-ErrorAction', 'Stop',
'|', 'Out-Null;'])
# Some ItemProperties are Strings and others are ConfigurationAttributes.
# Since the former doesn't have a Value property, we need to account
# for this.
ps_cmd.append("$Property = Get-ItemProperty -Path '{0}'".format(container_path))
ps_cmd.append("-Name '{0}' -ErrorAction Stop;".format(setting))
ps_cmd.append(r'if (([String]::IsNullOrEmpty($Property) -eq $False) -and')
ps_cmd.append(r"($Property.GetType()).Name -eq 'ConfigurationAttribute') {")
ps_cmd.append(r'$Property = $Property | Select-Object')
ps_cmd.append(r'-ExpandProperty Value };')
ps_cmd.append("$Settings['{0}'] = [String] $Property;".format(setting))
ps_cmd.append(r'$Property = $Null;')
# Validate the setting names that were passed in.
cmd_ret = _srvmgr(cmd=ps_cmd_validate, return_json=True)
if cmd_ret['retcode'] != 0:
message = 'One or more invalid property names were specified for the provided container.'
raise SaltInvocationError(message)
ps_cmd.append('$Settings')
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
if isinstance(items, list):
ret.update(items[0])
else:
ret.update(items)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
return ret | python | def get_container_setting(name, container, settings):
'''
Get the value of the setting for the IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, SslBindings
settings (dict): A dictionary of the setting names and their values.
Returns:
dict: A dictionary of the provided settings and their values.
CLI Example:
.. code-block:: bash
salt '*' win_iis.get_container_setting name='MyTestPool' container='AppPools'
settings="['processModel.identityType']"
'''
ret = dict()
ps_cmd = list()
ps_cmd_validate = list()
container_path = r"IIS:\{0}\{1}".format(container, name)
if not settings:
log.warning('No settings provided')
return ret
ps_cmd.append(r'$Settings = @{};')
for setting in settings:
# Build the commands to verify that the property names are valid.
ps_cmd_validate.extend(['Get-ItemProperty',
'-Path', "'{0}'".format(container_path),
'-Name', "'{0}'".format(setting),
'-ErrorAction', 'Stop',
'|', 'Out-Null;'])
# Some ItemProperties are Strings and others are ConfigurationAttributes.
# Since the former doesn't have a Value property, we need to account
# for this.
ps_cmd.append("$Property = Get-ItemProperty -Path '{0}'".format(container_path))
ps_cmd.append("-Name '{0}' -ErrorAction Stop;".format(setting))
ps_cmd.append(r'if (([String]::IsNullOrEmpty($Property) -eq $False) -and')
ps_cmd.append(r"($Property.GetType()).Name -eq 'ConfigurationAttribute') {")
ps_cmd.append(r'$Property = $Property | Select-Object')
ps_cmd.append(r'-ExpandProperty Value };')
ps_cmd.append("$Settings['{0}'] = [String] $Property;".format(setting))
ps_cmd.append(r'$Property = $Null;')
# Validate the setting names that were passed in.
cmd_ret = _srvmgr(cmd=ps_cmd_validate, return_json=True)
if cmd_ret['retcode'] != 0:
message = 'One or more invalid property names were specified for the provided container.'
raise SaltInvocationError(message)
ps_cmd.append('$Settings')
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
if isinstance(items, list):
ret.update(items[0])
else:
ret.update(items)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
return ret | [
"def",
"get_container_setting",
"(",
"name",
",",
"container",
",",
"settings",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"ps_cmd",
"=",
"list",
"(",
")",
"ps_cmd_validate",
"=",
"list",
"(",
")",
"container_path",
"=",
"r\"IIS:\\{0}\\{1}\"",
".",
"format",
... | Get the value of the setting for the IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, SslBindings
settings (dict): A dictionary of the setting names and their values.
Returns:
dict: A dictionary of the provided settings and their values.
CLI Example:
.. code-block:: bash
salt '*' win_iis.get_container_setting name='MyTestPool' container='AppPools'
settings="['processModel.identityType']" | [
"Get",
"the",
"value",
"of",
"the",
"setting",
"for",
"the",
"IIS",
"container",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1220-L1294 | train |
saltstack/salt | salt/modules/win_iis.py | set_container_setting | def set_container_setting(name, container, settings):
'''
Set the value of the setting for an IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, SslBindings
settings (dict): A dictionary of the setting names and their values.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.set_container_setting name='MyTestPool' container='AppPools'
settings="{'managedPipeLineMode': 'Integrated'}"
'''
identityType_map2string = {'0': 'LocalSystem', '1': 'LocalService', '2': 'NetworkService', '3': 'SpecificUser', '4': 'ApplicationPoolIdentity'}
identityType_map2numeric = {'LocalSystem': '0', 'LocalService': '1', 'NetworkService': '2', 'SpecificUser': '3', 'ApplicationPoolIdentity': '4'}
ps_cmd = list()
container_path = r"IIS:\{0}\{1}".format(container, name)
if not settings:
log.warning('No settings provided')
return False
# Treat all values as strings for the purpose of comparing them to existing values.
for setting in settings:
settings[setting] = six.text_type(settings[setting])
current_settings = get_container_setting(
name=name, container=container, settings=settings.keys())
if settings == current_settings:
log.debug('Settings already contain the provided values.')
return True
for setting in settings:
# If the value is numeric, don't treat it as a string in PowerShell.
try:
complex(settings[setting])
value = settings[setting]
except ValueError:
value = "'{0}'".format(settings[setting])
# Map to numeric to support server 2008
if setting == 'processModel.identityType' and settings[setting] in identityType_map2numeric.keys():
value = identityType_map2numeric[settings[setting]]
ps_cmd.extend(['Set-ItemProperty',
'-Path', "'{0}'".format(container_path),
'-Name', "'{0}'".format(setting),
'-Value', '{0};'.format(value)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to set settings for {0}: {1}'.format(container, name)
raise CommandExecutionError(msg)
# Get the fields post-change so that we can verify tht all values
# were modified successfully. Track the ones that weren't.
new_settings = get_container_setting(
name=name, container=container, settings=settings.keys())
failed_settings = dict()
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if six.text_type(settings[setting]) != six.text_type(new_settings[setting]):
failed_settings[setting] = settings[setting]
if failed_settings:
log.error('Failed to change settings: %s', failed_settings)
return False
log.debug('Settings configured successfully: %s', settings.keys())
return True | python | def set_container_setting(name, container, settings):
'''
Set the value of the setting for an IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, SslBindings
settings (dict): A dictionary of the setting names and their values.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.set_container_setting name='MyTestPool' container='AppPools'
settings="{'managedPipeLineMode': 'Integrated'}"
'''
identityType_map2string = {'0': 'LocalSystem', '1': 'LocalService', '2': 'NetworkService', '3': 'SpecificUser', '4': 'ApplicationPoolIdentity'}
identityType_map2numeric = {'LocalSystem': '0', 'LocalService': '1', 'NetworkService': '2', 'SpecificUser': '3', 'ApplicationPoolIdentity': '4'}
ps_cmd = list()
container_path = r"IIS:\{0}\{1}".format(container, name)
if not settings:
log.warning('No settings provided')
return False
# Treat all values as strings for the purpose of comparing them to existing values.
for setting in settings:
settings[setting] = six.text_type(settings[setting])
current_settings = get_container_setting(
name=name, container=container, settings=settings.keys())
if settings == current_settings:
log.debug('Settings already contain the provided values.')
return True
for setting in settings:
# If the value is numeric, don't treat it as a string in PowerShell.
try:
complex(settings[setting])
value = settings[setting]
except ValueError:
value = "'{0}'".format(settings[setting])
# Map to numeric to support server 2008
if setting == 'processModel.identityType' and settings[setting] in identityType_map2numeric.keys():
value = identityType_map2numeric[settings[setting]]
ps_cmd.extend(['Set-ItemProperty',
'-Path', "'{0}'".format(container_path),
'-Name', "'{0}'".format(setting),
'-Value', '{0};'.format(value)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to set settings for {0}: {1}'.format(container, name)
raise CommandExecutionError(msg)
# Get the fields post-change so that we can verify tht all values
# were modified successfully. Track the ones that weren't.
new_settings = get_container_setting(
name=name, container=container, settings=settings.keys())
failed_settings = dict()
for setting in settings:
# map identity type from numeric to string for comparing
if setting == 'processModel.identityType' and settings[setting] in identityType_map2string.keys():
settings[setting] = identityType_map2string[settings[setting]]
if six.text_type(settings[setting]) != six.text_type(new_settings[setting]):
failed_settings[setting] = settings[setting]
if failed_settings:
log.error('Failed to change settings: %s', failed_settings)
return False
log.debug('Settings configured successfully: %s', settings.keys())
return True | [
"def",
"set_container_setting",
"(",
"name",
",",
"container",
",",
"settings",
")",
":",
"identityType_map2string",
"=",
"{",
"'0'",
":",
"'LocalSystem'",
",",
"'1'",
":",
"'LocalService'",
",",
"'2'",
":",
"'NetworkService'",
",",
"'3'",
":",
"'SpecificUser'",... | Set the value of the setting for an IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, SslBindings
settings (dict): A dictionary of the setting names and their values.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.set_container_setting name='MyTestPool' container='AppPools'
settings="{'managedPipeLineMode': 'Integrated'}" | [
"Set",
"the",
"value",
"of",
"the",
"setting",
"for",
"an",
"IIS",
"container",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1297-L1383 | train |
saltstack/salt | salt/modules/win_iis.py | list_apps | def list_apps(site):
'''
Get all configured IIS applications for the specified site.
Args:
site (str): The IIS site name.
Returns: A dictionary of the application names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_apps site
'''
ret = dict()
ps_cmd = list()
ps_cmd.append("Get-WebApplication -Site '{0}'".format(site))
ps_cmd.append(r"| Select-Object applicationPool, path, PhysicalPath, preloadEnabled,")
ps_cmd.append(r"@{ Name='name'; Expression={ $_.path.Split('/', 2)[-1] } },")
ps_cmd.append(r"@{ Name='protocols'; Expression={ @( $_.enabledProtocols.Split(',')")
ps_cmd.append(r"| Foreach-Object { $_.Trim() } ) } }")
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
protocols = list()
# If there are no associated protocols, protocols will be an empty dict,
# if there is one protocol, it will be a string, and if there are
# multiple, it will be a dict with 'Count' and 'value' as the keys.
if isinstance(item['protocols'], dict):
if 'value' in item['protocols']:
protocols += item['protocols']['value']
else:
protocols.append(item['protocols'])
ret[item['name']] = {'apppool': item['applicationPool'],
'path': item['path'],
'preload': item['preloadEnabled'],
'protocols': protocols,
'sourcepath': item['PhysicalPath']}
if not ret:
log.warning('No apps found in output: %s', cmd_ret)
return ret | python | def list_apps(site):
'''
Get all configured IIS applications for the specified site.
Args:
site (str): The IIS site name.
Returns: A dictionary of the application names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_apps site
'''
ret = dict()
ps_cmd = list()
ps_cmd.append("Get-WebApplication -Site '{0}'".format(site))
ps_cmd.append(r"| Select-Object applicationPool, path, PhysicalPath, preloadEnabled,")
ps_cmd.append(r"@{ Name='name'; Expression={ $_.path.Split('/', 2)[-1] } },")
ps_cmd.append(r"@{ Name='protocols'; Expression={ @( $_.enabledProtocols.Split(',')")
ps_cmd.append(r"| Foreach-Object { $_.Trim() } ) } }")
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
protocols = list()
# If there are no associated protocols, protocols will be an empty dict,
# if there is one protocol, it will be a string, and if there are
# multiple, it will be a dict with 'Count' and 'value' as the keys.
if isinstance(item['protocols'], dict):
if 'value' in item['protocols']:
protocols += item['protocols']['value']
else:
protocols.append(item['protocols'])
ret[item['name']] = {'apppool': item['applicationPool'],
'path': item['path'],
'preload': item['preloadEnabled'],
'protocols': protocols,
'sourcepath': item['PhysicalPath']}
if not ret:
log.warning('No apps found in output: %s', cmd_ret)
return ret | [
"def",
"list_apps",
"(",
"site",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"ps_cmd",
"=",
"list",
"(",
")",
"ps_cmd",
".",
"append",
"(",
"\"Get-WebApplication -Site '{0}'\"",
".",
"format",
"(",
"site",
")",
")",
"ps_cmd",
".",
"append",
"(",
"r\"| Select... | Get all configured IIS applications for the specified site.
Args:
site (str): The IIS site name.
Returns: A dictionary of the application names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_apps site | [
"Get",
"all",
"configured",
"IIS",
"applications",
"for",
"the",
"specified",
"site",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1386-L1438 | train |
saltstack/salt | salt/modules/win_iis.py | create_app | def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note::
This function only validates against the application name, and will
return True even if the application already exists with a different
configuration. It will not modify the configuration of an existing
application.
Args:
name (str): The IIS application.
site (str): The IIS site name.
sourcepath (str): The physical path.
apppool (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_app name='app0' site='site0' sourcepath='C:\\site0' apppool='site0'
'''
current_apps = list_apps(site)
if name in current_apps:
log.debug('Application already present: %s', name)
return True
# The target physical path must exist.
if not os.path.isdir(sourcepath):
log.error('Path is not present: %s', sourcepath)
return False
ps_cmd = ['New-WebApplication',
'-Name', "'{0}'".format(name),
'-Site', "'{0}'".format(site),
'-PhysicalPath', "'{0}'".format(sourcepath)]
if apppool:
ps_cmd.extend(['-ApplicationPool', "'{0}'".format(apppool)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create application: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_apps = list_apps(site)
if name in new_apps:
log.debug('Application created successfully: %s', name)
return True
log.error('Unable to create application: %s', name)
return False | python | def create_app(name, site, sourcepath, apppool=None):
'''
Create an IIS application.
.. note::
This function only validates against the application name, and will
return True even if the application already exists with a different
configuration. It will not modify the configuration of an existing
application.
Args:
name (str): The IIS application.
site (str): The IIS site name.
sourcepath (str): The physical path.
apppool (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_app name='app0' site='site0' sourcepath='C:\\site0' apppool='site0'
'''
current_apps = list_apps(site)
if name in current_apps:
log.debug('Application already present: %s', name)
return True
# The target physical path must exist.
if not os.path.isdir(sourcepath):
log.error('Path is not present: %s', sourcepath)
return False
ps_cmd = ['New-WebApplication',
'-Name', "'{0}'".format(name),
'-Site', "'{0}'".format(site),
'-PhysicalPath', "'{0}'".format(sourcepath)]
if apppool:
ps_cmd.extend(['-ApplicationPool', "'{0}'".format(apppool)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create application: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_apps = list_apps(site)
if name in new_apps:
log.debug('Application created successfully: %s', name)
return True
log.error('Unable to create application: %s', name)
return False | [
"def",
"create_app",
"(",
"name",
",",
"site",
",",
"sourcepath",
",",
"apppool",
"=",
"None",
")",
":",
"current_apps",
"=",
"list_apps",
"(",
"site",
")",
"if",
"name",
"in",
"current_apps",
":",
"log",
".",
"debug",
"(",
"'Application already present: %s'... | Create an IIS application.
.. note::
This function only validates against the application name, and will
return True even if the application already exists with a different
configuration. It will not modify the configuration of an existing
application.
Args:
name (str): The IIS application.
site (str): The IIS site name.
sourcepath (str): The physical path.
apppool (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_app name='app0' site='site0' sourcepath='C:\\site0' apppool='site0' | [
"Create",
"an",
"IIS",
"application",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1441-L1500 | train |
saltstack/salt | salt/modules/win_iis.py | remove_app | def remove_app(name, site):
'''
Remove an IIS application.
Args:
name (str): The application name.
site (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_app name='app0' site='site0'
'''
current_apps = list_apps(site)
if name not in current_apps:
log.debug('Application already absent: %s', name)
return True
ps_cmd = ['Remove-WebApplication',
'-Name', "'{0}'".format(name),
'-Site', "'{0}'".format(site)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove application: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_apps = list_apps(site)
if name not in new_apps:
log.debug('Application removed successfully: %s', name)
return True
log.error('Unable to remove application: %s', name)
return False | python | def remove_app(name, site):
'''
Remove an IIS application.
Args:
name (str): The application name.
site (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_app name='app0' site='site0'
'''
current_apps = list_apps(site)
if name not in current_apps:
log.debug('Application already absent: %s', name)
return True
ps_cmd = ['Remove-WebApplication',
'-Name', "'{0}'".format(name),
'-Site', "'{0}'".format(site)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove application: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_apps = list_apps(site)
if name not in new_apps:
log.debug('Application removed successfully: %s', name)
return True
log.error('Unable to remove application: %s', name)
return False | [
"def",
"remove_app",
"(",
"name",
",",
"site",
")",
":",
"current_apps",
"=",
"list_apps",
"(",
"site",
")",
"if",
"name",
"not",
"in",
"current_apps",
":",
"log",
".",
"debug",
"(",
"'Application already absent: %s'",
",",
"name",
")",
"return",
"True",
"... | Remove an IIS application.
Args:
name (str): The application name.
site (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_app name='app0' site='site0' | [
"Remove",
"an",
"IIS",
"application",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1503-L1544 | train |
saltstack/salt | salt/modules/win_iis.py | list_vdirs | def list_vdirs(site, app=_DEFAULT_APP):
'''
Get all configured IIS virtual directories for the specified site, or for
the combination of site and application.
Args:
site (str): The IIS site name.
app (str): The IIS application.
Returns:
dict: A dictionary of the virtual directory names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_vdirs site
'''
ret = dict()
ps_cmd = ['Get-WebVirtualDirectory',
'-Site', r"'{0}'".format(site),
'-Application', r"'{0}'".format(app),
'|', "Select-Object PhysicalPath, @{ Name = 'name';",
r"Expression = { $_.path.Split('/')[-1] } }"]
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
ret[item['name']] = {'sourcepath': item['physicalPath']}
if not ret:
log.warning('No vdirs found in output: %s', cmd_ret)
return ret | python | def list_vdirs(site, app=_DEFAULT_APP):
'''
Get all configured IIS virtual directories for the specified site, or for
the combination of site and application.
Args:
site (str): The IIS site name.
app (str): The IIS application.
Returns:
dict: A dictionary of the virtual directory names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_vdirs site
'''
ret = dict()
ps_cmd = ['Get-WebVirtualDirectory',
'-Site', r"'{0}'".format(site),
'-Application', r"'{0}'".format(app),
'|', "Select-Object PhysicalPath, @{ Name = 'name';",
r"Expression = { $_.path.Split('/')[-1] } }"]
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
ret[item['name']] = {'sourcepath': item['physicalPath']}
if not ret:
log.warning('No vdirs found in output: %s', cmd_ret)
return ret | [
"def",
"list_vdirs",
"(",
"site",
",",
"app",
"=",
"_DEFAULT_APP",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"ps_cmd",
"=",
"[",
"'Get-WebVirtualDirectory'",
",",
"'-Site'",
",",
"r\"'{0}'\"",
".",
"format",
"(",
"site",
")",
",",
"'-Application'",
",",
"r... | Get all configured IIS virtual directories for the specified site, or for
the combination of site and application.
Args:
site (str): The IIS site name.
app (str): The IIS application.
Returns:
dict: A dictionary of the virtual directory names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_vdirs site | [
"Get",
"all",
"configured",
"IIS",
"virtual",
"directories",
"for",
"the",
"specified",
"site",
"or",
"for",
"the",
"combination",
"of",
"site",
"and",
"application",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1547-L1586 | train |
saltstack/salt | salt/modules/win_iis.py | create_vdir | def create_vdir(name, site, sourcepath, app=_DEFAULT_APP):
'''
Create an IIS virtual directory.
.. note::
This function only validates against the virtual directory name, and
will return True even if the virtual directory already exists with a
different configuration. It will not modify the configuration of an
existing virtual directory.
Args:
name (str): The virtual directory name.
site (str): The IIS site name.
sourcepath (str): The physical path.
app (str): The IIS application.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_vdir name='vd0' site='site0' sourcepath='C:\\inetpub\\vdirs\\vd0'
'''
current_vdirs = list_vdirs(site, app)
if name in current_vdirs:
log.debug('Virtual directory already present: %s', name)
return True
# The target physical path must exist.
if not os.path.isdir(sourcepath):
log.error('Path is not present: %s', sourcepath)
return False
ps_cmd = ['New-WebVirtualDirectory',
'-Name', r"'{0}'".format(name),
'-Site', r"'{0}'".format(site),
'-PhysicalPath', r"'{0}'".format(sourcepath)]
if app != _DEFAULT_APP:
ps_cmd.extend(['-Application', r"'{0}'".format(app)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create virtual directory: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_vdirs = list_vdirs(site, app)
if name in new_vdirs:
log.debug('Virtual directory created successfully: %s', name)
return True
log.error('Unable to create virtual directory: %s', name)
return False | python | def create_vdir(name, site, sourcepath, app=_DEFAULT_APP):
'''
Create an IIS virtual directory.
.. note::
This function only validates against the virtual directory name, and
will return True even if the virtual directory already exists with a
different configuration. It will not modify the configuration of an
existing virtual directory.
Args:
name (str): The virtual directory name.
site (str): The IIS site name.
sourcepath (str): The physical path.
app (str): The IIS application.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_vdir name='vd0' site='site0' sourcepath='C:\\inetpub\\vdirs\\vd0'
'''
current_vdirs = list_vdirs(site, app)
if name in current_vdirs:
log.debug('Virtual directory already present: %s', name)
return True
# The target physical path must exist.
if not os.path.isdir(sourcepath):
log.error('Path is not present: %s', sourcepath)
return False
ps_cmd = ['New-WebVirtualDirectory',
'-Name', r"'{0}'".format(name),
'-Site', r"'{0}'".format(site),
'-PhysicalPath', r"'{0}'".format(sourcepath)]
if app != _DEFAULT_APP:
ps_cmd.extend(['-Application', r"'{0}'".format(app)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to create virtual directory: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_vdirs = list_vdirs(site, app)
if name in new_vdirs:
log.debug('Virtual directory created successfully: %s', name)
return True
log.error('Unable to create virtual directory: %s', name)
return False | [
"def",
"create_vdir",
"(",
"name",
",",
"site",
",",
"sourcepath",
",",
"app",
"=",
"_DEFAULT_APP",
")",
":",
"current_vdirs",
"=",
"list_vdirs",
"(",
"site",
",",
"app",
")",
"if",
"name",
"in",
"current_vdirs",
":",
"log",
".",
"debug",
"(",
"'Virtual ... | Create an IIS virtual directory.
.. note::
This function only validates against the virtual directory name, and
will return True even if the virtual directory already exists with a
different configuration. It will not modify the configuration of an
existing virtual directory.
Args:
name (str): The virtual directory name.
site (str): The IIS site name.
sourcepath (str): The physical path.
app (str): The IIS application.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_vdir name='vd0' site='site0' sourcepath='C:\\inetpub\\vdirs\\vd0' | [
"Create",
"an",
"IIS",
"virtual",
"directory",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1589-L1648 | train |
saltstack/salt | salt/modules/win_iis.py | remove_vdir | def remove_vdir(name, site, app=_DEFAULT_APP):
'''
Remove an IIS virtual directory.
Args:
name (str): The virtual directory name.
site (str): The IIS site name.
app (str): The IIS application.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_vdir name='vdir0' site='site0'
'''
current_vdirs = list_vdirs(site, app)
app_path = os.path.join(*app.rstrip('/').split('/'))
if app_path:
app_path = '{0}\\'.format(app_path)
vdir_path = r'IIS:\Sites\{0}\{1}{2}'.format(site, app_path, name)
if name not in current_vdirs:
log.debug('Virtual directory already absent: %s', name)
return True
# We use Remove-Item here instead of Remove-WebVirtualDirectory, since the
# latter has a bug that causes it to always prompt for user input.
ps_cmd = ['Remove-Item',
'-Path', r"'{0}'".format(vdir_path),
'-Recurse']
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove virtual directory: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_vdirs = list_vdirs(site, app)
if name not in new_vdirs:
log.debug('Virtual directory removed successfully: %s', name)
return True
log.error('Unable to remove virtual directory: %s', name)
return False | python | def remove_vdir(name, site, app=_DEFAULT_APP):
'''
Remove an IIS virtual directory.
Args:
name (str): The virtual directory name.
site (str): The IIS site name.
app (str): The IIS application.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_vdir name='vdir0' site='site0'
'''
current_vdirs = list_vdirs(site, app)
app_path = os.path.join(*app.rstrip('/').split('/'))
if app_path:
app_path = '{0}\\'.format(app_path)
vdir_path = r'IIS:\Sites\{0}\{1}{2}'.format(site, app_path, name)
if name not in current_vdirs:
log.debug('Virtual directory already absent: %s', name)
return True
# We use Remove-Item here instead of Remove-WebVirtualDirectory, since the
# latter has a bug that causes it to always prompt for user input.
ps_cmd = ['Remove-Item',
'-Path', r"'{0}'".format(vdir_path),
'-Recurse']
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove virtual directory: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_vdirs = list_vdirs(site, app)
if name not in new_vdirs:
log.debug('Virtual directory removed successfully: %s', name)
return True
log.error('Unable to remove virtual directory: %s', name)
return False | [
"def",
"remove_vdir",
"(",
"name",
",",
"site",
",",
"app",
"=",
"_DEFAULT_APP",
")",
":",
"current_vdirs",
"=",
"list_vdirs",
"(",
"site",
",",
"app",
")",
"app_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"app",
".",
"rstrip",
"(",
"'/'",
... | Remove an IIS virtual directory.
Args:
name (str): The virtual directory name.
site (str): The IIS site name.
app (str): The IIS application.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_vdir name='vdir0' site='site0' | [
"Remove",
"an",
"IIS",
"virtual",
"directory",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1651-L1701 | train |
saltstack/salt | salt/modules/win_iis.py | create_backup | def create_backup(name):
r'''
Backup an IIS Configuration on the System.
.. versionadded:: 2017.7.0
.. note::
Backups are stored in the ``$env:Windir\System32\inetsrv\backup``
folder.
Args:
name (str): The name to give the backup
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_backup good_config_20170209
'''
if name in list_backups():
raise CommandExecutionError('Backup already present: {0}'.format(name))
ps_cmd = ['Backup-WebConfiguration',
'-Name', "'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to backup web configuration: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
return name in list_backups() | python | def create_backup(name):
r'''
Backup an IIS Configuration on the System.
.. versionadded:: 2017.7.0
.. note::
Backups are stored in the ``$env:Windir\System32\inetsrv\backup``
folder.
Args:
name (str): The name to give the backup
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_backup good_config_20170209
'''
if name in list_backups():
raise CommandExecutionError('Backup already present: {0}'.format(name))
ps_cmd = ['Backup-WebConfiguration',
'-Name', "'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to backup web configuration: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
return name in list_backups() | [
"def",
"create_backup",
"(",
"name",
")",
":",
"if",
"name",
"in",
"list_backups",
"(",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Backup already present: {0}'",
".",
"format",
"(",
"name",
")",
")",
"ps_cmd",
"=",
"[",
"'Backup-WebConfiguration'",
",",
... | r'''
Backup an IIS Configuration on the System.
.. versionadded:: 2017.7.0
.. note::
Backups are stored in the ``$env:Windir\System32\inetsrv\backup``
folder.
Args:
name (str): The name to give the backup
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_backup good_config_20170209 | [
"r",
"Backup",
"an",
"IIS",
"Configuration",
"on",
"the",
"System",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1749-L1784 | train |
saltstack/salt | salt/modules/win_iis.py | remove_backup | def remove_backup(name):
'''
Remove an IIS Configuration backup from the System.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the backup to remove
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_backup backup_20170209
'''
if name not in list_backups():
log.debug('Backup already removed: %s', name)
return True
ps_cmd = ['Remove-WebConfigurationBackup',
'-Name', "'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove web configuration: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
return name not in list_backups() | python | def remove_backup(name):
'''
Remove an IIS Configuration backup from the System.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the backup to remove
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_backup backup_20170209
'''
if name not in list_backups():
log.debug('Backup already removed: %s', name)
return True
ps_cmd = ['Remove-WebConfigurationBackup',
'-Name', "'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove web configuration: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
return name not in list_backups() | [
"def",
"remove_backup",
"(",
"name",
")",
":",
"if",
"name",
"not",
"in",
"list_backups",
"(",
")",
":",
"log",
".",
"debug",
"(",
"'Backup already removed: %s'",
",",
"name",
")",
"return",
"True",
"ps_cmd",
"=",
"[",
"'Remove-WebConfigurationBackup'",
",",
... | Remove an IIS Configuration backup from the System.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the backup to remove
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_backup backup_20170209 | [
"Remove",
"an",
"IIS",
"Configuration",
"backup",
"from",
"the",
"System",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1787-L1819 | train |
saltstack/salt | salt/modules/win_iis.py | list_worker_processes | def list_worker_processes(apppool):
'''
Returns a list of worker processes that correspond to the passed
application pool.
.. versionadded:: 2017.7.0
Args:
apppool (str): The application pool to query
Returns:
dict: A dictionary of worker processes with their process IDs
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_worker_processes 'My App Pool'
'''
ps_cmd = ['Get-ChildItem',
r"'IIS:\AppPools\{0}\WorkerProcesses'".format(apppool)]
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
ret = dict()
for item in items:
ret[item['processId']] = item['appPoolName']
if not ret:
log.warning('No backups found in output: %s', cmd_ret)
return ret | python | def list_worker_processes(apppool):
'''
Returns a list of worker processes that correspond to the passed
application pool.
.. versionadded:: 2017.7.0
Args:
apppool (str): The application pool to query
Returns:
dict: A dictionary of worker processes with their process IDs
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_worker_processes 'My App Pool'
'''
ps_cmd = ['Get-ChildItem',
r"'IIS:\AppPools\{0}\WorkerProcesses'".format(apppool)]
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
ret = dict()
for item in items:
ret[item['processId']] = item['appPoolName']
if not ret:
log.warning('No backups found in output: %s', cmd_ret)
return ret | [
"def",
"list_worker_processes",
"(",
"apppool",
")",
":",
"ps_cmd",
"=",
"[",
"'Get-ChildItem'",
",",
"r\"'IIS:\\AppPools\\{0}\\WorkerProcesses'\"",
".",
"format",
"(",
"apppool",
")",
"]",
"cmd_ret",
"=",
"_srvmgr",
"(",
"cmd",
"=",
"ps_cmd",
",",
"return_json",
... | Returns a list of worker processes that correspond to the passed
application pool.
.. versionadded:: 2017.7.0
Args:
apppool (str): The application pool to query
Returns:
dict: A dictionary of worker processes with their process IDs
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_worker_processes 'My App Pool' | [
"Returns",
"a",
"list",
"of",
"worker",
"processes",
"that",
"correspond",
"to",
"the",
"passed",
"application",
"pool",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1822-L1858 | train |
saltstack/salt | salt/modules/win_iis.py | get_webapp_settings | def get_webapp_settings(name, site, settings):
r'''
.. versionadded:: 2017.7.0
Get the value of the setting for the IIS web application.
.. note::
Params are case sensitive
:param str name: The name of the IIS web application.
:param str site: The site name contains the web application.
Example: Default Web Site
:param str settings: A dictionary of the setting names and their values.
Available settings: physicalPath, applicationPool, userName, password
Returns:
dict: A dictionary of the provided settings and their values.
CLI Example:
.. code-block:: bash
salt '*' win_iis.get_webapp_settings name='app0' site='Default Web Site'
settings="['physicalPath','applicationPool']"
'''
ret = dict()
pscmd = list()
availableSettings = ('physicalPath', 'applicationPool', 'userName', 'password')
if not settings:
log.warning('No settings provided')
return ret
pscmd.append(r'$Settings = @{};')
# Verify setting is ine predefined settings and append relevant query command per setting key
for setting in settings:
if setting in availableSettings:
if setting == "userName" or setting == "password":
pscmd.append(" $Property = Get-WebConfigurationProperty -Filter \"system.applicationHost/sites/site[@name='{0}']/application[@path='/{1}']/virtualDirectory[@path='/']\"".format(site, name))
pscmd.append(r' -Name "{0}" -ErrorAction Stop | select Value;'.format(setting))
pscmd.append(r' $Property = $Property | Select-Object -ExpandProperty Value;')
pscmd.append(r" $Settings['{0}'] = [String] $Property;".format(setting))
pscmd.append(r' $Property = $Null;')
if setting == "physicalPath" or setting == "applicationPool":
pscmd.append(r" $Property = (get-webapplication {0}).{1};".format(name, setting))
pscmd.append(r" $Settings['{0}'] = [String] $Property;".format(setting))
pscmd.append(r' $Property = $Null;')
else:
availSetStr = ', '.join(availableSettings)
message = 'Unexpected setting:' + setting + '. Available settings are: ' + availSetStr
raise SaltInvocationError(message)
pscmd.append(' $Settings')
# Run commands and return data as json
cmd_ret = _srvmgr(cmd=six.text_type().join(pscmd), return_json=True)
# Update dict var to return data
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
if isinstance(items, list):
ret.update(items[0])
else:
ret.update(items)
except ValueError:
log.error('Unable to parse return data as Json.')
if None in six.viewvalues(ret):
message = 'Some values are empty - please validate site and web application names. Some commands are case sensitive'
raise SaltInvocationError(message)
return ret | python | def get_webapp_settings(name, site, settings):
r'''
.. versionadded:: 2017.7.0
Get the value of the setting for the IIS web application.
.. note::
Params are case sensitive
:param str name: The name of the IIS web application.
:param str site: The site name contains the web application.
Example: Default Web Site
:param str settings: A dictionary of the setting names and their values.
Available settings: physicalPath, applicationPool, userName, password
Returns:
dict: A dictionary of the provided settings and their values.
CLI Example:
.. code-block:: bash
salt '*' win_iis.get_webapp_settings name='app0' site='Default Web Site'
settings="['physicalPath','applicationPool']"
'''
ret = dict()
pscmd = list()
availableSettings = ('physicalPath', 'applicationPool', 'userName', 'password')
if not settings:
log.warning('No settings provided')
return ret
pscmd.append(r'$Settings = @{};')
# Verify setting is ine predefined settings and append relevant query command per setting key
for setting in settings:
if setting in availableSettings:
if setting == "userName" or setting == "password":
pscmd.append(" $Property = Get-WebConfigurationProperty -Filter \"system.applicationHost/sites/site[@name='{0}']/application[@path='/{1}']/virtualDirectory[@path='/']\"".format(site, name))
pscmd.append(r' -Name "{0}" -ErrorAction Stop | select Value;'.format(setting))
pscmd.append(r' $Property = $Property | Select-Object -ExpandProperty Value;')
pscmd.append(r" $Settings['{0}'] = [String] $Property;".format(setting))
pscmd.append(r' $Property = $Null;')
if setting == "physicalPath" or setting == "applicationPool":
pscmd.append(r" $Property = (get-webapplication {0}).{1};".format(name, setting))
pscmd.append(r" $Settings['{0}'] = [String] $Property;".format(setting))
pscmd.append(r' $Property = $Null;')
else:
availSetStr = ', '.join(availableSettings)
message = 'Unexpected setting:' + setting + '. Available settings are: ' + availSetStr
raise SaltInvocationError(message)
pscmd.append(' $Settings')
# Run commands and return data as json
cmd_ret = _srvmgr(cmd=six.text_type().join(pscmd), return_json=True)
# Update dict var to return data
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
if isinstance(items, list):
ret.update(items[0])
else:
ret.update(items)
except ValueError:
log.error('Unable to parse return data as Json.')
if None in six.viewvalues(ret):
message = 'Some values are empty - please validate site and web application names. Some commands are case sensitive'
raise SaltInvocationError(message)
return ret | [
"def",
"get_webapp_settings",
"(",
"name",
",",
"site",
",",
"settings",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"pscmd",
"=",
"list",
"(",
")",
"availableSettings",
"=",
"(",
"'physicalPath'",
",",
"'applicationPool'",
",",
"'userName'",
",",
"'password'",
... | r'''
.. versionadded:: 2017.7.0
Get the value of the setting for the IIS web application.
.. note::
Params are case sensitive
:param str name: The name of the IIS web application.
:param str site: The site name contains the web application.
Example: Default Web Site
:param str settings: A dictionary of the setting names and their values.
Available settings: physicalPath, applicationPool, userName, password
Returns:
dict: A dictionary of the provided settings and their values.
CLI Example:
.. code-block:: bash
salt '*' win_iis.get_webapp_settings name='app0' site='Default Web Site'
settings="['physicalPath','applicationPool']" | [
"r",
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1861-L1934 | train |
saltstack/salt | salt/modules/win_iis.py | set_webapp_settings | def set_webapp_settings(name, site, settings):
r'''
.. versionadded:: 2017.7.0
Configure an IIS application.
.. note::
This function only configures an existing app. Params are case
sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
- physicalPath: The physical path of the webapp.
- applicationPool: The application pool for the webapp.
- userName: "connectAs" user
- password: "connectAs" password for user
:return: A boolean representing whether all changes succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_iis.set_webapp_settings name='app0' site='site0' settings="{'physicalPath': 'C:\site0', 'apppool': 'site0'}"
'''
pscmd = list()
current_apps = list_apps(site)
current_sites = list_sites()
availableSettings = ('physicalPath', 'applicationPool', 'userName', 'password')
# Validate params
if name not in current_apps:
msg = "Application" + name + "doesn't exist"
raise SaltInvocationError(msg)
if site not in current_sites:
msg = "Site" + site + "doesn't exist"
raise SaltInvocationError(msg)
if not settings:
msg = "No settings provided"
raise SaltInvocationError(msg)
# Treat all values as strings for the purpose of comparing them to existing values & validate settings exists in predefined settings list
for setting in settings.keys():
if setting in availableSettings:
settings[setting] = six.text_type(settings[setting])
else:
availSetStr = ', '.join(availableSettings)
log.error("Unexpected setting: %s ", setting)
log.error("Available settings: %s", availSetStr)
msg = "Unexpected setting:" + setting + " Available settings:" + availSetStr
raise SaltInvocationError(msg)
# Check if settings already configured
current_settings = get_webapp_settings(
name=name, site=site, settings=settings.keys())
if settings == current_settings:
log.warning('Settings already contain the provided values.')
return True
for setting in settings:
# If the value is numeric, don't treat it as a string in PowerShell.
try:
complex(settings[setting])
value = settings[setting]
except ValueError:
value = "'{0}'".format(settings[setting])
# Append relevant update command per setting key
if setting == "userName" or setting == "password":
pscmd.append(" Set-WebConfigurationProperty -Filter \"system.applicationHost/sites/site[@name='{0}']/application[@path='/{1}']/virtualDirectory[@path='/']\"".format(site, name))
pscmd.append(" -Name \"{0}\" -Value {1};".format(setting, value))
if setting == "physicalPath" or setting == "applicationPool":
pscmd.append(r' Set-ItemProperty "IIS:\Sites\{0}\{1}" -Name {2} -Value {3};'.format(site, name, setting, value))
if setting == "physicalPath":
if not os.path.isdir(settings[setting]):
msg = 'Path is not present: ' + settings[setting]
raise SaltInvocationError(msg)
# Run commands
cmd_ret = _srvmgr(pscmd)
# Verify commands completed successfully
if cmd_ret['retcode'] != 0:
msg = 'Unable to set settings for web application {0}'.format(name)
raise SaltInvocationError(msg)
# verify changes
new_settings = get_webapp_settings(
name=name, site=site, settings=settings.keys())
failed_settings = dict()
for setting in settings:
if six.text_type(settings[setting]) != six.text_type(new_settings[setting]):
failed_settings[setting] = settings[setting]
if failed_settings:
log.error('Failed to change settings: %s', failed_settings)
return False
log.debug('Settings configured successfully: %s', list(settings))
return True | python | def set_webapp_settings(name, site, settings):
r'''
.. versionadded:: 2017.7.0
Configure an IIS application.
.. note::
This function only configures an existing app. Params are case
sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
- physicalPath: The physical path of the webapp.
- applicationPool: The application pool for the webapp.
- userName: "connectAs" user
- password: "connectAs" password for user
:return: A boolean representing whether all changes succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_iis.set_webapp_settings name='app0' site='site0' settings="{'physicalPath': 'C:\site0', 'apppool': 'site0'}"
'''
pscmd = list()
current_apps = list_apps(site)
current_sites = list_sites()
availableSettings = ('physicalPath', 'applicationPool', 'userName', 'password')
# Validate params
if name not in current_apps:
msg = "Application" + name + "doesn't exist"
raise SaltInvocationError(msg)
if site not in current_sites:
msg = "Site" + site + "doesn't exist"
raise SaltInvocationError(msg)
if not settings:
msg = "No settings provided"
raise SaltInvocationError(msg)
# Treat all values as strings for the purpose of comparing them to existing values & validate settings exists in predefined settings list
for setting in settings.keys():
if setting in availableSettings:
settings[setting] = six.text_type(settings[setting])
else:
availSetStr = ', '.join(availableSettings)
log.error("Unexpected setting: %s ", setting)
log.error("Available settings: %s", availSetStr)
msg = "Unexpected setting:" + setting + " Available settings:" + availSetStr
raise SaltInvocationError(msg)
# Check if settings already configured
current_settings = get_webapp_settings(
name=name, site=site, settings=settings.keys())
if settings == current_settings:
log.warning('Settings already contain the provided values.')
return True
for setting in settings:
# If the value is numeric, don't treat it as a string in PowerShell.
try:
complex(settings[setting])
value = settings[setting]
except ValueError:
value = "'{0}'".format(settings[setting])
# Append relevant update command per setting key
if setting == "userName" or setting == "password":
pscmd.append(" Set-WebConfigurationProperty -Filter \"system.applicationHost/sites/site[@name='{0}']/application[@path='/{1}']/virtualDirectory[@path='/']\"".format(site, name))
pscmd.append(" -Name \"{0}\" -Value {1};".format(setting, value))
if setting == "physicalPath" or setting == "applicationPool":
pscmd.append(r' Set-ItemProperty "IIS:\Sites\{0}\{1}" -Name {2} -Value {3};'.format(site, name, setting, value))
if setting == "physicalPath":
if not os.path.isdir(settings[setting]):
msg = 'Path is not present: ' + settings[setting]
raise SaltInvocationError(msg)
# Run commands
cmd_ret = _srvmgr(pscmd)
# Verify commands completed successfully
if cmd_ret['retcode'] != 0:
msg = 'Unable to set settings for web application {0}'.format(name)
raise SaltInvocationError(msg)
# verify changes
new_settings = get_webapp_settings(
name=name, site=site, settings=settings.keys())
failed_settings = dict()
for setting in settings:
if six.text_type(settings[setting]) != six.text_type(new_settings[setting]):
failed_settings[setting] = settings[setting]
if failed_settings:
log.error('Failed to change settings: %s', failed_settings)
return False
log.debug('Settings configured successfully: %s', list(settings))
return True | [
"def",
"set_webapp_settings",
"(",
"name",
",",
"site",
",",
"settings",
")",
":",
"pscmd",
"=",
"list",
"(",
")",
"current_apps",
"=",
"list_apps",
"(",
"site",
")",
"current_sites",
"=",
"list_sites",
"(",
")",
"availableSettings",
"=",
"(",
"'physicalPath... | r'''
.. versionadded:: 2017.7.0
Configure an IIS application.
.. note::
This function only configures an existing app. Params are case
sensitive.
:param str name: The IIS application.
:param str site: The IIS site name.
:param str settings: A dictionary of the setting names and their values.
- physicalPath: The physical path of the webapp.
- applicationPool: The application pool for the webapp.
- userName: "connectAs" user
- password: "connectAs" password for user
:return: A boolean representing whether all changes succeeded.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' win_iis.set_webapp_settings name='app0' site='site0' settings="{'physicalPath': 'C:\site0', 'apppool': 'site0'}" | [
"r",
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1937-L2042 | train |
saltstack/salt | salt/modules/win_iis.py | get_webconfiguration_settings | def get_webconfiguration_settings(name, settings, location=''):
r'''
Get the webconfiguration settings for the IIS PSPath.
Args:
name (str): The PSPath of the IIS webconfiguration settings.
settings (list): A list of dictionaries containing setting name and filter.
location (str): The location of the settings (optional)
Returns:
dict: A list of dictionaries containing setting name, filter and value.
CLI Example:
.. code-block:: bash
salt '*' win_iis.get_webconfiguration_settings name='IIS:\' settings="[{'name': 'enabled', 'filter': 'system.webServer/security/authentication/anonymousAuthentication'}]"
'''
ret = {}
ps_cmd = []
ps_cmd_validate = []
if not settings:
log.warning('No settings provided')
return ret
settings = _prepare_settings(name, settings)
ps_cmd.append(r'$Settings = New-Object System.Collections.ArrayList;')
for setting in settings:
# Build the commands to verify that the property names are valid.
ps_cmd_validate.extend(['Get-WebConfigurationProperty',
'-PSPath', "'{0}'".format(name),
'-Filter', "'{0}'".format(setting['filter']),
'-Name', "'{0}'".format(setting['name']),
'-Location', "'{0}'".format(location),
'-ErrorAction', 'Stop',
'|', 'Out-Null;'])
# Some ItemProperties are Strings and others are ConfigurationAttributes.
# Since the former doesn't have a Value property, we need to account
# for this.
ps_cmd.append("$Property = Get-WebConfigurationProperty -PSPath '{0}'".format(name))
ps_cmd.append("-Name '{0}' -Filter '{1}' -Location '{2}' -ErrorAction Stop;".format(setting['name'], setting['filter'], location))
if setting['name'].split('.')[-1] == 'Collection':
if 'value' in setting:
ps_cmd.append("$Property = $Property | select -Property {0} ;"
.format(",".join(list(setting['value'][0].keys()))))
ps_cmd.append("$Settings.add(@{{filter='{0}';name='{1}';location='{2}';value=[System.Collections.ArrayList] @($Property)}})| Out-Null;"
.format(setting['filter'], setting['name'], location))
else:
ps_cmd.append(r'if (([String]::IsNullOrEmpty($Property) -eq $False) -and')
ps_cmd.append(r"($Property.GetType()).Name -eq 'ConfigurationAttribute') {")
ps_cmd.append(r'$Property = $Property | Select-Object')
ps_cmd.append(r'-ExpandProperty Value };')
ps_cmd.append("$Settings.add(@{{filter='{0}';name='{1}';location='{2}';value=[String] $Property}})| Out-Null;"
.format(setting['filter'], setting['name'], location))
ps_cmd.append(r'$Property = $Null;')
# Validate the setting names that were passed in.
cmd_ret = _srvmgr(cmd=ps_cmd_validate, return_json=True)
if cmd_ret['retcode'] != 0:
message = 'One or more invalid property names were specified for the provided container.'
raise SaltInvocationError(message)
ps_cmd.append('$Settings')
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
ret = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
return ret | python | def get_webconfiguration_settings(name, settings, location=''):
r'''
Get the webconfiguration settings for the IIS PSPath.
Args:
name (str): The PSPath of the IIS webconfiguration settings.
settings (list): A list of dictionaries containing setting name and filter.
location (str): The location of the settings (optional)
Returns:
dict: A list of dictionaries containing setting name, filter and value.
CLI Example:
.. code-block:: bash
salt '*' win_iis.get_webconfiguration_settings name='IIS:\' settings="[{'name': 'enabled', 'filter': 'system.webServer/security/authentication/anonymousAuthentication'}]"
'''
ret = {}
ps_cmd = []
ps_cmd_validate = []
if not settings:
log.warning('No settings provided')
return ret
settings = _prepare_settings(name, settings)
ps_cmd.append(r'$Settings = New-Object System.Collections.ArrayList;')
for setting in settings:
# Build the commands to verify that the property names are valid.
ps_cmd_validate.extend(['Get-WebConfigurationProperty',
'-PSPath', "'{0}'".format(name),
'-Filter', "'{0}'".format(setting['filter']),
'-Name', "'{0}'".format(setting['name']),
'-Location', "'{0}'".format(location),
'-ErrorAction', 'Stop',
'|', 'Out-Null;'])
# Some ItemProperties are Strings and others are ConfigurationAttributes.
# Since the former doesn't have a Value property, we need to account
# for this.
ps_cmd.append("$Property = Get-WebConfigurationProperty -PSPath '{0}'".format(name))
ps_cmd.append("-Name '{0}' -Filter '{1}' -Location '{2}' -ErrorAction Stop;".format(setting['name'], setting['filter'], location))
if setting['name'].split('.')[-1] == 'Collection':
if 'value' in setting:
ps_cmd.append("$Property = $Property | select -Property {0} ;"
.format(",".join(list(setting['value'][0].keys()))))
ps_cmd.append("$Settings.add(@{{filter='{0}';name='{1}';location='{2}';value=[System.Collections.ArrayList] @($Property)}})| Out-Null;"
.format(setting['filter'], setting['name'], location))
else:
ps_cmd.append(r'if (([String]::IsNullOrEmpty($Property) -eq $False) -and')
ps_cmd.append(r"($Property.GetType()).Name -eq 'ConfigurationAttribute') {")
ps_cmd.append(r'$Property = $Property | Select-Object')
ps_cmd.append(r'-ExpandProperty Value };')
ps_cmd.append("$Settings.add(@{{filter='{0}';name='{1}';location='{2}';value=[String] $Property}})| Out-Null;"
.format(setting['filter'], setting['name'], location))
ps_cmd.append(r'$Property = $Null;')
# Validate the setting names that were passed in.
cmd_ret = _srvmgr(cmd=ps_cmd_validate, return_json=True)
if cmd_ret['retcode'] != 0:
message = 'One or more invalid property names were specified for the provided container.'
raise SaltInvocationError(message)
ps_cmd.append('$Settings')
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
ret = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
return ret | [
"def",
"get_webconfiguration_settings",
"(",
"name",
",",
"settings",
",",
"location",
"=",
"''",
")",
":",
"ret",
"=",
"{",
"}",
"ps_cmd",
"=",
"[",
"]",
"ps_cmd_validate",
"=",
"[",
"]",
"if",
"not",
"settings",
":",
"log",
".",
"warning",
"(",
"'No ... | r'''
Get the webconfiguration settings for the IIS PSPath.
Args:
name (str): The PSPath of the IIS webconfiguration settings.
settings (list): A list of dictionaries containing setting name and filter.
location (str): The location of the settings (optional)
Returns:
dict: A list of dictionaries containing setting name, filter and value.
CLI Example:
.. code-block:: bash
salt '*' win_iis.get_webconfiguration_settings name='IIS:\' settings="[{'name': 'enabled', 'filter': 'system.webServer/security/authentication/anonymousAuthentication'}]" | [
"r",
"Get",
"the",
"webconfiguration",
"settings",
"for",
"the",
"IIS",
"PSPath",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L2045-L2122 | train |
saltstack/salt | salt/modules/win_iis.py | set_webconfiguration_settings | def set_webconfiguration_settings(name, settings, location=''):
r'''
Set the value of the setting for an IIS container.
Args:
name (str): The PSPath of the IIS webconfiguration settings.
settings (list): A list of dictionaries containing setting name, filter and value.
location (str): The location of the settings (optional)
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.set_webconfiguration_settings name='IIS:\' settings="[{'name': 'enabled', 'filter': 'system.webServer/security/authentication/anonymousAuthentication', 'value': False}]"
'''
ps_cmd = []
if not settings:
log.warning('No settings provided')
return False
settings = _prepare_settings(name, settings)
# Treat all values as strings for the purpose of comparing them to existing values.
for idx, setting in enumerate(settings):
if setting['name'].split('.')[-1] != 'Collection':
settings[idx]['value'] = six.text_type(setting['value'])
current_settings = get_webconfiguration_settings(
name=name, settings=settings, location=location)
if settings == current_settings:
log.debug('Settings already contain the provided values.')
return True
for setting in settings:
# If the value is numeric, don't treat it as a string in PowerShell.
if setting['name'].split('.')[-1] != 'Collection':
try:
complex(setting['value'])
value = setting['value']
except ValueError:
value = "'{0}'".format(setting['value'])
else:
configelement_list = []
for value_item in setting['value']:
configelement_construct = []
for key, value in value_item.items():
configelement_construct.append("{0}='{1}'".format(key, value))
configelement_list.append('@{' + ';'.join(configelement_construct) + '}')
value = ','.join(configelement_list)
ps_cmd.extend(['Set-WebConfigurationProperty',
'-PSPath', "'{0}'".format(name),
'-Filter', "'{0}'".format(setting['filter']),
'-Name', "'{0}'".format(setting['name']),
'-Location', "'{0}'".format(location),
'-Value', '{0};'.format(value)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to set settings for {0}'.format(name)
raise CommandExecutionError(msg)
# Get the fields post-change so that we can verify tht all values
# were modified successfully. Track the ones that weren't.
new_settings = get_webconfiguration_settings(
name=name, settings=settings, location=location)
failed_settings = []
for idx, setting in enumerate(settings):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((not is_collection and six.text_type(setting['value']) != six.text_type(new_settings[idx]['value']))
or (is_collection and list(map(dict, setting['value'])) != list(map(dict, new_settings[idx]['value'])))):
failed_settings.append(setting)
if failed_settings:
log.error('Failed to change settings: %s', failed_settings)
return False
log.debug('Settings configured successfully: %s', settings)
return True | python | def set_webconfiguration_settings(name, settings, location=''):
r'''
Set the value of the setting for an IIS container.
Args:
name (str): The PSPath of the IIS webconfiguration settings.
settings (list): A list of dictionaries containing setting name, filter and value.
location (str): The location of the settings (optional)
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.set_webconfiguration_settings name='IIS:\' settings="[{'name': 'enabled', 'filter': 'system.webServer/security/authentication/anonymousAuthentication', 'value': False}]"
'''
ps_cmd = []
if not settings:
log.warning('No settings provided')
return False
settings = _prepare_settings(name, settings)
# Treat all values as strings for the purpose of comparing them to existing values.
for idx, setting in enumerate(settings):
if setting['name'].split('.')[-1] != 'Collection':
settings[idx]['value'] = six.text_type(setting['value'])
current_settings = get_webconfiguration_settings(
name=name, settings=settings, location=location)
if settings == current_settings:
log.debug('Settings already contain the provided values.')
return True
for setting in settings:
# If the value is numeric, don't treat it as a string in PowerShell.
if setting['name'].split('.')[-1] != 'Collection':
try:
complex(setting['value'])
value = setting['value']
except ValueError:
value = "'{0}'".format(setting['value'])
else:
configelement_list = []
for value_item in setting['value']:
configelement_construct = []
for key, value in value_item.items():
configelement_construct.append("{0}='{1}'".format(key, value))
configelement_list.append('@{' + ';'.join(configelement_construct) + '}')
value = ','.join(configelement_list)
ps_cmd.extend(['Set-WebConfigurationProperty',
'-PSPath', "'{0}'".format(name),
'-Filter', "'{0}'".format(setting['filter']),
'-Name', "'{0}'".format(setting['name']),
'-Location', "'{0}'".format(location),
'-Value', '{0};'.format(value)])
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to set settings for {0}'.format(name)
raise CommandExecutionError(msg)
# Get the fields post-change so that we can verify tht all values
# were modified successfully. Track the ones that weren't.
new_settings = get_webconfiguration_settings(
name=name, settings=settings, location=location)
failed_settings = []
for idx, setting in enumerate(settings):
is_collection = setting['name'].split('.')[-1] == 'Collection'
if ((not is_collection and six.text_type(setting['value']) != six.text_type(new_settings[idx]['value']))
or (is_collection and list(map(dict, setting['value'])) != list(map(dict, new_settings[idx]['value'])))):
failed_settings.append(setting)
if failed_settings:
log.error('Failed to change settings: %s', failed_settings)
return False
log.debug('Settings configured successfully: %s', settings)
return True | [
"def",
"set_webconfiguration_settings",
"(",
"name",
",",
"settings",
",",
"location",
"=",
"''",
")",
":",
"ps_cmd",
"=",
"[",
"]",
"if",
"not",
"settings",
":",
"log",
".",
"warning",
"(",
"'No settings provided'",
")",
"return",
"False",
"settings",
"=",
... | r'''
Set the value of the setting for an IIS container.
Args:
name (str): The PSPath of the IIS webconfiguration settings.
settings (list): A list of dictionaries containing setting name, filter and value.
location (str): The location of the settings (optional)
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.set_webconfiguration_settings name='IIS:\' settings="[{'name': 'enabled', 'filter': 'system.webServer/security/authentication/anonymousAuthentication', 'value': False}]" | [
"r",
"Set",
"the",
"value",
"of",
"the",
"setting",
"for",
"an",
"IIS",
"container",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L2125-L2214 | train |
saltstack/salt | salt/runners/ddns.py | create | def create(zone, name, ttl, rdtype, data, keyname, keyfile, nameserver,
timeout, port=53, keyalgorithm='hmac-md5'):
'''
Create a DNS record. The nameserver must be an IP address and the master running
this runner must have create privileges on that server.
CLI Example:
.. code-block:: bash
salt-run ddns.create domain.com my-test-vm 3600 A 10.20.30.40 my-tsig-key /etc/salt/tsig.keyring 10.0.0.1 5
'''
if zone in name:
name = name.replace(zone, '').rstrip('.')
fqdn = '{0}.{1}'.format(name, zone)
request = dns.message.make_query(fqdn, rdtype)
answer = dns.query.udp(request, nameserver, timeout, port)
rdata_value = dns.rdatatype.from_text(rdtype)
rdata = dns.rdata.from_text(dns.rdataclass.IN, rdata_value, data)
for rrset in answer.answer:
if rdata in rrset.items:
return {fqdn: 'Record of type \'{0}\' already exists with ttl of {1}'.format(rdtype, rrset.ttl)}
keyring = _get_keyring(keyfile)
dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname,
keyalgorithm=keyalgorithm)
dns_update.add(name, ttl, rdata)
answer = dns.query.udp(dns_update, nameserver, timeout, port)
if answer.rcode() > 0:
return {fqdn: 'Failed to create record of type \'{0}\''.format(rdtype)}
return {fqdn: 'Created record of type \'{0}\': {1} -> {2}'.format(rdtype, fqdn, data)} | python | def create(zone, name, ttl, rdtype, data, keyname, keyfile, nameserver,
timeout, port=53, keyalgorithm='hmac-md5'):
'''
Create a DNS record. The nameserver must be an IP address and the master running
this runner must have create privileges on that server.
CLI Example:
.. code-block:: bash
salt-run ddns.create domain.com my-test-vm 3600 A 10.20.30.40 my-tsig-key /etc/salt/tsig.keyring 10.0.0.1 5
'''
if zone in name:
name = name.replace(zone, '').rstrip('.')
fqdn = '{0}.{1}'.format(name, zone)
request = dns.message.make_query(fqdn, rdtype)
answer = dns.query.udp(request, nameserver, timeout, port)
rdata_value = dns.rdatatype.from_text(rdtype)
rdata = dns.rdata.from_text(dns.rdataclass.IN, rdata_value, data)
for rrset in answer.answer:
if rdata in rrset.items:
return {fqdn: 'Record of type \'{0}\' already exists with ttl of {1}'.format(rdtype, rrset.ttl)}
keyring = _get_keyring(keyfile)
dns_update = dns.update.Update(zone, keyring=keyring, keyname=keyname,
keyalgorithm=keyalgorithm)
dns_update.add(name, ttl, rdata)
answer = dns.query.udp(dns_update, nameserver, timeout, port)
if answer.rcode() > 0:
return {fqdn: 'Failed to create record of type \'{0}\''.format(rdtype)}
return {fqdn: 'Created record of type \'{0}\': {1} -> {2}'.format(rdtype, fqdn, data)} | [
"def",
"create",
"(",
"zone",
",",
"name",
",",
"ttl",
",",
"rdtype",
",",
"data",
",",
"keyname",
",",
"keyfile",
",",
"nameserver",
",",
"timeout",
",",
"port",
"=",
"53",
",",
"keyalgorithm",
"=",
"'hmac-md5'",
")",
":",
"if",
"zone",
"in",
"name"... | Create a DNS record. The nameserver must be an IP address and the master running
this runner must have create privileges on that server.
CLI Example:
.. code-block:: bash
salt-run ddns.create domain.com my-test-vm 3600 A 10.20.30.40 my-tsig-key /etc/salt/tsig.keyring 10.0.0.1 5 | [
"Create",
"a",
"DNS",
"record",
".",
"The",
"nameserver",
"must",
"be",
"an",
"IP",
"address",
"and",
"the",
"master",
"running",
"this",
"runner",
"must",
"have",
"create",
"privileges",
"on",
"that",
"server",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/ddns.py#L56-L91 | train |
saltstack/salt | salt/runners/ddns.py | add_host | def add_host(zone, name, ttl, ip, keyname, keyfile, nameserver, timeout,
port=53, keyalgorithm='hmac-md5'):
'''
Create both A and PTR (reverse) records for a host.
CLI Example:
.. code-block:: bash
salt-run ddns.add_host domain.com my-test-vm 3600 10.20.30.40 my-tsig-key /etc/salt/tsig.keyring 10.0.0.1 5
'''
res = []
if zone in name:
name = name.replace(zone, '').rstrip('.')
fqdn = '{0}.{1}'.format(name, zone)
ret = create(zone, name, ttl, 'A', ip, keyname, keyfile, nameserver,
timeout, port, keyalgorithm)
res.append(ret[fqdn])
parts = ip.split('.')[::-1]
i = len(parts)
popped = []
# Iterate over possible reverse zones
while i > 1:
p = parts.pop(0)
i -= 1
popped.append(p)
zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.')
name = '.'.join(popped)
rev_fqdn = '{0}.{1}'.format(name, zone)
ret = create(zone, name, ttl, 'PTR', "{0}.".format(fqdn), keyname,
keyfile, nameserver, timeout, port, keyalgorithm)
if "Created" in ret[rev_fqdn]:
res.append(ret[rev_fqdn])
return {fqdn: res}
res.append(ret[rev_fqdn])
return {fqdn: res} | python | def add_host(zone, name, ttl, ip, keyname, keyfile, nameserver, timeout,
port=53, keyalgorithm='hmac-md5'):
'''
Create both A and PTR (reverse) records for a host.
CLI Example:
.. code-block:: bash
salt-run ddns.add_host domain.com my-test-vm 3600 10.20.30.40 my-tsig-key /etc/salt/tsig.keyring 10.0.0.1 5
'''
res = []
if zone in name:
name = name.replace(zone, '').rstrip('.')
fqdn = '{0}.{1}'.format(name, zone)
ret = create(zone, name, ttl, 'A', ip, keyname, keyfile, nameserver,
timeout, port, keyalgorithm)
res.append(ret[fqdn])
parts = ip.split('.')[::-1]
i = len(parts)
popped = []
# Iterate over possible reverse zones
while i > 1:
p = parts.pop(0)
i -= 1
popped.append(p)
zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.')
name = '.'.join(popped)
rev_fqdn = '{0}.{1}'.format(name, zone)
ret = create(zone, name, ttl, 'PTR', "{0}.".format(fqdn), keyname,
keyfile, nameserver, timeout, port, keyalgorithm)
if "Created" in ret[rev_fqdn]:
res.append(ret[rev_fqdn])
return {fqdn: res}
res.append(ret[rev_fqdn])
return {fqdn: res} | [
"def",
"add_host",
"(",
"zone",
",",
"name",
",",
"ttl",
",",
"ip",
",",
"keyname",
",",
"keyfile",
",",
"nameserver",
",",
"timeout",
",",
"port",
"=",
"53",
",",
"keyalgorithm",
"=",
"'hmac-md5'",
")",
":",
"res",
"=",
"[",
"]",
"if",
"zone",
"in... | Create both A and PTR (reverse) records for a host.
CLI Example:
.. code-block:: bash
salt-run ddns.add_host domain.com my-test-vm 3600 10.20.30.40 my-tsig-key /etc/salt/tsig.keyring 10.0.0.1 5 | [
"Create",
"both",
"A",
"and",
"PTR",
"(",
"reverse",
")",
"records",
"for",
"a",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/ddns.py#L187-L229 | train |
saltstack/salt | salt/runners/ddns.py | delete_host | def delete_host(zone, name, keyname, keyfile, nameserver, timeout, port=53,
keyalgorithm='hmac-md5'):
'''
Delete both forward (A) and reverse (PTR) records for a host only if the
forward (A) record exists.
CLI Example:
.. code-block:: bash
salt-run ddns.delete_host domain.com my-test-vm my-tsig-key /etc/salt/tsig.keyring 10.0.0.1 5
'''
res = []
if zone in name:
name = name.replace(zone, '').rstrip('.')
fqdn = '{0}.{1}'.format(name, zone)
request = dns.message.make_query(fqdn, 'A')
answer = dns.query.udp(request, nameserver, timeout, port)
try:
ips = [i.address for i in answer.answer[0].items]
except IndexError:
ips = []
ret = delete(zone, name, keyname, keyfile, nameserver, timeout, port=port,
keyalgorithm=keyalgorithm)
res.append("{0} of type \'A\'".format(ret[fqdn]))
for ip in ips:
parts = ip.split('.')[::-1]
i = len(parts)
popped = []
# Iterate over possible reverse zones
while i > 1:
p = parts.pop(0)
i -= 1
popped.append(p)
zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.')
name = '.'.join(popped)
rev_fqdn = '{0}.{1}'.format(name, zone)
ret = delete(zone, name, keyname, keyfile, nameserver, timeout,
'PTR', "{0}.".format(fqdn), port, keyalgorithm)
if "Deleted" in ret[rev_fqdn]:
res.append("{0} of type \'PTR\'".format(ret[rev_fqdn]))
return {fqdn: res}
res.append(ret[rev_fqdn])
return {fqdn: res} | python | def delete_host(zone, name, keyname, keyfile, nameserver, timeout, port=53,
keyalgorithm='hmac-md5'):
'''
Delete both forward (A) and reverse (PTR) records for a host only if the
forward (A) record exists.
CLI Example:
.. code-block:: bash
salt-run ddns.delete_host domain.com my-test-vm my-tsig-key /etc/salt/tsig.keyring 10.0.0.1 5
'''
res = []
if zone in name:
name = name.replace(zone, '').rstrip('.')
fqdn = '{0}.{1}'.format(name, zone)
request = dns.message.make_query(fqdn, 'A')
answer = dns.query.udp(request, nameserver, timeout, port)
try:
ips = [i.address for i in answer.answer[0].items]
except IndexError:
ips = []
ret = delete(zone, name, keyname, keyfile, nameserver, timeout, port=port,
keyalgorithm=keyalgorithm)
res.append("{0} of type \'A\'".format(ret[fqdn]))
for ip in ips:
parts = ip.split('.')[::-1]
i = len(parts)
popped = []
# Iterate over possible reverse zones
while i > 1:
p = parts.pop(0)
i -= 1
popped.append(p)
zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.')
name = '.'.join(popped)
rev_fqdn = '{0}.{1}'.format(name, zone)
ret = delete(zone, name, keyname, keyfile, nameserver, timeout,
'PTR', "{0}.".format(fqdn), port, keyalgorithm)
if "Deleted" in ret[rev_fqdn]:
res.append("{0} of type \'PTR\'".format(ret[rev_fqdn]))
return {fqdn: res}
res.append(ret[rev_fqdn])
return {fqdn: res} | [
"def",
"delete_host",
"(",
"zone",
",",
"name",
",",
"keyname",
",",
"keyfile",
",",
"nameserver",
",",
"timeout",
",",
"port",
"=",
"53",
",",
"keyalgorithm",
"=",
"'hmac-md5'",
")",
":",
"res",
"=",
"[",
"]",
"if",
"zone",
"in",
"name",
":",
"name"... | Delete both forward (A) and reverse (PTR) records for a host only if the
forward (A) record exists.
CLI Example:
.. code-block:: bash
salt-run ddns.delete_host domain.com my-test-vm my-tsig-key /etc/salt/tsig.keyring 10.0.0.1 5 | [
"Delete",
"both",
"forward",
"(",
"A",
")",
"and",
"reverse",
"(",
"PTR",
")",
"records",
"for",
"a",
"host",
"only",
"if",
"the",
"forward",
"(",
"A",
")",
"record",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/ddns.py#L232-L282 | train |
saltstack/salt | salt/utils/pkg/deb.py | combine_comments | def combine_comments(comments):
'''
Given a list of comments, or a comment submitted as a string, return a
single line of text containing all of the comments.
'''
if isinstance(comments, list):
for idx in range(len(comments)):
if not isinstance(comments[idx], six.string_types):
comments[idx] = six.text_type(comments[idx])
else:
if not isinstance(comments, six.string_types):
comments = [six.text_type(comments)]
else:
comments = [comments]
return ' '.join(comments).strip() | python | def combine_comments(comments):
'''
Given a list of comments, or a comment submitted as a string, return a
single line of text containing all of the comments.
'''
if isinstance(comments, list):
for idx in range(len(comments)):
if not isinstance(comments[idx], six.string_types):
comments[idx] = six.text_type(comments[idx])
else:
if not isinstance(comments, six.string_types):
comments = [six.text_type(comments)]
else:
comments = [comments]
return ' '.join(comments).strip() | [
"def",
"combine_comments",
"(",
"comments",
")",
":",
"if",
"isinstance",
"(",
"comments",
",",
"list",
")",
":",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"comments",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
"comments",
"[",
"idx",
"]",
",... | Given a list of comments, or a comment submitted as a string, return a
single line of text containing all of the comments. | [
"Given",
"a",
"list",
"of",
"comments",
"or",
"a",
"comment",
"submitted",
"as",
"a",
"string",
"return",
"a",
"single",
"line",
"of",
"text",
"containing",
"all",
"of",
"the",
"comments",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/deb.py#L14-L28 | train |
saltstack/salt | salt/utils/pkg/deb.py | strip_uri | def strip_uri(repo):
'''
Remove the trailing slash from the URI in a repo definition
'''
splits = repo.split()
for idx in range(len(splits)):
if any(splits[idx].startswith(x)
for x in ('http://', 'https://', 'ftp://')):
splits[idx] = splits[idx].rstrip('/')
return ' '.join(splits) | python | def strip_uri(repo):
'''
Remove the trailing slash from the URI in a repo definition
'''
splits = repo.split()
for idx in range(len(splits)):
if any(splits[idx].startswith(x)
for x in ('http://', 'https://', 'ftp://')):
splits[idx] = splits[idx].rstrip('/')
return ' '.join(splits) | [
"def",
"strip_uri",
"(",
"repo",
")",
":",
"splits",
"=",
"repo",
".",
"split",
"(",
")",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"splits",
")",
")",
":",
"if",
"any",
"(",
"splits",
"[",
"idx",
"]",
".",
"startswith",
"(",
"x",
")",
"for... | Remove the trailing slash from the URI in a repo definition | [
"Remove",
"the",
"trailing",
"slash",
"from",
"the",
"URI",
"in",
"a",
"repo",
"definition"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/deb.py#L31-L40 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | _get_si | def _get_si():
'''
Authenticate with vCenter server and return service instance object.
'''
url = config.get_cloud_config_value(
'url', get_configured_provider(), __opts__, search_global=False
)
username = config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
)
password = config.get_cloud_config_value(
'password', get_configured_provider(), __opts__, search_global=False
)
protocol = config.get_cloud_config_value(
'protocol', get_configured_provider(), __opts__, search_global=False, default='https'
)
port = config.get_cloud_config_value(
'port', get_configured_provider(), __opts__, search_global=False, default=443
)
return salt.utils.vmware.get_service_instance(url,
username,
password,
protocol=protocol,
port=port) | python | def _get_si():
'''
Authenticate with vCenter server and return service instance object.
'''
url = config.get_cloud_config_value(
'url', get_configured_provider(), __opts__, search_global=False
)
username = config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
)
password = config.get_cloud_config_value(
'password', get_configured_provider(), __opts__, search_global=False
)
protocol = config.get_cloud_config_value(
'protocol', get_configured_provider(), __opts__, search_global=False, default='https'
)
port = config.get_cloud_config_value(
'port', get_configured_provider(), __opts__, search_global=False, default=443
)
return salt.utils.vmware.get_service_instance(url,
username,
password,
protocol=protocol,
port=port) | [
"def",
"_get_si",
"(",
")",
":",
"url",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'url'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
"username",
"=",
"config",
".",
"get_cloud_config_value",
"(... | Authenticate with vCenter server and return service instance object. | [
"Authenticate",
"with",
"vCenter",
"server",
"and",
"return",
"service",
"instance",
"object",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L238-L263 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | _add_new_ide_controller_helper | def _add_new_ide_controller_helper(ide_controller_label,
controller_key,
bus_number):
'''
Helper function for adding new IDE controllers
.. versionadded:: 2016.3.0
Args:
ide_controller_label: label of the IDE controller
controller_key: if not None, the controller key to use; otherwise it is randomly generated
bus_number: bus number
Returns: created device spec for an IDE controller
'''
if controller_key is None:
controller_key = randint(-200, 250)
ide_spec = vim.vm.device.VirtualDeviceSpec()
ide_spec.device = vim.vm.device.VirtualIDEController()
ide_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
ide_spec.device.key = controller_key
ide_spec.device.busNumber = bus_number
ide_spec.device.deviceInfo = vim.Description()
ide_spec.device.deviceInfo.label = ide_controller_label
ide_spec.device.deviceInfo.summary = ide_controller_label
return ide_spec | python | def _add_new_ide_controller_helper(ide_controller_label,
controller_key,
bus_number):
'''
Helper function for adding new IDE controllers
.. versionadded:: 2016.3.0
Args:
ide_controller_label: label of the IDE controller
controller_key: if not None, the controller key to use; otherwise it is randomly generated
bus_number: bus number
Returns: created device spec for an IDE controller
'''
if controller_key is None:
controller_key = randint(-200, 250)
ide_spec = vim.vm.device.VirtualDeviceSpec()
ide_spec.device = vim.vm.device.VirtualIDEController()
ide_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
ide_spec.device.key = controller_key
ide_spec.device.busNumber = bus_number
ide_spec.device.deviceInfo = vim.Description()
ide_spec.device.deviceInfo.label = ide_controller_label
ide_spec.device.deviceInfo.summary = ide_controller_label
return ide_spec | [
"def",
"_add_new_ide_controller_helper",
"(",
"ide_controller_label",
",",
"controller_key",
",",
"bus_number",
")",
":",
"if",
"controller_key",
"is",
"None",
":",
"controller_key",
"=",
"randint",
"(",
"-",
"200",
",",
"250",
")",
"ide_spec",
"=",
"vim",
".",
... | Helper function for adding new IDE controllers
.. versionadded:: 2016.3.0
Args:
ide_controller_label: label of the IDE controller
controller_key: if not None, the controller key to use; otherwise it is randomly generated
bus_number: bus number
Returns: created device spec for an IDE controller | [
"Helper",
"function",
"for",
"adding",
"new",
"IDE",
"controllers"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L554-L584 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | _valid_ip | def _valid_ip(ip_address):
'''
Check if the IP address is valid and routable
Return either True or False
'''
try:
address = ipaddress.IPv4Address(ip_address)
except ipaddress.AddressValueError:
return False
if address.is_unspecified or \
address.is_loopback or \
address.is_link_local or \
address.is_multicast or \
address.is_reserved:
return False
return True | python | def _valid_ip(ip_address):
'''
Check if the IP address is valid and routable
Return either True or False
'''
try:
address = ipaddress.IPv4Address(ip_address)
except ipaddress.AddressValueError:
return False
if address.is_unspecified or \
address.is_loopback or \
address.is_link_local or \
address.is_multicast or \
address.is_reserved:
return False
return True | [
"def",
"_valid_ip",
"(",
"ip_address",
")",
":",
"try",
":",
"address",
"=",
"ipaddress",
".",
"IPv4Address",
"(",
"ip_address",
")",
"except",
"ipaddress",
".",
"AddressValueError",
":",
"return",
"False",
"if",
"address",
".",
"is_unspecified",
"or",
"addres... | Check if the IP address is valid and routable
Return either True or False | [
"Check",
"if",
"the",
"IP",
"address",
"is",
"valid",
"and",
"routable",
"Return",
"either",
"True",
"or",
"False"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L993-L1011 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | _valid_ip6 | def _valid_ip6(ip_address):
'''
Check if the IPv6 address is valid and routable
Return either True or False
'''
# Validate IPv6 address
try:
address = ipaddress.IPv6Address(ip_address)
except ipaddress.AddressValueError:
return False
if address.is_unspecified or \
address.is_loopback or \
address.is_link_local or \
address.is_multicast or \
address.is_reserved:
return False
if address.ipv4_mapped is not None:
return False
return True | python | def _valid_ip6(ip_address):
'''
Check if the IPv6 address is valid and routable
Return either True or False
'''
# Validate IPv6 address
try:
address = ipaddress.IPv6Address(ip_address)
except ipaddress.AddressValueError:
return False
if address.is_unspecified or \
address.is_loopback or \
address.is_link_local or \
address.is_multicast or \
address.is_reserved:
return False
if address.ipv4_mapped is not None:
return False
return True | [
"def",
"_valid_ip6",
"(",
"ip_address",
")",
":",
"# Validate IPv6 address",
"try",
":",
"address",
"=",
"ipaddress",
".",
"IPv6Address",
"(",
"ip_address",
")",
"except",
"ipaddress",
".",
"AddressValueError",
":",
"return",
"False",
"if",
"address",
".",
"is_u... | Check if the IPv6 address is valid and routable
Return either True or False | [
"Check",
"if",
"the",
"IPv6",
"address",
"is",
"valid",
"and",
"routable",
"Return",
"either",
"True",
"or",
"False"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1014-L1036 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | _master_supports_ipv6 | def _master_supports_ipv6():
'''
Check if the salt master has a valid and
routable IPv6 address available
'''
master_fqdn = salt.utils.network.get_fqhostname()
pillar_util = salt.utils.master.MasterPillarUtil(master_fqdn,
tgt_type='glob',
use_cached_grains=False,
grains_fallback=False,
opts=__opts__)
grains_data = pillar_util.get_minion_grains()
ipv6_addresses = grains_data[master_fqdn]['ipv6']
for address in ipv6_addresses:
if _valid_ip6(address):
return True
return False | python | def _master_supports_ipv6():
'''
Check if the salt master has a valid and
routable IPv6 address available
'''
master_fqdn = salt.utils.network.get_fqhostname()
pillar_util = salt.utils.master.MasterPillarUtil(master_fqdn,
tgt_type='glob',
use_cached_grains=False,
grains_fallback=False,
opts=__opts__)
grains_data = pillar_util.get_minion_grains()
ipv6_addresses = grains_data[master_fqdn]['ipv6']
for address in ipv6_addresses:
if _valid_ip6(address):
return True
return False | [
"def",
"_master_supports_ipv6",
"(",
")",
":",
"master_fqdn",
"=",
"salt",
".",
"utils",
".",
"network",
".",
"get_fqhostname",
"(",
")",
"pillar_util",
"=",
"salt",
".",
"utils",
".",
"master",
".",
"MasterPillarUtil",
"(",
"master_fqdn",
",",
"tgt_type",
"... | Check if the salt master has a valid and
routable IPv6 address available | [
"Check",
"if",
"the",
"salt",
"master",
"has",
"a",
"valid",
"and",
"routable",
"IPv6",
"address",
"available"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1039-L1055 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | _get_hba_type | def _get_hba_type(hba_type):
'''
Convert a string representation of a HostHostBusAdapter into an
object reference.
'''
if hba_type == "parallel":
return vim.host.ParallelScsiHba
elif hba_type == "block":
return vim.host.BlockHba
elif hba_type == "iscsi":
return vim.host.InternetScsiHba
elif hba_type == "fibre":
return vim.host.FibreChannelHba
raise ValueError('Unknown Host Bus Adapter Type') | python | def _get_hba_type(hba_type):
'''
Convert a string representation of a HostHostBusAdapter into an
object reference.
'''
if hba_type == "parallel":
return vim.host.ParallelScsiHba
elif hba_type == "block":
return vim.host.BlockHba
elif hba_type == "iscsi":
return vim.host.InternetScsiHba
elif hba_type == "fibre":
return vim.host.FibreChannelHba
raise ValueError('Unknown Host Bus Adapter Type') | [
"def",
"_get_hba_type",
"(",
"hba_type",
")",
":",
"if",
"hba_type",
"==",
"\"parallel\"",
":",
"return",
"vim",
".",
"host",
".",
"ParallelScsiHba",
"elif",
"hba_type",
"==",
"\"block\"",
":",
"return",
"vim",
".",
"host",
".",
"BlockHba",
"elif",
"hba_type... | Convert a string representation of a HostHostBusAdapter into an
object reference. | [
"Convert",
"a",
"string",
"representation",
"of",
"a",
"HostHostBusAdapter",
"into",
"an",
"object",
"reference",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1484-L1498 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | get_vcenter_version | def get_vcenter_version(kwargs=None, call=None):
'''
Show the vCenter Server version with build number.
CLI Example:
.. code-block:: bash
salt-cloud -f get_vcenter_version my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_vcenter_version function must be called with '
'-f or --function.'
)
# Get the inventory
inv = salt.utils.vmware.get_inventory(_get_si())
return inv.about.fullName | python | def get_vcenter_version(kwargs=None, call=None):
'''
Show the vCenter Server version with build number.
CLI Example:
.. code-block:: bash
salt-cloud -f get_vcenter_version my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_vcenter_version function must be called with '
'-f or --function.'
)
# Get the inventory
inv = salt.utils.vmware.get_inventory(_get_si())
return inv.about.fullName | [
"def",
"get_vcenter_version",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The get_vcenter_version function must be called with '",
"'-f or --function.'",
")",
"# Get the in... | Show the vCenter Server version with build number.
CLI Example:
.. code-block:: bash
salt-cloud -f get_vcenter_version my-vmware-config | [
"Show",
"the",
"vCenter",
"Server",
"version",
"with",
"build",
"number",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1528-L1547 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_datacenters | def list_datacenters(kwargs=None, call=None):
'''
List all the data centers for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datacenters function must be called with '
'-f or --function.'
)
return {'Datacenters': salt.utils.vmware.list_datacenters(_get_si())} | python | def list_datacenters(kwargs=None, call=None):
'''
List all the data centers for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datacenters function must be called with '
'-f or --function.'
)
return {'Datacenters': salt.utils.vmware.list_datacenters(_get_si())} | [
"def",
"list_datacenters",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_datacenters function must be called with '",
"'-f or --function.'",
")",
"return",
"{",
... | List all the data centers for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-vmware-config | [
"List",
"all",
"the",
"data",
"centers",
"for",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1550-L1566 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_portgroups | def list_portgroups(kwargs=None, call=None):
'''
List all the distributed virtual portgroups for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_portgroups my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_portgroups function must be called with '
'-f or --function.'
)
return {'Portgroups': salt.utils.vmware.list_portgroups(_get_si())} | python | def list_portgroups(kwargs=None, call=None):
'''
List all the distributed virtual portgroups for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_portgroups my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_portgroups function must be called with '
'-f or --function.'
)
return {'Portgroups': salt.utils.vmware.list_portgroups(_get_si())} | [
"def",
"list_portgroups",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_portgroups function must be called with '",
"'-f or --function.'",
")",
"return",
"{",
"'... | List all the distributed virtual portgroups for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_portgroups my-vmware-config | [
"List",
"all",
"the",
"distributed",
"virtual",
"portgroups",
"for",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1569-L1585 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_clusters | def list_clusters(kwargs=None, call=None):
'''
List all the clusters for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_clusters my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_clusters function must be called with '
'-f or --function.'
)
return {'Clusters': salt.utils.vmware.list_clusters(_get_si())} | python | def list_clusters(kwargs=None, call=None):
'''
List all the clusters for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_clusters my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_clusters function must be called with '
'-f or --function.'
)
return {'Clusters': salt.utils.vmware.list_clusters(_get_si())} | [
"def",
"list_clusters",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_clusters function must be called with '",
"'-f or --function.'",
")",
"return",
"{",
"'Clus... | List all the clusters for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_clusters my-vmware-config | [
"List",
"all",
"the",
"clusters",
"for",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1588-L1604 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_datastore_clusters | def list_datastore_clusters(kwargs=None, call=None):
'''
List all the datastore clusters for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastore_clusters my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datastore_clusters function must be called with '
'-f or --function.'
)
return {'Datastore Clusters': salt.utils.vmware.list_datastore_clusters(_get_si())} | python | def list_datastore_clusters(kwargs=None, call=None):
'''
List all the datastore clusters for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastore_clusters my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datastore_clusters function must be called with '
'-f or --function.'
)
return {'Datastore Clusters': salt.utils.vmware.list_datastore_clusters(_get_si())} | [
"def",
"list_datastore_clusters",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_datastore_clusters function must be called with '",
"'-f or --function.'",
")",
"retu... | List all the datastore clusters for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastore_clusters my-vmware-config | [
"List",
"all",
"the",
"datastore",
"clusters",
"for",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1607-L1623 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_datastores | def list_datastores(kwargs=None, call=None):
'''
List all the datastores for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastores my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datastores function must be called with '
'-f or --function.'
)
return {'Datastores': salt.utils.vmware.list_datastores(_get_si())} | python | def list_datastores(kwargs=None, call=None):
'''
List all the datastores for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastores my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datastores function must be called with '
'-f or --function.'
)
return {'Datastores': salt.utils.vmware.list_datastores(_get_si())} | [
"def",
"list_datastores",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_datastores function must be called with '",
"'-f or --function.'",
")",
"return",
"{",
"'... | List all the datastores for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastores my-vmware-config | [
"List",
"all",
"the",
"datastores",
"for",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1626-L1642 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_datastores_full | def list_datastores_full(kwargs=None, call=None):
'''
List all the datastores for this VMware environment, with extra information
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastores_full my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datastores_full function must be called with '
'-f or --function.'
)
return {'Datastores': salt.utils.vmware.list_datastores_full(_get_si())} | python | def list_datastores_full(kwargs=None, call=None):
'''
List all the datastores for this VMware environment, with extra information
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastores_full my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datastores_full function must be called with '
'-f or --function.'
)
return {'Datastores': salt.utils.vmware.list_datastores_full(_get_si())} | [
"def",
"list_datastores_full",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_datastores_full function must be called with '",
"'-f or --function.'",
")",
"return",
... | List all the datastores for this VMware environment, with extra information
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastores_full my-vmware-config | [
"List",
"all",
"the",
"datastores",
"for",
"this",
"VMware",
"environment",
"with",
"extra",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1645-L1661 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_datastore_full | def list_datastore_full(kwargs=None, call=None, datastore=None):
'''
Returns a dictionary with basic information for the given datastore
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastore_full my-vmware-config datastore=datastore-name
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datastore_full function must be called with '
'-f or --function.'
)
if kwargs:
datastore = kwargs.get('datastore', None)
if not datastore:
raise SaltCloudSystemExit(
'The list_datastore_full function requires a datastore'
)
return {datastore: salt.utils.vmware.list_datastore_full(_get_si(), datastore)} | python | def list_datastore_full(kwargs=None, call=None, datastore=None):
'''
Returns a dictionary with basic information for the given datastore
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastore_full my-vmware-config datastore=datastore-name
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datastore_full function must be called with '
'-f or --function.'
)
if kwargs:
datastore = kwargs.get('datastore', None)
if not datastore:
raise SaltCloudSystemExit(
'The list_datastore_full function requires a datastore'
)
return {datastore: salt.utils.vmware.list_datastore_full(_get_si(), datastore)} | [
"def",
"list_datastore_full",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
",",
"datastore",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_datastore_full function must be called with '",
"'-f o... | Returns a dictionary with basic information for the given datastore
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastore_full my-vmware-config datastore=datastore-name | [
"Returns",
"a",
"dictionary",
"with",
"basic",
"information",
"for",
"the",
"given",
"datastore"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1664-L1688 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_hosts | def list_hosts(kwargs=None, call=None):
'''
List all the hosts for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_hosts function must be called with '
'-f or --function.'
)
return {'Hosts': salt.utils.vmware.list_hosts(_get_si())} | python | def list_hosts(kwargs=None, call=None):
'''
List all the hosts for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_hosts function must be called with '
'-f or --function.'
)
return {'Hosts': salt.utils.vmware.list_hosts(_get_si())} | [
"def",
"list_hosts",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_hosts function must be called with '",
"'-f or --function.'",
")",
"return",
"{",
"'Hosts'",
... | List all the hosts for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts my-vmware-config | [
"List",
"all",
"the",
"hosts",
"for",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1691-L1707 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_resourcepools | def list_resourcepools(kwargs=None, call=None):
'''
List all the resource pools for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_resourcepools my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_resourcepools function must be called with '
'-f or --function.'
)
return {'Resource Pools': salt.utils.vmware.list_resourcepools(_get_si())} | python | def list_resourcepools(kwargs=None, call=None):
'''
List all the resource pools for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_resourcepools my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_resourcepools function must be called with '
'-f or --function.'
)
return {'Resource Pools': salt.utils.vmware.list_resourcepools(_get_si())} | [
"def",
"list_resourcepools",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_resourcepools function must be called with '",
"'-f or --function.'",
")",
"return",
"{"... | List all the resource pools for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_resourcepools my-vmware-config | [
"List",
"all",
"the",
"resource",
"pools",
"for",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1710-L1726 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_networks | def list_networks(kwargs=None, call=None):
'''
List all the standard networks for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_networks my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function.'
)
return {'Networks': salt.utils.vmware.list_networks(_get_si())} | python | def list_networks(kwargs=None, call=None):
'''
List all the standard networks for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_networks my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function.'
)
return {'Networks': salt.utils.vmware.list_networks(_get_si())} | [
"def",
"list_networks",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_networks function must be called with '",
"'-f or --function.'",
")",
"return",
"{",
"'Netw... | List all the standard networks for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_networks my-vmware-config | [
"List",
"all",
"the",
"standard",
"networks",
"for",
"this",
"VMware",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1729-L1745 | train |
saltstack/salt | salt/cloud/clouds/vmware.py | list_nodes_min | def list_nodes_min(kwargs=None, call=None):
'''
Return a list of all VMs and templates that are on the specified provider, with no details
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes_min my-vmware-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called '
'with -f or --function.'
)
ret = {}
vm_properties = ["name"]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
ret[vm['name']] = {'state': 'Running', 'id': vm['name']}
return ret | python | def list_nodes_min(kwargs=None, call=None):
'''
Return a list of all VMs and templates that are on the specified provider, with no details
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes_min my-vmware-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called '
'with -f or --function.'
)
ret = {}
vm_properties = ["name"]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
ret[vm['name']] = {'state': 'Running', 'id': vm['name']}
return ret | [
"def",
"list_nodes_min",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_min function must be called '",
"'with -f or --function.'",
")",
"ret",
"=",
"{",
"}... | Return a list of all VMs and templates that are on the specified provider, with no details
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes_min my-vmware-config | [
"Return",
"a",
"list",
"of",
"all",
"VMs",
"and",
"templates",
"that",
"are",
"on",
"the",
"specified",
"provider",
"with",
"no",
"details"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1748-L1772 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.