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/renderers/pass.py | _fetch_secret | def _fetch_secret(pass_path):
'''
Fetch secret from pass based on pass_path. If there is
any error, return back the original pass_path value
'''
cmd = "pass show {0}".format(pass_path.strip())
log.debug('Fetching secret: %s', cmd)
proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
pass_data, pass_error = proc.communicate()
# The version of pass used during development sent output to
# stdout instead of stderr even though its returncode was non zero.
if proc.returncode or not pass_data:
log.warning('Could not fetch secret: %s %s', pass_data, pass_error)
pass_data = pass_path
return pass_data.strip() | python | def _fetch_secret(pass_path):
'''
Fetch secret from pass based on pass_path. If there is
any error, return back the original pass_path value
'''
cmd = "pass show {0}".format(pass_path.strip())
log.debug('Fetching secret: %s', cmd)
proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
pass_data, pass_error = proc.communicate()
# The version of pass used during development sent output to
# stdout instead of stderr even though its returncode was non zero.
if proc.returncode or not pass_data:
log.warning('Could not fetch secret: %s %s', pass_data, pass_error)
pass_data = pass_path
return pass_data.strip() | [
"def",
"_fetch_secret",
"(",
"pass_path",
")",
":",
"cmd",
"=",
"\"pass show {0}\"",
".",
"format",
"(",
"pass_path",
".",
"strip",
"(",
")",
")",
"log",
".",
"debug",
"(",
"'Fetching secret: %s'",
",",
"cmd",
")",
"proc",
"=",
"Popen",
"(",
"cmd",
".",
... | Fetch secret from pass based on pass_path. If there is
any error, return back the original pass_path value | [
"Fetch",
"secret",
"from",
"pass",
"based",
"on",
"pass_path",
".",
"If",
"there",
"is",
"any",
"error",
"return",
"back",
"the",
"original",
"pass_path",
"value"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/pass.py#L79-L95 | train |
saltstack/salt | salt/renderers/pass.py | _decrypt_object | def _decrypt_object(obj):
'''
Recursively try to find a pass path (string) that can be handed off to pass
'''
if isinstance(obj, six.string_types):
return _fetch_secret(obj)
elif isinstance(obj, dict):
for pass_key, pass_path in six.iteritems(obj):
obj[pass_key] = _decrypt_object(pass_path)
elif isinstance(obj, list):
for pass_key, pass_path in enumerate(obj):
obj[pass_key] = _decrypt_object(pass_path)
return obj | python | def _decrypt_object(obj):
'''
Recursively try to find a pass path (string) that can be handed off to pass
'''
if isinstance(obj, six.string_types):
return _fetch_secret(obj)
elif isinstance(obj, dict):
for pass_key, pass_path in six.iteritems(obj):
obj[pass_key] = _decrypt_object(pass_path)
elif isinstance(obj, list):
for pass_key, pass_path in enumerate(obj):
obj[pass_key] = _decrypt_object(pass_path)
return obj | [
"def",
"_decrypt_object",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
":",
"return",
"_fetch_secret",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"for",
"pass_key",
",",
"pas... | Recursively try to find a pass path (string) that can be handed off to pass | [
"Recursively",
"try",
"to",
"find",
"a",
"pass",
"path",
"(",
"string",
")",
"that",
"can",
"be",
"handed",
"off",
"to",
"pass"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/pass.py#L98-L110 | train |
saltstack/salt | salt/renderers/pass.py | render | def render(pass_info, saltenv='base', sls='', argline='', **kwargs):
'''
Fetch secret from pass based on pass_path
'''
try:
_get_pass_exec()
except SaltRenderError:
raise
# Make sure environment variable HOME is set, since Pass looks for the
# password-store under ~/.password-store.
os.environ['HOME'] = expanduser('~')
return _decrypt_object(pass_info) | python | def render(pass_info, saltenv='base', sls='', argline='', **kwargs):
'''
Fetch secret from pass based on pass_path
'''
try:
_get_pass_exec()
except SaltRenderError:
raise
# Make sure environment variable HOME is set, since Pass looks for the
# password-store under ~/.password-store.
os.environ['HOME'] = expanduser('~')
return _decrypt_object(pass_info) | [
"def",
"render",
"(",
"pass_info",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"argline",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"_get_pass_exec",
"(",
")",
"except",
"SaltRenderError",
":",
"raise",
"# Make sure environ... | Fetch secret from pass based on pass_path | [
"Fetch",
"secret",
"from",
"pass",
"based",
"on",
"pass_path"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/pass.py#L113-L125 | train |
saltstack/salt | salt/runners/pkg.py | list_upgrades | def list_upgrades(jid,
style='group',
outputter='nested',
ext_source=None):
'''
Show list of available pkg upgrades using a specified format style
CLI Example:
.. code-block:: bash
salt-run pkg.list_upgrades jid=20141120114114417719 style=group
'''
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
pkgs = {}
if style == 'group':
for minion in data:
results = data[minion]['return']
for pkg, pkgver in six.iteritems(results):
if pkg not in six.iterkeys(pkgs):
pkgs[pkg] = {pkgver: {'hosts': []}}
if pkgver not in six.iterkeys(pkgs[pkg]):
pkgs[pkg].update({pkgver: {'hosts': []}})
pkgs[pkg][pkgver]['hosts'].append(minion)
if outputter:
salt.output.display_output(pkgs, outputter, opts=__opts__)
return pkgs | python | def list_upgrades(jid,
style='group',
outputter='nested',
ext_source=None):
'''
Show list of available pkg upgrades using a specified format style
CLI Example:
.. code-block:: bash
salt-run pkg.list_upgrades jid=20141120114114417719 style=group
'''
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
pkgs = {}
if style == 'group':
for minion in data:
results = data[minion]['return']
for pkg, pkgver in six.iteritems(results):
if pkg not in six.iterkeys(pkgs):
pkgs[pkg] = {pkgver: {'hosts': []}}
if pkgver not in six.iterkeys(pkgs[pkg]):
pkgs[pkg].update({pkgver: {'hosts': []}})
pkgs[pkg][pkgver]['hosts'].append(minion)
if outputter:
salt.output.display_output(pkgs, outputter, opts=__opts__)
return pkgs | [
"def",
"list_upgrades",
"(",
"jid",
",",
"style",
"=",
"'group'",
",",
"outputter",
"=",
"'nested'",
",",
"ext_source",
"=",
"None",
")",
":",
"mminion",
"=",
"salt",
".",
"minion",
".",
"MasterMinion",
"(",
"__opts__",
")",
"returner",
"=",
"_get_returner... | Show list of available pkg upgrades using a specified format style
CLI Example:
.. code-block:: bash
salt-run pkg.list_upgrades jid=20141120114114417719 style=group | [
"Show",
"list",
"of",
"available",
"pkg",
"upgrades",
"using",
"a",
"specified",
"format",
"style"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/pkg.py#L28-L66 | train |
saltstack/salt | salt/modules/firewalld.py | __firewall_cmd | def __firewall_cmd(cmd):
'''
Return the firewall-cmd location
'''
firewall_cmd = '{0} {1}'.format(salt.utils.path.which('firewall-cmd'), cmd)
out = __salt__['cmd.run_all'](firewall_cmd)
if out['retcode'] != 0:
if not out['stderr']:
msg = out['stdout']
else:
msg = out['stderr']
raise CommandExecutionError(
'firewall-cmd failed: {0}'.format(msg)
)
return out['stdout'] | python | def __firewall_cmd(cmd):
'''
Return the firewall-cmd location
'''
firewall_cmd = '{0} {1}'.format(salt.utils.path.which('firewall-cmd'), cmd)
out = __salt__['cmd.run_all'](firewall_cmd)
if out['retcode'] != 0:
if not out['stderr']:
msg = out['stdout']
else:
msg = out['stderr']
raise CommandExecutionError(
'firewall-cmd failed: {0}'.format(msg)
)
return out['stdout'] | [
"def",
"__firewall_cmd",
"(",
"cmd",
")",
":",
"firewall_cmd",
"=",
"'{0} {1}'",
".",
"format",
"(",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'firewall-cmd'",
")",
",",
"cmd",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"... | Return the firewall-cmd location | [
"Return",
"the",
"firewall",
"-",
"cmd",
"location"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L30-L45 | train |
saltstack/salt | salt/modules/firewalld.py | __mgmt | def __mgmt(name, _type, action):
'''
Perform zone management
'''
# It's permanent because the 4 concerned functions need the permanent option, it's wrong without
cmd = '--{0}-{1}={2} --permanent'.format(action, _type, name)
return __firewall_cmd(cmd) | python | def __mgmt(name, _type, action):
'''
Perform zone management
'''
# It's permanent because the 4 concerned functions need the permanent option, it's wrong without
cmd = '--{0}-{1}={2} --permanent'.format(action, _type, name)
return __firewall_cmd(cmd) | [
"def",
"__mgmt",
"(",
"name",
",",
"_type",
",",
"action",
")",
":",
"# It's permanent because the 4 concerned functions need the permanent option, it's wrong without",
"cmd",
"=",
"'--{0}-{1}={2} --permanent'",
".",
"format",
"(",
"action",
",",
"_type",
",",
"name",
")"... | Perform zone management | [
"Perform",
"zone",
"management"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L48-L55 | train |
saltstack/salt | salt/modules/firewalld.py | list_zones | def list_zones(permanent=True):
'''
List everything added for or enabled in all zones
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_zones
'''
zones = {}
cmd = '--list-all-zones'
if permanent:
cmd += ' --permanent'
for i in __firewall_cmd(cmd).splitlines():
if i.strip():
if bool(re.match('^[a-z0-9]', i, re.I)):
zone_name = i.rstrip()
else:
(id_, val) = i.strip().split(':')
if zones.get(zone_name, None):
zones[zone_name].update({id_: val})
else:
zones[zone_name] = {id_: val}
return zones | python | def list_zones(permanent=True):
'''
List everything added for or enabled in all zones
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_zones
'''
zones = {}
cmd = '--list-all-zones'
if permanent:
cmd += ' --permanent'
for i in __firewall_cmd(cmd).splitlines():
if i.strip():
if bool(re.match('^[a-z0-9]', i, re.I)):
zone_name = i.rstrip()
else:
(id_, val) = i.strip().split(':')
if zones.get(zone_name, None):
zones[zone_name].update({id_: val})
else:
zones[zone_name] = {id_: val}
return zones | [
"def",
"list_zones",
"(",
"permanent",
"=",
"True",
")",
":",
"zones",
"=",
"{",
"}",
"cmd",
"=",
"'--list-all-zones'",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"for",
"i",
"in",
"__firewall_cmd",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")... | List everything added for or enabled in all zones
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_zones | [
"List",
"everything",
"added",
"for",
"or",
"enabled",
"in",
"all",
"zones"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L100-L129 | train |
saltstack/salt | salt/modules/firewalld.py | new_zone | def new_zone(zone, restart=True):
'''
Add a new zone
CLI Example:
.. code-block:: bash
salt '*' firewalld.new_zone my_zone
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.new_zone my_zone False
'''
out = __mgmt(zone, 'zone', 'new')
if restart:
if out == 'success':
return __firewall_cmd('--reload')
return out | python | def new_zone(zone, restart=True):
'''
Add a new zone
CLI Example:
.. code-block:: bash
salt '*' firewalld.new_zone my_zone
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.new_zone my_zone False
'''
out = __mgmt(zone, 'zone', 'new')
if restart:
if out == 'success':
return __firewall_cmd('--reload')
return out | [
"def",
"new_zone",
"(",
"zone",
",",
"restart",
"=",
"True",
")",
":",
"out",
"=",
"__mgmt",
"(",
"zone",
",",
"'zone'",
",",
"'new'",
")",
"if",
"restart",
":",
"if",
"out",
"==",
"'success'",
":",
"return",
"__firewall_cmd",
"(",
"'--reload'",
")",
... | Add a new zone
CLI Example:
.. code-block:: bash
salt '*' firewalld.new_zone my_zone
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.new_zone my_zone False | [
"Add",
"a",
"new",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L186-L210 | train |
saltstack/salt | salt/modules/firewalld.py | delete_zone | def delete_zone(zone, restart=True):
'''
Delete an existing zone
CLI Example:
.. code-block:: bash
salt '*' firewalld.delete_zone my_zone
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.delete_zone my_zone False
'''
out = __mgmt(zone, 'zone', 'delete')
if restart:
if out == 'success':
return __firewall_cmd('--reload')
return out | python | def delete_zone(zone, restart=True):
'''
Delete an existing zone
CLI Example:
.. code-block:: bash
salt '*' firewalld.delete_zone my_zone
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.delete_zone my_zone False
'''
out = __mgmt(zone, 'zone', 'delete')
if restart:
if out == 'success':
return __firewall_cmd('--reload')
return out | [
"def",
"delete_zone",
"(",
"zone",
",",
"restart",
"=",
"True",
")",
":",
"out",
"=",
"__mgmt",
"(",
"zone",
",",
"'zone'",
",",
"'delete'",
")",
"if",
"restart",
":",
"if",
"out",
"==",
"'success'",
":",
"return",
"__firewall_cmd",
"(",
"'--reload'",
... | Delete an existing zone
CLI Example:
.. code-block:: bash
salt '*' firewalld.delete_zone my_zone
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.delete_zone my_zone False | [
"Delete",
"an",
"existing",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L213-L237 | train |
saltstack/salt | salt/modules/firewalld.py | new_service | def new_service(name, restart=True):
'''
Add a new service
CLI Example:
.. code-block:: bash
salt '*' firewalld.new_service my_service
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.new_service my_service False
'''
out = __mgmt(name, 'service', 'new')
if restart:
if out == 'success':
return __firewall_cmd('--reload')
return out | python | def new_service(name, restart=True):
'''
Add a new service
CLI Example:
.. code-block:: bash
salt '*' firewalld.new_service my_service
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.new_service my_service False
'''
out = __mgmt(name, 'service', 'new')
if restart:
if out == 'success':
return __firewall_cmd('--reload')
return out | [
"def",
"new_service",
"(",
"name",
",",
"restart",
"=",
"True",
")",
":",
"out",
"=",
"__mgmt",
"(",
"name",
",",
"'service'",
",",
"'new'",
")",
"if",
"restart",
":",
"if",
"out",
"==",
"'success'",
":",
"return",
"__firewall_cmd",
"(",
"'--reload'",
... | Add a new service
CLI Example:
.. code-block:: bash
salt '*' firewalld.new_service my_service
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.new_service my_service False | [
"Add",
"a",
"new",
"service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L253-L277 | train |
saltstack/salt | salt/modules/firewalld.py | delete_service | def delete_service(name, restart=True):
'''
Delete an existing service
CLI Example:
.. code-block:: bash
salt '*' firewalld.delete_service my_service
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.delete_service my_service False
'''
out = __mgmt(name, 'service', 'delete')
if restart:
if out == 'success':
return __firewall_cmd('--reload')
return out | python | def delete_service(name, restart=True):
'''
Delete an existing service
CLI Example:
.. code-block:: bash
salt '*' firewalld.delete_service my_service
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.delete_service my_service False
'''
out = __mgmt(name, 'service', 'delete')
if restart:
if out == 'success':
return __firewall_cmd('--reload')
return out | [
"def",
"delete_service",
"(",
"name",
",",
"restart",
"=",
"True",
")",
":",
"out",
"=",
"__mgmt",
"(",
"name",
",",
"'service'",
",",
"'delete'",
")",
"if",
"restart",
":",
"if",
"out",
"==",
"'success'",
":",
"return",
"__firewall_cmd",
"(",
"'--reload... | Delete an existing service
CLI Example:
.. code-block:: bash
salt '*' firewalld.delete_service my_service
By default firewalld will be reloaded. However, to avoid reloading
you need to specify the restart as False
.. code-block:: bash
salt '*' firewalld.delete_service my_service False | [
"Delete",
"an",
"existing",
"service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L280-L304 | train |
saltstack/salt | salt/modules/firewalld.py | list_all | def list_all(zone=None, permanent=True):
'''
List everything added for or enabled in a zone
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_all
List a specific zone
.. code-block:: bash
salt '*' firewalld.list_all my_zone
'''
_zone = {}
id_ = ''
if zone:
cmd = '--zone={0} --list-all'.format(zone)
else:
cmd = '--list-all'
if permanent:
cmd += ' --permanent'
for i in __firewall_cmd(cmd).splitlines():
if re.match('^[a-z0-9]', i, re.I):
zone_name = i.rstrip()
else:
if i.startswith('\t'):
_zone[zone_name][id_].append(i.strip())
continue
(id_, val) = i.split(':', 1)
id_ = id_.strip()
if _zone.get(zone_name, None):
_zone[zone_name].update({id_: [val.strip()]})
else:
_zone[zone_name] = {id_: [val.strip()]}
return _zone | python | def list_all(zone=None, permanent=True):
'''
List everything added for or enabled in a zone
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_all
List a specific zone
.. code-block:: bash
salt '*' firewalld.list_all my_zone
'''
_zone = {}
id_ = ''
if zone:
cmd = '--zone={0} --list-all'.format(zone)
else:
cmd = '--list-all'
if permanent:
cmd += ' --permanent'
for i in __firewall_cmd(cmd).splitlines():
if re.match('^[a-z0-9]', i, re.I):
zone_name = i.rstrip()
else:
if i.startswith('\t'):
_zone[zone_name][id_].append(i.strip())
continue
(id_, val) = i.split(':', 1)
id_ = id_.strip()
if _zone.get(zone_name, None):
_zone[zone_name].update({id_: [val.strip()]})
else:
_zone[zone_name] = {id_: [val.strip()]}
return _zone | [
"def",
"list_all",
"(",
"zone",
"=",
"None",
",",
"permanent",
"=",
"True",
")",
":",
"_zone",
"=",
"{",
"}",
"id_",
"=",
"''",
"if",
"zone",
":",
"cmd",
"=",
"'--zone={0} --list-all'",
".",
"format",
"(",
"zone",
")",
"else",
":",
"cmd",
"=",
"'--... | List everything added for or enabled in a zone
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_all
List a specific zone
.. code-block:: bash
salt '*' firewalld.list_all my_zone | [
"List",
"everything",
"added",
"for",
"or",
"enabled",
"in",
"a",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L307-L351 | train |
saltstack/salt | salt/modules/firewalld.py | list_services | def list_services(zone=None, permanent=True):
'''
List services added for zone as a space separated list.
If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_services
List a specific zone
.. code-block:: bash
salt '*' firewalld.list_services my_zone
'''
if zone:
cmd = '--zone={0} --list-services'.format(zone)
else:
cmd = '--list-services'
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).split() | python | def list_services(zone=None, permanent=True):
'''
List services added for zone as a space separated list.
If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_services
List a specific zone
.. code-block:: bash
salt '*' firewalld.list_services my_zone
'''
if zone:
cmd = '--zone={0} --list-services'.format(zone)
else:
cmd = '--list-services'
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).split() | [
"def",
"list_services",
"(",
"zone",
"=",
"None",
",",
"permanent",
"=",
"True",
")",
":",
"if",
"zone",
":",
"cmd",
"=",
"'--zone={0} --list-services'",
".",
"format",
"(",
"zone",
")",
"else",
":",
"cmd",
"=",
"'--list-services'",
"if",
"permanent",
":",... | List services added for zone as a space separated list.
If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_services
List a specific zone
.. code-block:: bash
salt '*' firewalld.list_services my_zone | [
"List",
"services",
"added",
"for",
"zone",
"as",
"a",
"space",
"separated",
"list",
".",
"If",
"zone",
"is",
"omitted",
"default",
"zone",
"will",
"be",
"used",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L354-L379 | train |
saltstack/salt | salt/modules/firewalld.py | add_service | def add_service(service, zone=None, permanent=True):
'''
Add a service for zone. If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_service ssh
To assign a service to a specific zone:
.. code-block:: bash
salt '*' firewalld.add_service ssh my_zone
'''
if zone:
cmd = '--zone={0} --add-service={1}'.format(zone, service)
else:
cmd = '--add-service={0}'.format(service)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def add_service(service, zone=None, permanent=True):
'''
Add a service for zone. If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_service ssh
To assign a service to a specific zone:
.. code-block:: bash
salt '*' firewalld.add_service ssh my_zone
'''
if zone:
cmd = '--zone={0} --add-service={1}'.format(zone, service)
else:
cmd = '--add-service={0}'.format(service)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"add_service",
"(",
"service",
",",
"zone",
"=",
"None",
",",
"permanent",
"=",
"True",
")",
":",
"if",
"zone",
":",
"cmd",
"=",
"'--zone={0} --add-service={1}'",
".",
"format",
"(",
"zone",
",",
"service",
")",
"else",
":",
"cmd",
"=",
"'--add-se... | Add a service for zone. If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_service ssh
To assign a service to a specific zone:
.. code-block:: bash
salt '*' firewalld.add_service ssh my_zone | [
"Add",
"a",
"service",
"for",
"zone",
".",
"If",
"zone",
"is",
"omitted",
"default",
"zone",
"will",
"be",
"used",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L382-L406 | train |
saltstack/salt | salt/modules/firewalld.py | remove_service | def remove_service(service, zone=None, permanent=True):
'''
Remove a service from zone. This option can be specified multiple times.
If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_service ssh
To remove a service from a specific zone
.. code-block:: bash
salt '*' firewalld.remove_service ssh dmz
'''
if zone:
cmd = '--zone={0} --remove-service={1}'.format(zone, service)
else:
cmd = '--remove-service={0}'.format(service)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def remove_service(service, zone=None, permanent=True):
'''
Remove a service from zone. This option can be specified multiple times.
If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_service ssh
To remove a service from a specific zone
.. code-block:: bash
salt '*' firewalld.remove_service ssh dmz
'''
if zone:
cmd = '--zone={0} --remove-service={1}'.format(zone, service)
else:
cmd = '--remove-service={0}'.format(service)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"remove_service",
"(",
"service",
",",
"zone",
"=",
"None",
",",
"permanent",
"=",
"True",
")",
":",
"if",
"zone",
":",
"cmd",
"=",
"'--zone={0} --remove-service={1}'",
".",
"format",
"(",
"zone",
",",
"service",
")",
"else",
":",
"cmd",
"=",
"'--... | Remove a service from zone. This option can be specified multiple times.
If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_service ssh
To remove a service from a specific zone
.. code-block:: bash
salt '*' firewalld.remove_service ssh dmz | [
"Remove",
"a",
"service",
"from",
"zone",
".",
"This",
"option",
"can",
"be",
"specified",
"multiple",
"times",
".",
"If",
"zone",
"is",
"omitted",
"default",
"zone",
"will",
"be",
"used",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L409-L434 | train |
saltstack/salt | salt/modules/firewalld.py | add_service_port | def add_service_port(service, port):
'''
Add a new port to the specified service.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_service_port zone 80
'''
if service not in get_services(permanent=True):
raise CommandExecutionError('The service does not exist.')
cmd = '--permanent --service={0} --add-port={1}'.format(service, port)
return __firewall_cmd(cmd) | python | def add_service_port(service, port):
'''
Add a new port to the specified service.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_service_port zone 80
'''
if service not in get_services(permanent=True):
raise CommandExecutionError('The service does not exist.')
cmd = '--permanent --service={0} --add-port={1}'.format(service, port)
return __firewall_cmd(cmd) | [
"def",
"add_service_port",
"(",
"service",
",",
"port",
")",
":",
"if",
"service",
"not",
"in",
"get_services",
"(",
"permanent",
"=",
"True",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'The service does not exist.'",
")",
"cmd",
"=",
"'--permanent --servic... | Add a new port to the specified service.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_service_port zone 80 | [
"Add",
"a",
"new",
"port",
"to",
"the",
"specified",
"service",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L437-L453 | train |
saltstack/salt | salt/modules/firewalld.py | get_masquerade | def get_masquerade(zone=None, permanent=True):
'''
Show if masquerading is enabled on a zone.
If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_masquerade zone
'''
zone_info = list_all(zone, permanent)
if 'no' in [zone_info[i]['masquerade'][0] for i in zone_info]:
return False
return True | python | def get_masquerade(zone=None, permanent=True):
'''
Show if masquerading is enabled on a zone.
If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_masquerade zone
'''
zone_info = list_all(zone, permanent)
if 'no' in [zone_info[i]['masquerade'][0] for i in zone_info]:
return False
return True | [
"def",
"get_masquerade",
"(",
"zone",
"=",
"None",
",",
"permanent",
"=",
"True",
")",
":",
"zone_info",
"=",
"list_all",
"(",
"zone",
",",
"permanent",
")",
"if",
"'no'",
"in",
"[",
"zone_info",
"[",
"i",
"]",
"[",
"'masquerade'",
"]",
"[",
"0",
"]"... | Show if masquerading is enabled on a zone.
If zone is omitted, default zone will be used.
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_masquerade zone | [
"Show",
"if",
"masquerading",
"is",
"enabled",
"on",
"a",
"zone",
".",
"If",
"zone",
"is",
"omitted",
"default",
"zone",
"will",
"be",
"used",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L541-L557 | train |
saltstack/salt | salt/modules/firewalld.py | add_masquerade | def add_masquerade(zone=None, permanent=True):
'''
Enable masquerade on a zone.
If zone is omitted, default zone will be used.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_masquerade
To enable masquerade on a specific zone
.. code-block:: bash
salt '*' firewalld.add_masquerade dmz
'''
if zone:
cmd = '--zone={0} --add-masquerade'.format(zone)
else:
cmd = '--add-masquerade'
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def add_masquerade(zone=None, permanent=True):
'''
Enable masquerade on a zone.
If zone is omitted, default zone will be used.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_masquerade
To enable masquerade on a specific zone
.. code-block:: bash
salt '*' firewalld.add_masquerade dmz
'''
if zone:
cmd = '--zone={0} --add-masquerade'.format(zone)
else:
cmd = '--add-masquerade'
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"add_masquerade",
"(",
"zone",
"=",
"None",
",",
"permanent",
"=",
"True",
")",
":",
"if",
"zone",
":",
"cmd",
"=",
"'--zone={0} --add-masquerade'",
".",
"format",
"(",
"zone",
")",
"else",
":",
"cmd",
"=",
"'--add-masquerade'",
"if",
"permanent",
"... | Enable masquerade on a zone.
If zone is omitted, default zone will be used.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_masquerade
To enable masquerade on a specific zone
.. code-block:: bash
salt '*' firewalld.add_masquerade dmz | [
"Enable",
"masquerade",
"on",
"a",
"zone",
".",
"If",
"zone",
"is",
"omitted",
"default",
"zone",
"will",
"be",
"used",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L560-L587 | train |
saltstack/salt | salt/modules/firewalld.py | remove_masquerade | def remove_masquerade(zone=None, permanent=True):
'''
Remove masquerade on a zone.
If zone is omitted, default zone will be used.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_masquerade
To remove masquerade on a specific zone
.. code-block:: bash
salt '*' firewalld.remove_masquerade dmz
'''
if zone:
cmd = '--zone={0} --remove-masquerade'.format(zone)
else:
cmd = '--remove-masquerade'
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def remove_masquerade(zone=None, permanent=True):
'''
Remove masquerade on a zone.
If zone is omitted, default zone will be used.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_masquerade
To remove masquerade on a specific zone
.. code-block:: bash
salt '*' firewalld.remove_masquerade dmz
'''
if zone:
cmd = '--zone={0} --remove-masquerade'.format(zone)
else:
cmd = '--remove-masquerade'
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"remove_masquerade",
"(",
"zone",
"=",
"None",
",",
"permanent",
"=",
"True",
")",
":",
"if",
"zone",
":",
"cmd",
"=",
"'--zone={0} --remove-masquerade'",
".",
"format",
"(",
"zone",
")",
"else",
":",
"cmd",
"=",
"'--remove-masquerade'",
"if",
"perman... | Remove masquerade on a zone.
If zone is omitted, default zone will be used.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_masquerade
To remove masquerade on a specific zone
.. code-block:: bash
salt '*' firewalld.remove_masquerade dmz | [
"Remove",
"masquerade",
"on",
"a",
"zone",
".",
"If",
"zone",
"is",
"omitted",
"default",
"zone",
"will",
"be",
"used",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L590-L617 | train |
saltstack/salt | salt/modules/firewalld.py | add_port | def add_port(zone, port, permanent=True):
'''
Allow specific ports in a zone.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_port internal 443/tcp
'''
cmd = '--zone={0} --add-port={1}'.format(zone, port)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def add_port(zone, port, permanent=True):
'''
Allow specific ports in a zone.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_port internal 443/tcp
'''
cmd = '--zone={0} --add-port={1}'.format(zone, port)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"add_port",
"(",
"zone",
",",
"port",
",",
"permanent",
"=",
"True",
")",
":",
"cmd",
"=",
"'--zone={0} --add-port={1}'",
".",
"format",
"(",
"zone",
",",
"port",
")",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"return",
"__firewall_cmd",
... | Allow specific ports in a zone.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_port internal 443/tcp | [
"Allow",
"specific",
"ports",
"in",
"a",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L620-L637 | train |
saltstack/salt | salt/modules/firewalld.py | remove_port | def remove_port(zone, port, permanent=True):
'''
Remove a specific port from a zone.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_port internal 443/tcp
'''
cmd = '--zone={0} --remove-port={1}'.format(zone, port)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def remove_port(zone, port, permanent=True):
'''
Remove a specific port from a zone.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_port internal 443/tcp
'''
cmd = '--zone={0} --remove-port={1}'.format(zone, port)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"remove_port",
"(",
"zone",
",",
"port",
",",
"permanent",
"=",
"True",
")",
":",
"cmd",
"=",
"'--zone={0} --remove-port={1}'",
".",
"format",
"(",
"zone",
",",
"port",
")",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"return",
"__firewall_... | Remove a specific port from a zone.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_port internal 443/tcp | [
"Remove",
"a",
"specific",
"port",
"from",
"a",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L640-L657 | train |
saltstack/salt | salt/modules/firewalld.py | list_ports | def list_ports(zone, permanent=True):
'''
List all ports in a zone.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_ports
'''
cmd = '--zone={0} --list-ports'.format(zone)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).split() | python | def list_ports(zone, permanent=True):
'''
List all ports in a zone.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_ports
'''
cmd = '--zone={0} --list-ports'.format(zone)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).split() | [
"def",
"list_ports",
"(",
"zone",
",",
"permanent",
"=",
"True",
")",
":",
"cmd",
"=",
"'--zone={0} --list-ports'",
".",
"format",
"(",
"zone",
")",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"return",
"__firewall_cmd",
"(",
"cmd",
")",
".",
"s... | List all ports in a zone.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_ports | [
"List",
"all",
"ports",
"in",
"a",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L660-L677 | train |
saltstack/salt | salt/modules/firewalld.py | add_port_fwd | def add_port_fwd(zone, src, dest, proto='tcp', dstaddr='', permanent=True):
'''
Add port forwarding.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_port_fwd public 80 443 tcp
'''
cmd = '--zone={0} --add-forward-port=port={1}:proto={2}:toport={3}:toaddr={4}'.format(
zone,
src,
proto,
dest,
dstaddr
)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def add_port_fwd(zone, src, dest, proto='tcp', dstaddr='', permanent=True):
'''
Add port forwarding.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_port_fwd public 80 443 tcp
'''
cmd = '--zone={0} --add-forward-port=port={1}:proto={2}:toport={3}:toaddr={4}'.format(
zone,
src,
proto,
dest,
dstaddr
)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"add_port_fwd",
"(",
"zone",
",",
"src",
",",
"dest",
",",
"proto",
"=",
"'tcp'",
",",
"dstaddr",
"=",
"''",
",",
"permanent",
"=",
"True",
")",
":",
"cmd",
"=",
"'--zone={0} --add-forward-port=port={1}:proto={2}:toport={3}:toaddr={4}'",
".",
"format",
"(... | Add port forwarding.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_port_fwd public 80 443 tcp | [
"Add",
"port",
"forwarding",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L680-L703 | train |
saltstack/salt | salt/modules/firewalld.py | list_port_fwd | def list_port_fwd(zone, permanent=True):
'''
List port forwarding
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_port_fwd public
'''
ret = []
cmd = '--zone={0} --list-forward-ports'.format(zone)
if permanent:
cmd += ' --permanent'
for i in __firewall_cmd(cmd).splitlines():
(src, proto, dest, addr) = i.split(':')
ret.append(
{'Source port': src.split('=')[1],
'Protocol': proto.split('=')[1],
'Destination port': dest.split('=')[1],
'Destination address': addr.split('=')[1]}
)
return ret | python | def list_port_fwd(zone, permanent=True):
'''
List port forwarding
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_port_fwd public
'''
ret = []
cmd = '--zone={0} --list-forward-ports'.format(zone)
if permanent:
cmd += ' --permanent'
for i in __firewall_cmd(cmd).splitlines():
(src, proto, dest, addr) = i.split(':')
ret.append(
{'Source port': src.split('=')[1],
'Protocol': proto.split('=')[1],
'Destination port': dest.split('=')[1],
'Destination address': addr.split('=')[1]}
)
return ret | [
"def",
"list_port_fwd",
"(",
"zone",
",",
"permanent",
"=",
"True",
")",
":",
"ret",
"=",
"[",
"]",
"cmd",
"=",
"'--zone={0} --list-forward-ports'",
".",
"format",
"(",
"zone",
")",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"for",
"i",
"in",
... | List port forwarding
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_port_fwd public | [
"List",
"port",
"forwarding"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L732-L761 | train |
saltstack/salt | salt/modules/firewalld.py | block_icmp | def block_icmp(zone, icmp, permanent=True):
'''
Block a specific ICMP type on a zone
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.block_icmp zone echo-reply
'''
if icmp not in get_icmp_types(permanent):
log.error('Invalid ICMP type')
return False
if icmp in list_icmp_block(zone, permanent):
log.info('ICMP block already exists')
return 'success'
cmd = '--zone={0} --add-icmp-block={1}'.format(zone, icmp)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def block_icmp(zone, icmp, permanent=True):
'''
Block a specific ICMP type on a zone
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.block_icmp zone echo-reply
'''
if icmp not in get_icmp_types(permanent):
log.error('Invalid ICMP type')
return False
if icmp in list_icmp_block(zone, permanent):
log.info('ICMP block already exists')
return 'success'
cmd = '--zone={0} --add-icmp-block={1}'.format(zone, icmp)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"block_icmp",
"(",
"zone",
",",
"icmp",
",",
"permanent",
"=",
"True",
")",
":",
"if",
"icmp",
"not",
"in",
"get_icmp_types",
"(",
"permanent",
")",
":",
"log",
".",
"error",
"(",
"'Invalid ICMP type'",
")",
"return",
"False",
"if",
"icmp",
"in",
... | Block a specific ICMP type on a zone
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.block_icmp zone echo-reply | [
"Block",
"a",
"specific",
"ICMP",
"type",
"on",
"a",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L764-L789 | train |
saltstack/salt | salt/modules/firewalld.py | list_icmp_block | def list_icmp_block(zone, permanent=True):
'''
List ICMP blocks on a zone
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewlld.list_icmp_block zone
'''
cmd = '--zone={0} --list-icmp-blocks'.format(zone)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).split() | python | def list_icmp_block(zone, permanent=True):
'''
List ICMP blocks on a zone
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewlld.list_icmp_block zone
'''
cmd = '--zone={0} --list-icmp-blocks'.format(zone)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).split() | [
"def",
"list_icmp_block",
"(",
"zone",
",",
"permanent",
"=",
"True",
")",
":",
"cmd",
"=",
"'--zone={0} --list-icmp-blocks'",
".",
"format",
"(",
"zone",
")",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"return",
"__firewall_cmd",
"(",
"cmd",
")",
... | List ICMP blocks on a zone
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' firewlld.list_icmp_block zone | [
"List",
"ICMP",
"blocks",
"on",
"a",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L820-L837 | train |
saltstack/salt | salt/modules/firewalld.py | get_interfaces | def get_interfaces(zone, permanent=True):
'''
List interfaces bound to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_interfaces zone
'''
cmd = '--zone={0} --list-interfaces'.format(zone)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).split() | python | def get_interfaces(zone, permanent=True):
'''
List interfaces bound to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_interfaces zone
'''
cmd = '--zone={0} --list-interfaces'.format(zone)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).split() | [
"def",
"get_interfaces",
"(",
"zone",
",",
"permanent",
"=",
"True",
")",
":",
"cmd",
"=",
"'--zone={0} --list-interfaces'",
".",
"format",
"(",
"zone",
")",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"return",
"__firewall_cmd",
"(",
"cmd",
")",
... | List interfaces bound to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_interfaces zone | [
"List",
"interfaces",
"bound",
"to",
"a",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L855-L872 | train |
saltstack/salt | salt/modules/firewalld.py | add_interface | def add_interface(zone, interface, permanent=True):
'''
Bind an interface to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_interface zone eth0
'''
if interface in get_interfaces(zone, permanent):
log.info('Interface is already bound to zone.')
cmd = '--zone={0} --add-interface={1}'.format(zone, interface)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def add_interface(zone, interface, permanent=True):
'''
Bind an interface to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_interface zone eth0
'''
if interface in get_interfaces(zone, permanent):
log.info('Interface is already bound to zone.')
cmd = '--zone={0} --add-interface={1}'.format(zone, interface)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"add_interface",
"(",
"zone",
",",
"interface",
",",
"permanent",
"=",
"True",
")",
":",
"if",
"interface",
"in",
"get_interfaces",
"(",
"zone",
",",
"permanent",
")",
":",
"log",
".",
"info",
"(",
"'Interface is already bound to zone.'",
")",
"cmd",
... | Bind an interface to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_interface zone eth0 | [
"Bind",
"an",
"interface",
"to",
"a",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L875-L895 | train |
saltstack/salt | salt/modules/firewalld.py | get_sources | def get_sources(zone, permanent=True):
'''
List sources bound to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_sources zone
'''
cmd = '--zone={0} --list-sources'.format(zone)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).split() | python | def get_sources(zone, permanent=True):
'''
List sources bound to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_sources zone
'''
cmd = '--zone={0} --list-sources'.format(zone)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).split() | [
"def",
"get_sources",
"(",
"zone",
",",
"permanent",
"=",
"True",
")",
":",
"cmd",
"=",
"'--zone={0} --list-sources'",
".",
"format",
"(",
"zone",
")",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"return",
"__firewall_cmd",
"(",
"cmd",
")",
".",
... | List sources bound to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_sources zone | [
"List",
"sources",
"bound",
"to",
"a",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L921-L938 | train |
saltstack/salt | salt/modules/firewalld.py | add_source | def add_source(zone, source, permanent=True):
'''
Bind a source to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_source zone 192.168.1.0/24
'''
if source in get_sources(zone, permanent):
log.info('Source is already bound to zone.')
cmd = '--zone={0} --add-source={1}'.format(zone, source)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def add_source(zone, source, permanent=True):
'''
Bind a source to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_source zone 192.168.1.0/24
'''
if source in get_sources(zone, permanent):
log.info('Source is already bound to zone.')
cmd = '--zone={0} --add-source={1}'.format(zone, source)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"add_source",
"(",
"zone",
",",
"source",
",",
"permanent",
"=",
"True",
")",
":",
"if",
"source",
"in",
"get_sources",
"(",
"zone",
",",
"permanent",
")",
":",
"log",
".",
"info",
"(",
"'Source is already bound to zone.'",
")",
"cmd",
"=",
"'--zone... | Bind a source to a zone
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_source zone 192.168.1.0/24 | [
"Bind",
"a",
"source",
"to",
"a",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L941-L961 | train |
saltstack/salt | salt/modules/firewalld.py | get_rich_rules | def get_rich_rules(zone, permanent=True):
'''
List rich rules bound to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_rich_rules zone
'''
cmd = '--zone={0} --list-rich-rules'.format(zone)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).splitlines() | python | def get_rich_rules(zone, permanent=True):
'''
List rich rules bound to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_rich_rules zone
'''
cmd = '--zone={0} --list-rich-rules'.format(zone)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd).splitlines() | [
"def",
"get_rich_rules",
"(",
"zone",
",",
"permanent",
"=",
"True",
")",
":",
"cmd",
"=",
"'--zone={0} --list-rich-rules'",
".",
"format",
"(",
"zone",
")",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"return",
"__firewall_cmd",
"(",
"cmd",
")",
... | List rich rules bound to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.get_rich_rules zone | [
"List",
"rich",
"rules",
"bound",
"to",
"a",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L987-L1004 | train |
saltstack/salt | salt/modules/firewalld.py | add_rich_rule | def add_rich_rule(zone, rule, permanent=True):
'''
Add a rich rule to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_rich_rule zone 'rule'
'''
cmd = "--zone={0} --add-rich-rule='{1}'".format(zone, rule)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def add_rich_rule(zone, rule, permanent=True):
'''
Add a rich rule to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_rich_rule zone 'rule'
'''
cmd = "--zone={0} --add-rich-rule='{1}'".format(zone, rule)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"add_rich_rule",
"(",
"zone",
",",
"rule",
",",
"permanent",
"=",
"True",
")",
":",
"cmd",
"=",
"\"--zone={0} --add-rich-rule='{1}'\"",
".",
"format",
"(",
"zone",
",",
"rule",
")",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"return",
"__f... | Add a rich rule to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.add_rich_rule zone 'rule' | [
"Add",
"a",
"rich",
"rule",
"to",
"a",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L1007-L1024 | train |
saltstack/salt | salt/modules/firewalld.py | remove_rich_rule | def remove_rich_rule(zone, rule, permanent=True):
'''
Add a rich rule to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_rich_rule zone 'rule'
'''
cmd = "--zone={0} --remove-rich-rule='{1}'".format(zone, rule)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | python | def remove_rich_rule(zone, rule, permanent=True):
'''
Add a rich rule to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_rich_rule zone 'rule'
'''
cmd = "--zone={0} --remove-rich-rule='{1}'".format(zone, rule)
if permanent:
cmd += ' --permanent'
return __firewall_cmd(cmd) | [
"def",
"remove_rich_rule",
"(",
"zone",
",",
"rule",
",",
"permanent",
"=",
"True",
")",
":",
"cmd",
"=",
"\"--zone={0} --remove-rich-rule='{1}'\"",
".",
"format",
"(",
"zone",
",",
"rule",
")",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"return",
... | Add a rich rule to a zone
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' firewalld.remove_rich_rule zone 'rule' | [
"Add",
"a",
"rich",
"rule",
"to",
"a",
"zone"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/firewalld.py#L1027-L1044 | train |
saltstack/salt | salt/grains/mdadm.py | mdadm | def mdadm():
'''
Return list of mdadm devices
'''
devices = set()
try:
with salt.utils.files.fopen('/proc/mdstat', 'r') as mdstat:
for line in mdstat:
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('Personalities : '):
continue
if line.startswith('unused devices:'):
continue
if ' : ' in line:
devices.add(line.split(' : ')[0])
except IOError:
return {}
devices = sorted(devices)
if devices:
log.trace('mdadm devices detected: %s', ', '.join(devices))
return {'mdadm': devices} | python | def mdadm():
'''
Return list of mdadm devices
'''
devices = set()
try:
with salt.utils.files.fopen('/proc/mdstat', 'r') as mdstat:
for line in mdstat:
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('Personalities : '):
continue
if line.startswith('unused devices:'):
continue
if ' : ' in line:
devices.add(line.split(' : ')[0])
except IOError:
return {}
devices = sorted(devices)
if devices:
log.trace('mdadm devices detected: %s', ', '.join(devices))
return {'mdadm': devices} | [
"def",
"mdadm",
"(",
")",
":",
"devices",
"=",
"set",
"(",
")",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/proc/mdstat'",
",",
"'r'",
")",
"as",
"mdstat",
":",
"for",
"line",
"in",
"mdstat",
":",
"line",
"=",
"s... | Return list of mdadm devices | [
"Return",
"list",
"of",
"mdadm",
"devices"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/mdadm.py#L16-L38 | train |
saltstack/salt | salt/modules/vsphere.py | _get_proxy_connection_details | def _get_proxy_connection_details():
'''
Returns the connection details of the following proxies: esxi
'''
proxytype = get_proxy_type()
if proxytype == 'esxi':
details = __salt__['esxi.get_details']()
elif proxytype == 'esxcluster':
details = __salt__['esxcluster.get_details']()
elif proxytype == 'esxdatacenter':
details = __salt__['esxdatacenter.get_details']()
elif proxytype == 'vcenter':
details = __salt__['vcenter.get_details']()
elif proxytype == 'esxvm':
details = __salt__['esxvm.get_details']()
else:
raise CommandExecutionError('\'{0}\' proxy is not supported'
''.format(proxytype))
return \
details.get('vcenter') if 'vcenter' in details \
else details.get('host'), \
details.get('username'), \
details.get('password'), details.get('protocol'), \
details.get('port'), details.get('mechanism'), \
details.get('principal'), details.get('domain') | python | def _get_proxy_connection_details():
'''
Returns the connection details of the following proxies: esxi
'''
proxytype = get_proxy_type()
if proxytype == 'esxi':
details = __salt__['esxi.get_details']()
elif proxytype == 'esxcluster':
details = __salt__['esxcluster.get_details']()
elif proxytype == 'esxdatacenter':
details = __salt__['esxdatacenter.get_details']()
elif proxytype == 'vcenter':
details = __salt__['vcenter.get_details']()
elif proxytype == 'esxvm':
details = __salt__['esxvm.get_details']()
else:
raise CommandExecutionError('\'{0}\' proxy is not supported'
''.format(proxytype))
return \
details.get('vcenter') if 'vcenter' in details \
else details.get('host'), \
details.get('username'), \
details.get('password'), details.get('protocol'), \
details.get('port'), details.get('mechanism'), \
details.get('principal'), details.get('domain') | [
"def",
"_get_proxy_connection_details",
"(",
")",
":",
"proxytype",
"=",
"get_proxy_type",
"(",
")",
"if",
"proxytype",
"==",
"'esxi'",
":",
"details",
"=",
"__salt__",
"[",
"'esxi.get_details'",
"]",
"(",
")",
"elif",
"proxytype",
"==",
"'esxcluster'",
":",
"... | Returns the connection details of the following proxies: esxi | [
"Returns",
"the",
"connection",
"details",
"of",
"the",
"following",
"proxies",
":",
"esxi"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L253-L277 | train |
saltstack/salt | salt/modules/vsphere.py | supports_proxies | def supports_proxies(*proxy_types):
'''
Decorator to specify which proxy types are supported by a function
proxy_types:
Arbitrary list of strings with the supported types of proxies
'''
def _supports_proxies(fn):
@wraps(fn)
def __supports_proxies(*args, **kwargs):
proxy_type = get_proxy_type()
if proxy_type not in proxy_types:
raise CommandExecutionError(
'\'{0}\' proxy is not supported by function {1}'
''.format(proxy_type, fn.__name__))
return fn(*args, **salt.utils.args.clean_kwargs(**kwargs))
return __supports_proxies
return _supports_proxies | python | def supports_proxies(*proxy_types):
'''
Decorator to specify which proxy types are supported by a function
proxy_types:
Arbitrary list of strings with the supported types of proxies
'''
def _supports_proxies(fn):
@wraps(fn)
def __supports_proxies(*args, **kwargs):
proxy_type = get_proxy_type()
if proxy_type not in proxy_types:
raise CommandExecutionError(
'\'{0}\' proxy is not supported by function {1}'
''.format(proxy_type, fn.__name__))
return fn(*args, **salt.utils.args.clean_kwargs(**kwargs))
return __supports_proxies
return _supports_proxies | [
"def",
"supports_proxies",
"(",
"*",
"proxy_types",
")",
":",
"def",
"_supports_proxies",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"__supports_proxies",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"proxy_type",
"=",
"get_proxy_t... | Decorator to specify which proxy types are supported by a function
proxy_types:
Arbitrary list of strings with the supported types of proxies | [
"Decorator",
"to",
"specify",
"which",
"proxy",
"types",
"are",
"supported",
"by",
"a",
"function"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L280-L297 | train |
saltstack/salt | salt/modules/vsphere.py | gets_service_instance_via_proxy | def gets_service_instance_via_proxy(fn):
'''
Decorator that connects to a target system (vCenter or ESXi host) using the
proxy details and passes the connection (vim.ServiceInstance) to
the decorated function.
Supported proxies: esxi, esxcluster, esxdatacenter.
Notes:
1. The decorated function must have a ``service_instance`` parameter
or a ``**kwarg`` type argument (name of argument is not important);
2. If the ``service_instance`` parameter is already defined, the value
is passed through to the decorated function;
3. If the ``service_instance`` parameter in not defined, the
connection is created using the proxy details and the service instance
is returned.
CLI Example:
None, this is a decorator
'''
fn_name = fn.__name__
try:
arg_names, args_name, kwargs_name, default_values, _, _, _ = \
inspect.getfullargspec(fn)
except AttributeError:
# Fallback to Python 2.7
arg_names, args_name, kwargs_name, default_values = \
inspect.getargspec(fn)
default_values = default_values if default_values is not None else []
@wraps(fn)
def _gets_service_instance_via_proxy(*args, **kwargs):
if 'service_instance' not in arg_names and not kwargs_name:
raise CommandExecutionError(
'Function {0} must have either a \'service_instance\', or a '
'\'**kwargs\' type parameter'.format(fn_name))
connection_details = _get_proxy_connection_details()
# Figure out how to pass in the connection value
local_service_instance = None
if 'service_instance' in arg_names:
idx = arg_names.index('service_instance')
if idx >= len(arg_names) - len(default_values):
# 'service_instance' has a default value:
# we check if we need to instantiate it or
# pass it through
#
# NOTE: if 'service_instance' doesn't have a default value
# it must be explicitly set in the function call so we pass it
# through
# There are two cases:
# 1. service_instance was passed in as a positional parameter
# 2. service_instance was passed in as a named paramter
if len(args) > idx:
# case 1: The call was made with enough positional
# parameters to include 'service_instance'
if not args[idx]:
local_service_instance = \
salt.utils.vmware.get_service_instance(
*connection_details)
# Tuples are immutable, so if we want to change what
# was passed in, we need to first convert to a list.
args = list(args)
args[idx] = local_service_instance
else:
# case 2: Not enough positional parameters so
# 'service_instance' must be a named parameter
if not kwargs.get('service_instance'):
local_service_instance = \
salt.utils.vmware.get_service_instance(
*connection_details)
kwargs['service_instance'] = local_service_instance
else:
# 'service_instance' is not a paremter in the function definition
# but it will be caught by the **kwargs parameter
if not kwargs.get('service_instance'):
local_service_instance = \
salt.utils.vmware.get_service_instance(
*connection_details)
kwargs['service_instance'] = local_service_instance
try:
ret = fn(*args, **salt.utils.args.clean_kwargs(**kwargs))
# Disconnect if connected in the decorator
if local_service_instance:
salt.utils.vmware.disconnect(local_service_instance)
return ret
except Exception as e:
# Disconnect if connected in the decorator
if local_service_instance:
salt.utils.vmware.disconnect(local_service_instance)
# raise original exception and traceback
six.reraise(*sys.exc_info())
return _gets_service_instance_via_proxy | python | def gets_service_instance_via_proxy(fn):
'''
Decorator that connects to a target system (vCenter or ESXi host) using the
proxy details and passes the connection (vim.ServiceInstance) to
the decorated function.
Supported proxies: esxi, esxcluster, esxdatacenter.
Notes:
1. The decorated function must have a ``service_instance`` parameter
or a ``**kwarg`` type argument (name of argument is not important);
2. If the ``service_instance`` parameter is already defined, the value
is passed through to the decorated function;
3. If the ``service_instance`` parameter in not defined, the
connection is created using the proxy details and the service instance
is returned.
CLI Example:
None, this is a decorator
'''
fn_name = fn.__name__
try:
arg_names, args_name, kwargs_name, default_values, _, _, _ = \
inspect.getfullargspec(fn)
except AttributeError:
# Fallback to Python 2.7
arg_names, args_name, kwargs_name, default_values = \
inspect.getargspec(fn)
default_values = default_values if default_values is not None else []
@wraps(fn)
def _gets_service_instance_via_proxy(*args, **kwargs):
if 'service_instance' not in arg_names and not kwargs_name:
raise CommandExecutionError(
'Function {0} must have either a \'service_instance\', or a '
'\'**kwargs\' type parameter'.format(fn_name))
connection_details = _get_proxy_connection_details()
# Figure out how to pass in the connection value
local_service_instance = None
if 'service_instance' in arg_names:
idx = arg_names.index('service_instance')
if idx >= len(arg_names) - len(default_values):
# 'service_instance' has a default value:
# we check if we need to instantiate it or
# pass it through
#
# NOTE: if 'service_instance' doesn't have a default value
# it must be explicitly set in the function call so we pass it
# through
# There are two cases:
# 1. service_instance was passed in as a positional parameter
# 2. service_instance was passed in as a named paramter
if len(args) > idx:
# case 1: The call was made with enough positional
# parameters to include 'service_instance'
if not args[idx]:
local_service_instance = \
salt.utils.vmware.get_service_instance(
*connection_details)
# Tuples are immutable, so if we want to change what
# was passed in, we need to first convert to a list.
args = list(args)
args[idx] = local_service_instance
else:
# case 2: Not enough positional parameters so
# 'service_instance' must be a named parameter
if not kwargs.get('service_instance'):
local_service_instance = \
salt.utils.vmware.get_service_instance(
*connection_details)
kwargs['service_instance'] = local_service_instance
else:
# 'service_instance' is not a paremter in the function definition
# but it will be caught by the **kwargs parameter
if not kwargs.get('service_instance'):
local_service_instance = \
salt.utils.vmware.get_service_instance(
*connection_details)
kwargs['service_instance'] = local_service_instance
try:
ret = fn(*args, **salt.utils.args.clean_kwargs(**kwargs))
# Disconnect if connected in the decorator
if local_service_instance:
salt.utils.vmware.disconnect(local_service_instance)
return ret
except Exception as e:
# Disconnect if connected in the decorator
if local_service_instance:
salt.utils.vmware.disconnect(local_service_instance)
# raise original exception and traceback
six.reraise(*sys.exc_info())
return _gets_service_instance_via_proxy | [
"def",
"gets_service_instance_via_proxy",
"(",
"fn",
")",
":",
"fn_name",
"=",
"fn",
".",
"__name__",
"try",
":",
"arg_names",
",",
"args_name",
",",
"kwargs_name",
",",
"default_values",
",",
"_",
",",
"_",
",",
"_",
"=",
"inspect",
".",
"getfullargspec",
... | Decorator that connects to a target system (vCenter or ESXi host) using the
proxy details and passes the connection (vim.ServiceInstance) to
the decorated function.
Supported proxies: esxi, esxcluster, esxdatacenter.
Notes:
1. The decorated function must have a ``service_instance`` parameter
or a ``**kwarg`` type argument (name of argument is not important);
2. If the ``service_instance`` parameter is already defined, the value
is passed through to the decorated function;
3. If the ``service_instance`` parameter in not defined, the
connection is created using the proxy details and the service instance
is returned.
CLI Example:
None, this is a decorator | [
"Decorator",
"that",
"connects",
"to",
"a",
"target",
"system",
"(",
"vCenter",
"or",
"ESXi",
"host",
")",
"using",
"the",
"proxy",
"details",
"and",
"passes",
"the",
"connection",
"(",
"vim",
".",
"ServiceInstance",
")",
"to",
"the",
"decorated",
"function"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L300-L392 | train |
saltstack/salt | salt/modules/vsphere.py | esxcli_cmd | def esxcli_cmd(cmd_str, host=None, username=None, password=None, protocol=None, port=None, esxi_hosts=None, credstore=None):
'''
Run an ESXCLI command directly on the host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
cmd_str
The ESXCLI command to run. Note: This should not include the ``-s``, ``-u``,
``-p``, ``-h``, ``--protocol``, or ``--portnumber`` arguments that are
frequently passed when using a bare ESXCLI command from the command line.
Those arguments are handled by this function via the other args and kwargs.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.esxcli_cmd my.esxi.host root bad-password \
'system coredump network get'
# Used for connecting to a vCenter Server
salt '*' vsphere.esxcli_cmd my.vcenter.location root bad-password \
'system coredump network get' esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd_str,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
if response['retcode'] != 0:
ret.update({esxi_host: {'Error': response.get('stdout')}})
else:
ret.update({esxi_host: response})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = salt.utils.vmware.esxcli(host, username, password, cmd_str,
protocol=protocol, port=port,
credstore=credstore)
if response['retcode'] != 0:
ret.update({host: {'Error': response.get('stdout')}})
else:
ret.update({host: response})
return ret | python | def esxcli_cmd(cmd_str, host=None, username=None, password=None, protocol=None, port=None, esxi_hosts=None, credstore=None):
'''
Run an ESXCLI command directly on the host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
cmd_str
The ESXCLI command to run. Note: This should not include the ``-s``, ``-u``,
``-p``, ``-h``, ``--protocol``, or ``--portnumber`` arguments that are
frequently passed when using a bare ESXCLI command from the command line.
Those arguments are handled by this function via the other args and kwargs.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.esxcli_cmd my.esxi.host root bad-password \
'system coredump network get'
# Used for connecting to a vCenter Server
salt '*' vsphere.esxcli_cmd my.vcenter.location root bad-password \
'system coredump network get' esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd_str,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
if response['retcode'] != 0:
ret.update({esxi_host: {'Error': response.get('stdout')}})
else:
ret.update({esxi_host: response})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = salt.utils.vmware.esxcli(host, username, password, cmd_str,
protocol=protocol, port=port,
credstore=credstore)
if response['retcode'] != 0:
ret.update({host: {'Error': response.get('stdout')}})
else:
ret.update({host: response})
return ret | [
"def",
"esxcli_cmd",
"(",
"cmd_str",
",",
"host",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"esxi_hosts",
"=",
"None",
",",
"credstore",
"=",
"None",
")",
":"... | Run an ESXCLI command directly on the host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
cmd_str
The ESXCLI command to run. Note: This should not include the ``-s``, ``-u``,
``-p``, ``-h``, ``--protocol``, or ``--portnumber`` arguments that are
frequently passed when using a bare ESXCLI command from the command line.
Those arguments are handled by this function via the other args and kwargs.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.esxcli_cmd my.esxi.host root bad-password \
'system coredump network get'
# Used for connecting to a vCenter Server
salt '*' vsphere.esxcli_cmd my.vcenter.location root bad-password \
'system coredump network get' esxi_hosts='[esxi-1.host.com, esxi-2.host.com]' | [
"Run",
"an",
"ESXCLI",
"command",
"directly",
"on",
"the",
"host",
"or",
"list",
"of",
"hosts",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L436-L505 | train |
saltstack/salt | salt/modules/vsphere.py | get_coredump_network_config | def get_coredump_network_config(host, username, password, protocol=None, port=None, esxi_hosts=None, credstore=None):
'''
Retrieve information on ESXi or vCenter network dump collection and
format it into a dictionary.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: A dictionary with the network configuration, or, if getting
the network config failed, a an error message retrieved from the
standard cmd.run_all dictionary, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.get_coredump_network_config my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_coredump_network_config my.vcenter.location root bad-password \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
cmd = 'system coredump network get'
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
if response['retcode'] != 0:
ret.update({esxi_host: {'Error': response.get('stdout')}})
else:
# format the response stdout into something useful
ret.update({esxi_host: {'Coredump Config': _format_coredump_stdout(response)}})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
credstore=credstore)
if response['retcode'] != 0:
ret.update({host: {'Error': response.get('stdout')}})
else:
# format the response stdout into something useful
stdout = _format_coredump_stdout(response)
ret.update({host: {'Coredump Config': stdout}})
return ret | python | def get_coredump_network_config(host, username, password, protocol=None, port=None, esxi_hosts=None, credstore=None):
'''
Retrieve information on ESXi or vCenter network dump collection and
format it into a dictionary.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: A dictionary with the network configuration, or, if getting
the network config failed, a an error message retrieved from the
standard cmd.run_all dictionary, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.get_coredump_network_config my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_coredump_network_config my.vcenter.location root bad-password \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
cmd = 'system coredump network get'
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
if response['retcode'] != 0:
ret.update({esxi_host: {'Error': response.get('stdout')}})
else:
# format the response stdout into something useful
ret.update({esxi_host: {'Coredump Config': _format_coredump_stdout(response)}})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
credstore=credstore)
if response['retcode'] != 0:
ret.update({host: {'Error': response.get('stdout')}})
else:
# format the response stdout into something useful
stdout = _format_coredump_stdout(response)
ret.update({host: {'Coredump Config': stdout}})
return ret | [
"def",
"get_coredump_network_config",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"esxi_hosts",
"=",
"None",
",",
"credstore",
"=",
"None",
")",
":",
"cmd",
"=",
"'system coredump network get'",
... | Retrieve information on ESXi or vCenter network dump collection and
format it into a dictionary.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: A dictionary with the network configuration, or, if getting
the network config failed, a an error message retrieved from the
standard cmd.run_all dictionary, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.get_coredump_network_config my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_coredump_network_config my.vcenter.location root bad-password \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]' | [
"Retrieve",
"information",
"on",
"ESXi",
"or",
"vCenter",
"network",
"dump",
"collection",
"and",
"format",
"it",
"into",
"a",
"dictionary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L509-L581 | train |
saltstack/salt | salt/modules/vsphere.py | coredump_network_enable | def coredump_network_enable(host, username, password, enabled, protocol=None, port=None, esxi_hosts=None, credstore=None):
'''
Enable or disable ESXi core dump collection. Returns ``True`` if coredump is enabled
and returns ``False`` if core dump is not enabled. If there was an error, the error
will be the value printed in the ``Error`` key dictionary for the given host.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
enabled
Python True or False to enable or disable coredumps.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.coredump_network_enable my.esxi.host root bad-password True
# Used for connecting to a vCenter Server
salt '*' vsphere.coredump_network_enable my.vcenter.location root bad-password True \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
if enabled:
enable_it = 1
else:
enable_it = 0
cmd = 'system coredump network set -e {0}'.format(enable_it)
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
if response['retcode'] != 0:
ret.update({esxi_host: {'Error': response.get('stdout')}})
else:
ret.update({esxi_host: {'Coredump Enabled': enabled}})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
credstore=credstore)
if response['retcode'] != 0:
ret.update({host: {'Error': response.get('stdout')}})
else:
ret.update({host: {'Coredump Enabled': enabled}})
return ret | python | def coredump_network_enable(host, username, password, enabled, protocol=None, port=None, esxi_hosts=None, credstore=None):
'''
Enable or disable ESXi core dump collection. Returns ``True`` if coredump is enabled
and returns ``False`` if core dump is not enabled. If there was an error, the error
will be the value printed in the ``Error`` key dictionary for the given host.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
enabled
Python True or False to enable or disable coredumps.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.coredump_network_enable my.esxi.host root bad-password True
# Used for connecting to a vCenter Server
salt '*' vsphere.coredump_network_enable my.vcenter.location root bad-password True \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
if enabled:
enable_it = 1
else:
enable_it = 0
cmd = 'system coredump network set -e {0}'.format(enable_it)
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
if response['retcode'] != 0:
ret.update({esxi_host: {'Error': response.get('stdout')}})
else:
ret.update({esxi_host: {'Coredump Enabled': enabled}})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
credstore=credstore)
if response['retcode'] != 0:
ret.update({host: {'Error': response.get('stdout')}})
else:
ret.update({host: {'Coredump Enabled': enabled}})
return ret | [
"def",
"coredump_network_enable",
"(",
"host",
",",
"username",
",",
"password",
",",
"enabled",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"esxi_hosts",
"=",
"None",
",",
"credstore",
"=",
"None",
")",
":",
"if",
"enabled",
":",
"enabl... | Enable or disable ESXi core dump collection. Returns ``True`` if coredump is enabled
and returns ``False`` if core dump is not enabled. If there was an error, the error
will be the value printed in the ``Error`` key dictionary for the given host.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
enabled
Python True or False to enable or disable coredumps.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.coredump_network_enable my.esxi.host root bad-password True
# Used for connecting to a vCenter Server
salt '*' vsphere.coredump_network_enable my.vcenter.location root bad-password True \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]' | [
"Enable",
"or",
"disable",
"ESXi",
"core",
"dump",
"collection",
".",
"Returns",
"True",
"if",
"coredump",
"is",
"enabled",
"and",
"returns",
"False",
"if",
"core",
"dump",
"is",
"not",
"enabled",
".",
"If",
"there",
"was",
"an",
"error",
"the",
"error",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L585-L659 | train |
saltstack/salt | salt/modules/vsphere.py | enable_firewall_ruleset | def enable_firewall_ruleset(host,
username,
password,
ruleset_enable,
ruleset_name,
protocol=None,
port=None,
esxi_hosts=None,
credstore=None):
'''
Enable or disable an ESXi firewall rule set.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
ruleset_enable
True to enable the ruleset, false to disable.
ruleset_name
Name of ruleset to target.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: A standard cmd.run_all dictionary, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.enable_firewall_ruleset my.esxi.host root bad-password True 'syslog'
# Used for connecting to a vCenter Server
salt '*' vsphere.enable_firewall_ruleset my.vcenter.location root bad-password True 'syslog' \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
cmd = 'network firewall ruleset set --enabled {0} --ruleset-id={1}'.format(
ruleset_enable, ruleset_name
)
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
ret.update({esxi_host: response})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
credstore=credstore)
ret.update({host: response})
return ret | python | def enable_firewall_ruleset(host,
username,
password,
ruleset_enable,
ruleset_name,
protocol=None,
port=None,
esxi_hosts=None,
credstore=None):
'''
Enable or disable an ESXi firewall rule set.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
ruleset_enable
True to enable the ruleset, false to disable.
ruleset_name
Name of ruleset to target.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: A standard cmd.run_all dictionary, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.enable_firewall_ruleset my.esxi.host root bad-password True 'syslog'
# Used for connecting to a vCenter Server
salt '*' vsphere.enable_firewall_ruleset my.vcenter.location root bad-password True 'syslog' \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
cmd = 'network firewall ruleset set --enabled {0} --ruleset-id={1}'.format(
ruleset_enable, ruleset_name
)
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
ret.update({esxi_host: response})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
credstore=credstore)
ret.update({host: response})
return ret | [
"def",
"enable_firewall_ruleset",
"(",
"host",
",",
"username",
",",
"password",
",",
"ruleset_enable",
",",
"ruleset_name",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"esxi_hosts",
"=",
"None",
",",
"credstore",
"=",
"None",
")",
":",
"c... | Enable or disable an ESXi firewall rule set.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
ruleset_enable
True to enable the ruleset, false to disable.
ruleset_name
Name of ruleset to target.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: A standard cmd.run_all dictionary, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.enable_firewall_ruleset my.esxi.host root bad-password True 'syslog'
# Used for connecting to a vCenter Server
salt '*' vsphere.enable_firewall_ruleset my.vcenter.location root bad-password True 'syslog' \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]' | [
"Enable",
"or",
"disable",
"an",
"ESXi",
"firewall",
"rule",
"set",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L839-L915 | train |
saltstack/salt | salt/modules/vsphere.py | set_syslog_config | def set_syslog_config(host,
username,
password,
syslog_config,
config_value,
protocol=None,
port=None,
firewall=True,
reset_service=True,
esxi_hosts=None,
credstore=None):
'''
Set the specified syslog configuration parameter. By default, this function will
reset the syslog service after the configuration is set.
host
ESXi or vCenter host to connect to.
username
User to connect as, usually root.
password
Password to connect with.
syslog_config
Name of parameter to set (corresponds to the command line switch for
esxcli without the double dashes (--))
Valid syslog_config values are ``logdir``, ``loghost``, ``default-rotate`,
``default-size``, ``default-timeout``, and ``logdir-unique``.
config_value
Value for the above parameter. For ``loghost``, URLs or IP addresses to
use for logging. Multiple log servers can be specified by listing them,
comma-separated, but without spaces before or after commas.
(reference: https://blogs.vmware.com/vsphere/2012/04/configuring-multiple-syslog-servers-for-esxi-5.html)
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
firewall
Enable the firewall rule set for syslog. Defaults to ``True``.
reset_service
After a successful parameter set, reset the service. Defaults to ``True``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: Dictionary with a top-level key of 'success' which indicates
if all the parameters were reset, and individual keys
for each parameter indicating which succeeded or failed, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.set_syslog_config my.esxi.host root bad-password \
loghost ssl://localhost:5432,tcp://10.1.0.1:1514
# Used for connecting to a vCenter Server
salt '*' vsphere.set_syslog_config my.vcenter.location root bad-password \
loghost ssl://localhost:5432,tcp://10.1.0.1:1514 \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
ret = {}
# First, enable the syslog firewall ruleset, for each host, if needed.
if firewall and syslog_config == 'loghost':
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = enable_firewall_ruleset(host, username, password,
ruleset_enable=True, ruleset_name='syslog',
protocol=protocol, port=port,
esxi_hosts=[esxi_host], credstore=credstore).get(esxi_host)
if response['retcode'] != 0:
ret.update({esxi_host: {'enable_firewall': {'message': response['stdout'],
'success': False}}})
else:
ret.update({esxi_host: {'enable_firewall': {'success': True}}})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = enable_firewall_ruleset(host, username, password,
ruleset_enable=True, ruleset_name='syslog',
protocol=protocol, port=port,
credstore=credstore).get(host)
if response['retcode'] != 0:
ret.update({host: {'enable_firewall': {'message': response['stdout'],
'success': False}}})
else:
ret.update({host: {'enable_firewall': {'success': True}}})
# Set the config value on each esxi_host, if provided.
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = _set_syslog_config_helper(host, username, password, syslog_config,
config_value, protocol=protocol, port=port,
reset_service=reset_service, esxi_host=esxi_host,
credstore=credstore)
# Ensure we don't overwrite any dictionary data already set
# By updating the esxi_host directly.
if ret.get(esxi_host) is None:
ret.update({esxi_host: {}})
ret[esxi_host].update(response)
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = _set_syslog_config_helper(host, username, password, syslog_config,
config_value, protocol=protocol, port=port,
reset_service=reset_service, credstore=credstore)
# Ensure we don't overwrite any dictionary data already set
# By updating the host directly.
if ret.get(host) is None:
ret.update({host: {}})
ret[host].update(response)
return ret | python | def set_syslog_config(host,
username,
password,
syslog_config,
config_value,
protocol=None,
port=None,
firewall=True,
reset_service=True,
esxi_hosts=None,
credstore=None):
'''
Set the specified syslog configuration parameter. By default, this function will
reset the syslog service after the configuration is set.
host
ESXi or vCenter host to connect to.
username
User to connect as, usually root.
password
Password to connect with.
syslog_config
Name of parameter to set (corresponds to the command line switch for
esxcli without the double dashes (--))
Valid syslog_config values are ``logdir``, ``loghost``, ``default-rotate`,
``default-size``, ``default-timeout``, and ``logdir-unique``.
config_value
Value for the above parameter. For ``loghost``, URLs or IP addresses to
use for logging. Multiple log servers can be specified by listing them,
comma-separated, but without spaces before or after commas.
(reference: https://blogs.vmware.com/vsphere/2012/04/configuring-multiple-syslog-servers-for-esxi-5.html)
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
firewall
Enable the firewall rule set for syslog. Defaults to ``True``.
reset_service
After a successful parameter set, reset the service. Defaults to ``True``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: Dictionary with a top-level key of 'success' which indicates
if all the parameters were reset, and individual keys
for each parameter indicating which succeeded or failed, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.set_syslog_config my.esxi.host root bad-password \
loghost ssl://localhost:5432,tcp://10.1.0.1:1514
# Used for connecting to a vCenter Server
salt '*' vsphere.set_syslog_config my.vcenter.location root bad-password \
loghost ssl://localhost:5432,tcp://10.1.0.1:1514 \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
ret = {}
# First, enable the syslog firewall ruleset, for each host, if needed.
if firewall and syslog_config == 'loghost':
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = enable_firewall_ruleset(host, username, password,
ruleset_enable=True, ruleset_name='syslog',
protocol=protocol, port=port,
esxi_hosts=[esxi_host], credstore=credstore).get(esxi_host)
if response['retcode'] != 0:
ret.update({esxi_host: {'enable_firewall': {'message': response['stdout'],
'success': False}}})
else:
ret.update({esxi_host: {'enable_firewall': {'success': True}}})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = enable_firewall_ruleset(host, username, password,
ruleset_enable=True, ruleset_name='syslog',
protocol=protocol, port=port,
credstore=credstore).get(host)
if response['retcode'] != 0:
ret.update({host: {'enable_firewall': {'message': response['stdout'],
'success': False}}})
else:
ret.update({host: {'enable_firewall': {'success': True}}})
# Set the config value on each esxi_host, if provided.
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = _set_syslog_config_helper(host, username, password, syslog_config,
config_value, protocol=protocol, port=port,
reset_service=reset_service, esxi_host=esxi_host,
credstore=credstore)
# Ensure we don't overwrite any dictionary data already set
# By updating the esxi_host directly.
if ret.get(esxi_host) is None:
ret.update({esxi_host: {}})
ret[esxi_host].update(response)
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = _set_syslog_config_helper(host, username, password, syslog_config,
config_value, protocol=protocol, port=port,
reset_service=reset_service, credstore=credstore)
# Ensure we don't overwrite any dictionary data already set
# By updating the host directly.
if ret.get(host) is None:
ret.update({host: {}})
ret[host].update(response)
return ret | [
"def",
"set_syslog_config",
"(",
"host",
",",
"username",
",",
"password",
",",
"syslog_config",
",",
"config_value",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"firewall",
"=",
"True",
",",
"reset_service",
"=",
"True",
",",
"esxi_hosts",
... | Set the specified syslog configuration parameter. By default, this function will
reset the syslog service after the configuration is set.
host
ESXi or vCenter host to connect to.
username
User to connect as, usually root.
password
Password to connect with.
syslog_config
Name of parameter to set (corresponds to the command line switch for
esxcli without the double dashes (--))
Valid syslog_config values are ``logdir``, ``loghost``, ``default-rotate`,
``default-size``, ``default-timeout``, and ``logdir-unique``.
config_value
Value for the above parameter. For ``loghost``, URLs or IP addresses to
use for logging. Multiple log servers can be specified by listing them,
comma-separated, but without spaces before or after commas.
(reference: https://blogs.vmware.com/vsphere/2012/04/configuring-multiple-syslog-servers-for-esxi-5.html)
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
firewall
Enable the firewall rule set for syslog. Defaults to ``True``.
reset_service
After a successful parameter set, reset the service. Defaults to ``True``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: Dictionary with a top-level key of 'success' which indicates
if all the parameters were reset, and individual keys
for each parameter indicating which succeeded or failed, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.set_syslog_config my.esxi.host root bad-password \
loghost ssl://localhost:5432,tcp://10.1.0.1:1514
# Used for connecting to a vCenter Server
salt '*' vsphere.set_syslog_config my.vcenter.location root bad-password \
loghost ssl://localhost:5432,tcp://10.1.0.1:1514 \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]' | [
"Set",
"the",
"specified",
"syslog",
"configuration",
"parameter",
".",
"By",
"default",
"this",
"function",
"will",
"reset",
"the",
"syslog",
"service",
"after",
"the",
"configuration",
"is",
"set",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L984-L1118 | train |
saltstack/salt | salt/modules/vsphere.py | get_syslog_config | def get_syslog_config(host, username, password, protocol=None, port=None, esxi_hosts=None, credstore=None):
'''
Retrieve the syslog configuration.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: Dictionary with keys and values corresponding to the
syslog configuration, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.get_syslog_config my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_syslog_config my.vcenter.location root bad-password \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
cmd = 'system syslog config get'
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
# format the response stdout into something useful
ret.update({esxi_host: _format_syslog_config(response)})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
credstore=credstore)
# format the response stdout into something useful
ret.update({host: _format_syslog_config(response)})
return ret | python | def get_syslog_config(host, username, password, protocol=None, port=None, esxi_hosts=None, credstore=None):
'''
Retrieve the syslog configuration.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: Dictionary with keys and values corresponding to the
syslog configuration, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.get_syslog_config my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_syslog_config my.vcenter.location root bad-password \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
cmd = 'system syslog config get'
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
# format the response stdout into something useful
ret.update({esxi_host: _format_syslog_config(response)})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response = salt.utils.vmware.esxcli(host, username, password, cmd,
protocol=protocol, port=port,
credstore=credstore)
# format the response stdout into something useful
ret.update({host: _format_syslog_config(response)})
return ret | [
"def",
"get_syslog_config",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"esxi_hosts",
"=",
"None",
",",
"credstore",
"=",
"None",
")",
":",
"cmd",
"=",
"'system syslog config get'",
"ret",
"="... | Retrieve the syslog configuration.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: Dictionary with keys and values corresponding to the
syslog configuration, per host.
CLI Example:
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.get_syslog_config my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_syslog_config my.vcenter.location root bad-password \
esxi_hosts='[esxi-1.host.com, esxi-2.host.com]' | [
"Retrieve",
"the",
"syslog",
"configuration",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1122-L1185 | train |
saltstack/salt | salt/modules/vsphere.py | reset_syslog_config | def reset_syslog_config(host,
username,
password,
protocol=None,
port=None,
syslog_config=None,
esxi_hosts=None,
credstore=None):
'''
Reset the syslog service to its default settings.
Valid syslog_config values are ``logdir``, ``loghost``, ``logdir-unique``,
``default-rotate``, ``default-size``, ``default-timeout``,
or ``all`` for all of these.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
syslog_config
List of parameters to reset, provided as a comma-delimited string, or 'all' to
reset all syslog configuration parameters. Required.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: Dictionary with a top-level key of 'success' which indicates
if all the parameters were reset, and individual keys
for each parameter indicating which succeeded or failed, per host.
CLI Example:
``syslog_config`` can be passed as a quoted, comma-separated string, e.g.
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.reset_syslog_config my.esxi.host root bad-password \
syslog_config='logdir,loghost'
# Used for connecting to a vCenter Server
salt '*' vsphere.reset_syslog_config my.vcenter.location root bad-password \
syslog_config='logdir,loghost' esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
if not syslog_config:
raise CommandExecutionError('The \'reset_syslog_config\' function requires a '
'\'syslog_config\' setting.')
valid_resets = ['logdir', 'loghost', 'default-rotate',
'default-size', 'default-timeout', 'logdir-unique']
cmd = 'system syslog config set --reset='
if ',' in syslog_config:
resets = [ind_reset.strip() for ind_reset in syslog_config.split(',')]
elif syslog_config == 'all':
resets = valid_resets
else:
resets = [syslog_config]
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response_dict = _reset_syslog_config_params(host, username, password,
cmd, resets, valid_resets,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
ret.update({esxi_host: response_dict})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response_dict = _reset_syslog_config_params(host, username, password,
cmd, resets, valid_resets,
protocol=protocol, port=port,
credstore=credstore)
ret.update({host: response_dict})
return ret | python | def reset_syslog_config(host,
username,
password,
protocol=None,
port=None,
syslog_config=None,
esxi_hosts=None,
credstore=None):
'''
Reset the syslog service to its default settings.
Valid syslog_config values are ``logdir``, ``loghost``, ``logdir-unique``,
``default-rotate``, ``default-size``, ``default-timeout``,
or ``all`` for all of these.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
syslog_config
List of parameters to reset, provided as a comma-delimited string, or 'all' to
reset all syslog configuration parameters. Required.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: Dictionary with a top-level key of 'success' which indicates
if all the parameters were reset, and individual keys
for each parameter indicating which succeeded or failed, per host.
CLI Example:
``syslog_config`` can be passed as a quoted, comma-separated string, e.g.
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.reset_syslog_config my.esxi.host root bad-password \
syslog_config='logdir,loghost'
# Used for connecting to a vCenter Server
salt '*' vsphere.reset_syslog_config my.vcenter.location root bad-password \
syslog_config='logdir,loghost' esxi_hosts='[esxi-1.host.com, esxi-2.host.com]'
'''
if not syslog_config:
raise CommandExecutionError('The \'reset_syslog_config\' function requires a '
'\'syslog_config\' setting.')
valid_resets = ['logdir', 'loghost', 'default-rotate',
'default-size', 'default-timeout', 'logdir-unique']
cmd = 'system syslog config set --reset='
if ',' in syslog_config:
resets = [ind_reset.strip() for ind_reset in syslog_config.split(',')]
elif syslog_config == 'all':
resets = valid_resets
else:
resets = [syslog_config]
ret = {}
if esxi_hosts:
if not isinstance(esxi_hosts, list):
raise CommandExecutionError('\'esxi_hosts\' must be a list.')
for esxi_host in esxi_hosts:
response_dict = _reset_syslog_config_params(host, username, password,
cmd, resets, valid_resets,
protocol=protocol, port=port,
esxi_host=esxi_host, credstore=credstore)
ret.update({esxi_host: response_dict})
else:
# Handles a single host or a vCenter connection when no esxi_hosts are provided.
response_dict = _reset_syslog_config_params(host, username, password,
cmd, resets, valid_resets,
protocol=protocol, port=port,
credstore=credstore)
ret.update({host: response_dict})
return ret | [
"def",
"reset_syslog_config",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"syslog_config",
"=",
"None",
",",
"esxi_hosts",
"=",
"None",
",",
"credstore",
"=",
"None",
")",
":",
"if",
"not",
... | Reset the syslog service to its default settings.
Valid syslog_config values are ``logdir``, ``loghost``, ``logdir-unique``,
``default-rotate``, ``default-size``, ``default-timeout``,
or ``all`` for all of these.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
syslog_config
List of parameters to reset, provided as a comma-delimited string, or 'all' to
reset all syslog configuration parameters. Required.
esxi_hosts
If ``host`` is a vCenter host, then use esxi_hosts to execute this function
on a list of one or more ESXi machines.
credstore
Optionally set to path to the credential store file.
:return: Dictionary with a top-level key of 'success' which indicates
if all the parameters were reset, and individual keys
for each parameter indicating which succeeded or failed, per host.
CLI Example:
``syslog_config`` can be passed as a quoted, comma-separated string, e.g.
.. code-block:: bash
# Used for ESXi host connection information
salt '*' vsphere.reset_syslog_config my.esxi.host root bad-password \
syslog_config='logdir,loghost'
# Used for connecting to a vCenter Server
salt '*' vsphere.reset_syslog_config my.vcenter.location root bad-password \
syslog_config='logdir,loghost' esxi_hosts='[esxi-1.host.com, esxi-2.host.com]' | [
"Reset",
"the",
"syslog",
"service",
"to",
"its",
"default",
"settings",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1189-L1283 | train |
saltstack/salt | salt/modules/vsphere.py | upload_ssh_key | def upload_ssh_key(host, username, password, ssh_key=None, ssh_key_file=None,
protocol=None, port=None, certificate_verify=False):
'''
Upload an ssh key for root to an ESXi host via http PUT.
This function only works for ESXi, not vCenter.
Only one ssh key can be uploaded for root. Uploading a second key will
replace any existing key.
:param host: The location of the ESXi Host
:param username: Username to connect as
:param password: Password for the ESXi web endpoint
:param ssh_key: Public SSH key, will be added to authorized_keys on ESXi
:param ssh_key_file: File containing the SSH key. Use 'ssh_key' or
ssh_key_file, but not both.
:param protocol: defaults to https, can be http if ssl is disabled on ESXi
:param port: defaults to 443 for https
:param certificate_verify: If true require that the SSL connection present
a valid certificate
:return: Dictionary with a 'status' key, True if upload is successful.
If upload is unsuccessful, 'status' key will be False and
an 'Error' key will have an informative message.
CLI Example:
.. code-block:: bash
salt '*' vsphere.upload_ssh_key my.esxi.host root bad-password ssh_key_file='/etc/salt/my_keys/my_key.pub'
'''
if protocol is None:
protocol = 'https'
if port is None:
port = 443
url = '{0}://{1}:{2}/host/ssh_root_authorized_keys'.format(protocol,
host,
port)
ret = {}
result = None
try:
if ssh_key:
result = salt.utils.http.query(url,
status=True,
text=True,
method='PUT',
username=username,
password=password,
data=ssh_key,
verify_ssl=certificate_verify)
elif ssh_key_file:
result = salt.utils.http.query(url,
status=True,
text=True,
method='PUT',
username=username,
password=password,
data_file=ssh_key_file,
data_render=False,
verify_ssl=certificate_verify)
if result.get('status') == 200:
ret['status'] = True
else:
ret['status'] = False
ret['Error'] = result['error']
except Exception as msg:
ret['status'] = False
ret['Error'] = msg
return ret | python | def upload_ssh_key(host, username, password, ssh_key=None, ssh_key_file=None,
protocol=None, port=None, certificate_verify=False):
'''
Upload an ssh key for root to an ESXi host via http PUT.
This function only works for ESXi, not vCenter.
Only one ssh key can be uploaded for root. Uploading a second key will
replace any existing key.
:param host: The location of the ESXi Host
:param username: Username to connect as
:param password: Password for the ESXi web endpoint
:param ssh_key: Public SSH key, will be added to authorized_keys on ESXi
:param ssh_key_file: File containing the SSH key. Use 'ssh_key' or
ssh_key_file, but not both.
:param protocol: defaults to https, can be http if ssl is disabled on ESXi
:param port: defaults to 443 for https
:param certificate_verify: If true require that the SSL connection present
a valid certificate
:return: Dictionary with a 'status' key, True if upload is successful.
If upload is unsuccessful, 'status' key will be False and
an 'Error' key will have an informative message.
CLI Example:
.. code-block:: bash
salt '*' vsphere.upload_ssh_key my.esxi.host root bad-password ssh_key_file='/etc/salt/my_keys/my_key.pub'
'''
if protocol is None:
protocol = 'https'
if port is None:
port = 443
url = '{0}://{1}:{2}/host/ssh_root_authorized_keys'.format(protocol,
host,
port)
ret = {}
result = None
try:
if ssh_key:
result = salt.utils.http.query(url,
status=True,
text=True,
method='PUT',
username=username,
password=password,
data=ssh_key,
verify_ssl=certificate_verify)
elif ssh_key_file:
result = salt.utils.http.query(url,
status=True,
text=True,
method='PUT',
username=username,
password=password,
data_file=ssh_key_file,
data_render=False,
verify_ssl=certificate_verify)
if result.get('status') == 200:
ret['status'] = True
else:
ret['status'] = False
ret['Error'] = result['error']
except Exception as msg:
ret['status'] = False
ret['Error'] = msg
return ret | [
"def",
"upload_ssh_key",
"(",
"host",
",",
"username",
",",
"password",
",",
"ssh_key",
"=",
"None",
",",
"ssh_key_file",
"=",
"None",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"certificate_verify",
"=",
"False",
")",
":",
"if",
"proto... | Upload an ssh key for root to an ESXi host via http PUT.
This function only works for ESXi, not vCenter.
Only one ssh key can be uploaded for root. Uploading a second key will
replace any existing key.
:param host: The location of the ESXi Host
:param username: Username to connect as
:param password: Password for the ESXi web endpoint
:param ssh_key: Public SSH key, will be added to authorized_keys on ESXi
:param ssh_key_file: File containing the SSH key. Use 'ssh_key' or
ssh_key_file, but not both.
:param protocol: defaults to https, can be http if ssl is disabled on ESXi
:param port: defaults to 443 for https
:param certificate_verify: If true require that the SSL connection present
a valid certificate
:return: Dictionary with a 'status' key, True if upload is successful.
If upload is unsuccessful, 'status' key will be False and
an 'Error' key will have an informative message.
CLI Example:
.. code-block:: bash
salt '*' vsphere.upload_ssh_key my.esxi.host root bad-password ssh_key_file='/etc/salt/my_keys/my_key.pub' | [
"Upload",
"an",
"ssh",
"key",
"for",
"root",
"to",
"an",
"ESXi",
"host",
"via",
"http",
"PUT",
".",
"This",
"function",
"only",
"works",
"for",
"ESXi",
"not",
"vCenter",
".",
"Only",
"one",
"ssh",
"key",
"can",
"be",
"uploaded",
"for",
"root",
".",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1287-L1355 | train |
saltstack/salt | salt/modules/vsphere.py | get_ssh_key | def get_ssh_key(host,
username,
password,
protocol=None,
port=None,
certificate_verify=False):
'''
Retrieve the authorized_keys entry for root.
This function only works for ESXi, not vCenter.
:param host: The location of the ESXi Host
:param username: Username to connect as
:param password: Password for the ESXi web endpoint
:param protocol: defaults to https, can be http if ssl is disabled on ESXi
:param port: defaults to 443 for https
:param certificate_verify: If true require that the SSL connection present
a valid certificate
:return: True if upload is successful
CLI Example:
.. code-block:: bash
salt '*' vsphere.get_ssh_key my.esxi.host root bad-password certificate_verify=True
'''
if protocol is None:
protocol = 'https'
if port is None:
port = 443
url = '{0}://{1}:{2}/host/ssh_root_authorized_keys'.format(protocol,
host,
port)
ret = {}
try:
result = salt.utils.http.query(url,
status=True,
text=True,
method='GET',
username=username,
password=password,
verify_ssl=certificate_verify)
if result.get('status') == 200:
ret['status'] = True
ret['key'] = result['text']
else:
ret['status'] = False
ret['Error'] = result['error']
except Exception as msg:
ret['status'] = False
ret['Error'] = msg
return ret | python | def get_ssh_key(host,
username,
password,
protocol=None,
port=None,
certificate_verify=False):
'''
Retrieve the authorized_keys entry for root.
This function only works for ESXi, not vCenter.
:param host: The location of the ESXi Host
:param username: Username to connect as
:param password: Password for the ESXi web endpoint
:param protocol: defaults to https, can be http if ssl is disabled on ESXi
:param port: defaults to 443 for https
:param certificate_verify: If true require that the SSL connection present
a valid certificate
:return: True if upload is successful
CLI Example:
.. code-block:: bash
salt '*' vsphere.get_ssh_key my.esxi.host root bad-password certificate_verify=True
'''
if protocol is None:
protocol = 'https'
if port is None:
port = 443
url = '{0}://{1}:{2}/host/ssh_root_authorized_keys'.format(protocol,
host,
port)
ret = {}
try:
result = salt.utils.http.query(url,
status=True,
text=True,
method='GET',
username=username,
password=password,
verify_ssl=certificate_verify)
if result.get('status') == 200:
ret['status'] = True
ret['key'] = result['text']
else:
ret['status'] = False
ret['Error'] = result['error']
except Exception as msg:
ret['status'] = False
ret['Error'] = msg
return ret | [
"def",
"get_ssh_key",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"certificate_verify",
"=",
"False",
")",
":",
"if",
"protocol",
"is",
"None",
":",
"protocol",
"=",
"'https'",
"if",
"port",... | Retrieve the authorized_keys entry for root.
This function only works for ESXi, not vCenter.
:param host: The location of the ESXi Host
:param username: Username to connect as
:param password: Password for the ESXi web endpoint
:param protocol: defaults to https, can be http if ssl is disabled on ESXi
:param port: defaults to 443 for https
:param certificate_verify: If true require that the SSL connection present
a valid certificate
:return: True if upload is successful
CLI Example:
.. code-block:: bash
salt '*' vsphere.get_ssh_key my.esxi.host root bad-password certificate_verify=True | [
"Retrieve",
"the",
"authorized_keys",
"entry",
"for",
"root",
".",
"This",
"function",
"only",
"works",
"for",
"ESXi",
"not",
"vCenter",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1359-L1412 | train |
saltstack/salt | salt/modules/vsphere.py | get_host_datetime | def get_host_datetime(host, username, password, protocol=None, port=None, host_names=None):
'''
Get the date/time information for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to get date/time information.
If host_names is not provided, the date/time information will be retrieved for the
``host`` location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_host_datetime my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_host_datetime my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
date_time_manager = _get_date_time_mgr(host_ref)
date_time = date_time_manager.QueryDateTime()
ret.update({host_name: date_time})
return ret | python | def get_host_datetime(host, username, password, protocol=None, port=None, host_names=None):
'''
Get the date/time information for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to get date/time information.
If host_names is not provided, the date/time information will be retrieved for the
``host`` location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_host_datetime my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_host_datetime my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
date_time_manager = _get_date_time_mgr(host_ref)
date_time = date_time_manager.QueryDateTime()
ret.update({host_name: date_time})
return ret | [
"def",
"get_host_datetime",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_ins... | Get the date/time information for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to get date/time information.
If host_names is not provided, the date/time information will be retrieved for the
``host`` location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_host_datetime my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_host_datetime my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Get",
"the",
"date",
"/",
"time",
"information",
"for",
"a",
"given",
"host",
"or",
"list",
"of",
"host_names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1417-L1471 | train |
saltstack/salt | salt/modules/vsphere.py | get_ntp_config | def get_ntp_config(host, username, password, protocol=None, port=None, host_names=None):
'''
Get the NTP configuration information for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to get ntp configuration information.
If host_names is not provided, the NTP configuration will be retrieved for the
``host`` location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_ntp_config my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_ntp_config my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
ntp_config = host_ref.configManager.dateTimeSystem.dateTimeInfo.ntpConfig.server
ret.update({host_name: ntp_config})
return ret | python | def get_ntp_config(host, username, password, protocol=None, port=None, host_names=None):
'''
Get the NTP configuration information for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to get ntp configuration information.
If host_names is not provided, the NTP configuration will be retrieved for the
``host`` location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_ntp_config my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_ntp_config my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
ntp_config = host_ref.configManager.dateTimeSystem.dateTimeInfo.ntpConfig.server
ret.update({host_name: ntp_config})
return ret | [
"def",
"get_ntp_config",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_instan... | Get the NTP configuration information for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to get ntp configuration information.
If host_names is not provided, the NTP configuration will be retrieved for the
``host`` location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_ntp_config my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_ntp_config my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Get",
"the",
"NTP",
"configuration",
"information",
"for",
"a",
"given",
"host",
"or",
"list",
"of",
"host_names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1476-L1529 | train |
saltstack/salt | salt/modules/vsphere.py | get_service_policy | def get_service_policy(host, username, password, service_name, protocol=None, port=None, host_names=None):
'''
Get the service name's policy for a given host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
service_name
The name of the service for which to retrieve the policy. Supported service names are:
- DCUI
- TSM
- SSH
- lbtd
- lsassd
- lwiod
- netlogond
- ntpd
- sfcbd-watchdog
- snmpd
- vprobed
- vpxa
- xorg
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to get service policy information.
If host_names is not provided, the service policy information will be retrieved
for the ``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_service_policy my.esxi.host root bad-password 'ssh'
# Used for connecting to a vCenter Server
salt '*' vsphere.get_service_policy my.vcenter.location root bad-password 'ntpd' \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
valid_services = ['DCUI', 'TSM', 'SSH', 'ssh', 'lbtd', 'lsassd', 'lwiod', 'netlogond',
'ntpd', 'sfcbd-watchdog', 'snmpd', 'vprobed', 'vpxa', 'xorg']
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
# Check if the service_name provided is a valid one.
# If we don't have a valid service, return. The service will be invalid for all hosts.
if service_name not in valid_services:
ret.update({host_name: {'Error': '{0} is not a valid service name.'.format(service_name)}})
return ret
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
services = host_ref.configManager.serviceSystem.serviceInfo.service
# Don't require users to know that VMware lists the ssh service as TSM-SSH
if service_name == 'SSH' or service_name == 'ssh':
temp_service_name = 'TSM-SSH'
else:
temp_service_name = service_name
# Loop through services until we find a matching name
for service in services:
if service.key == temp_service_name:
ret.update({host_name:
{service_name: service.policy}})
# We've found a match - break out of the loop so we don't overwrite the
# Updated host_name value with an error message.
break
else:
msg = 'Could not find service \'{0}\' for host \'{1}\'.'.format(service_name,
host_name)
ret.update({host_name: {'Error': msg}})
# If we made it this far, something else has gone wrong.
if ret.get(host_name) is None:
msg = '\'vsphere.get_service_policy\' failed for host {0}.'.format(host_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
return ret | python | def get_service_policy(host, username, password, service_name, protocol=None, port=None, host_names=None):
'''
Get the service name's policy for a given host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
service_name
The name of the service for which to retrieve the policy. Supported service names are:
- DCUI
- TSM
- SSH
- lbtd
- lsassd
- lwiod
- netlogond
- ntpd
- sfcbd-watchdog
- snmpd
- vprobed
- vpxa
- xorg
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to get service policy information.
If host_names is not provided, the service policy information will be retrieved
for the ``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_service_policy my.esxi.host root bad-password 'ssh'
# Used for connecting to a vCenter Server
salt '*' vsphere.get_service_policy my.vcenter.location root bad-password 'ntpd' \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
valid_services = ['DCUI', 'TSM', 'SSH', 'ssh', 'lbtd', 'lsassd', 'lwiod', 'netlogond',
'ntpd', 'sfcbd-watchdog', 'snmpd', 'vprobed', 'vpxa', 'xorg']
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
# Check if the service_name provided is a valid one.
# If we don't have a valid service, return. The service will be invalid for all hosts.
if service_name not in valid_services:
ret.update({host_name: {'Error': '{0} is not a valid service name.'.format(service_name)}})
return ret
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
services = host_ref.configManager.serviceSystem.serviceInfo.service
# Don't require users to know that VMware lists the ssh service as TSM-SSH
if service_name == 'SSH' or service_name == 'ssh':
temp_service_name = 'TSM-SSH'
else:
temp_service_name = service_name
# Loop through services until we find a matching name
for service in services:
if service.key == temp_service_name:
ret.update({host_name:
{service_name: service.policy}})
# We've found a match - break out of the loop so we don't overwrite the
# Updated host_name value with an error message.
break
else:
msg = 'Could not find service \'{0}\' for host \'{1}\'.'.format(service_name,
host_name)
ret.update({host_name: {'Error': msg}})
# If we made it this far, something else has gone wrong.
if ret.get(host_name) is None:
msg = '\'vsphere.get_service_policy\' failed for host {0}.'.format(host_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
return ret | [
"def",
"get_service_policy",
"(",
"host",
",",
"username",
",",
"password",
",",
"service_name",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",... | Get the service name's policy for a given host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
service_name
The name of the service for which to retrieve the policy. Supported service names are:
- DCUI
- TSM
- SSH
- lbtd
- lsassd
- lwiod
- netlogond
- ntpd
- sfcbd-watchdog
- snmpd
- vprobed
- vpxa
- xorg
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to get service policy information.
If host_names is not provided, the service policy information will be retrieved
for the ``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_service_policy my.esxi.host root bad-password 'ssh'
# Used for connecting to a vCenter Server
salt '*' vsphere.get_service_policy my.vcenter.location root bad-password 'ntpd' \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Get",
"the",
"service",
"name",
"s",
"policy",
"for",
"a",
"given",
"host",
"or",
"list",
"of",
"hosts",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1534-L1636 | train |
saltstack/salt | salt/modules/vsphere.py | get_vmotion_enabled | def get_vmotion_enabled(host, username, password, protocol=None, port=None, host_names=None):
'''
Get the VMotion enabled status for a given host or a list of host_names. Returns ``True``
if VMotion is enabled, ``False`` if it is not enabled.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts to check if VMotion is enabled.
If host_names is not provided, the VMotion status will be retrieved for the
``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_vmotion_enabled my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_vmotion_enabled my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
vmotion_vnic = host_ref.configManager.vmotionSystem.netConfig.selectedVnic
if vmotion_vnic:
ret.update({host_name: {'VMotion Enabled': True}})
else:
ret.update({host_name: {'VMotion Enabled': False}})
return ret | python | def get_vmotion_enabled(host, username, password, protocol=None, port=None, host_names=None):
'''
Get the VMotion enabled status for a given host or a list of host_names. Returns ``True``
if VMotion is enabled, ``False`` if it is not enabled.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts to check if VMotion is enabled.
If host_names is not provided, the VMotion status will be retrieved for the
``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_vmotion_enabled my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_vmotion_enabled my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
vmotion_vnic = host_ref.configManager.vmotionSystem.netConfig.selectedVnic
if vmotion_vnic:
ret.update({host_name: {'VMotion Enabled': True}})
else:
ret.update({host_name: {'VMotion Enabled': False}})
return ret | [
"def",
"get_vmotion_enabled",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_i... | Get the VMotion enabled status for a given host or a list of host_names. Returns ``True``
if VMotion is enabled, ``False`` if it is not enabled.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts to check if VMotion is enabled.
If host_names is not provided, the VMotion status will be retrieved for the
``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_vmotion_enabled my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_vmotion_enabled my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Get",
"the",
"VMotion",
"enabled",
"status",
"for",
"a",
"given",
"host",
"or",
"a",
"list",
"of",
"host_names",
".",
"Returns",
"True",
"if",
"VMotion",
"is",
"enabled",
"False",
"if",
"it",
"is",
"not",
"enabled",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1748-L1805 | train |
saltstack/salt | salt/modules/vsphere.py | get_vsan_enabled | def get_vsan_enabled(host, username, password, protocol=None, port=None, host_names=None):
'''
Get the VSAN enabled status for a given host or a list of host_names. Returns ``True``
if VSAN is enabled, ``False`` if it is not enabled, and ``None`` if a VSAN Host Config
is unset, per host.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts to check if VSAN enabled.
If host_names is not provided, the VSAN status will be retrieved for the
``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_vsan_enabled my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_vsan_enabled my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
vsan_config = host_ref.config.vsanHostConfig
# We must have a VSAN Config in place get information about VSAN state.
if vsan_config is None:
msg = 'VSAN System Config Manager is unset for host \'{0}\'.'.format(host_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
else:
ret.update({host_name: {'VSAN Enabled': vsan_config.enabled}})
return ret | python | def get_vsan_enabled(host, username, password, protocol=None, port=None, host_names=None):
'''
Get the VSAN enabled status for a given host or a list of host_names. Returns ``True``
if VSAN is enabled, ``False`` if it is not enabled, and ``None`` if a VSAN Host Config
is unset, per host.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts to check if VSAN enabled.
If host_names is not provided, the VSAN status will be retrieved for the
``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_vsan_enabled my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_vsan_enabled my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
vsan_config = host_ref.config.vsanHostConfig
# We must have a VSAN Config in place get information about VSAN state.
if vsan_config is None:
msg = 'VSAN System Config Manager is unset for host \'{0}\'.'.format(host_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
else:
ret.update({host_name: {'VSAN Enabled': vsan_config.enabled}})
return ret | [
"def",
"get_vsan_enabled",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_inst... | Get the VSAN enabled status for a given host or a list of host_names. Returns ``True``
if VSAN is enabled, ``False`` if it is not enabled, and ``None`` if a VSAN Host Config
is unset, per host.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts to check if VSAN enabled.
If host_names is not provided, the VSAN status will be retrieved for the
``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_vsan_enabled my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_vsan_enabled my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Get",
"the",
"VSAN",
"enabled",
"status",
"for",
"a",
"given",
"host",
"or",
"a",
"list",
"of",
"host_names",
".",
"Returns",
"True",
"if",
"VSAN",
"is",
"enabled",
"False",
"if",
"it",
"is",
"not",
"enabled",
"and",
"None",
"if",
"a",
"VSAN",
"Host",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1810-L1872 | train |
saltstack/salt | salt/modules/vsphere.py | get_vsan_eligible_disks | def get_vsan_eligible_disks(host, username, password, protocol=None, port=None, host_names=None):
'''
Returns a list of VSAN-eligible disks for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts to check if any VSAN-eligible disks are available.
If host_names is not provided, the VSAN-eligible disks will be retrieved
for the ``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_vsan_eligible_disks my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_vsan_eligible_disks my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
response = _get_vsan_eligible_disks(service_instance, host, host_names)
ret = {}
for host_name, value in six.iteritems(response):
error = value.get('Error')
if error:
ret.update({host_name: {'Error': error}})
continue
disks = value.get('Eligible')
# If we have eligible disks, it will be a list of disk objects
if disks and isinstance(disks, list):
disk_names = []
# We need to return ONLY the disk names, otherwise
# MessagePack can't deserialize the disk objects.
for disk in disks:
disk_names.append(disk.canonicalName)
ret.update({host_name: {'Eligible': disk_names}})
else:
# If we have disks, but it's not a list, it's actually a
# string message that we're passing along.
ret.update({host_name: {'Eligible': disks}})
return ret | python | def get_vsan_eligible_disks(host, username, password, protocol=None, port=None, host_names=None):
'''
Returns a list of VSAN-eligible disks for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts to check if any VSAN-eligible disks are available.
If host_names is not provided, the VSAN-eligible disks will be retrieved
for the ``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_vsan_eligible_disks my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_vsan_eligible_disks my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
response = _get_vsan_eligible_disks(service_instance, host, host_names)
ret = {}
for host_name, value in six.iteritems(response):
error = value.get('Error')
if error:
ret.update({host_name: {'Error': error}})
continue
disks = value.get('Eligible')
# If we have eligible disks, it will be a list of disk objects
if disks and isinstance(disks, list):
disk_names = []
# We need to return ONLY the disk names, otherwise
# MessagePack can't deserialize the disk objects.
for disk in disks:
disk_names.append(disk.canonicalName)
ret.update({host_name: {'Eligible': disk_names}})
else:
# If we have disks, but it's not a list, it's actually a
# string message that we're passing along.
ret.update({host_name: {'Eligible': disks}})
return ret | [
"def",
"get_vsan_eligible_disks",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_servi... | Returns a list of VSAN-eligible disks for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts to check if any VSAN-eligible disks are available.
If host_names is not provided, the VSAN-eligible disks will be retrieved
for the ``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.get_vsan_eligible_disks my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.get_vsan_eligible_disks my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Returns",
"a",
"list",
"of",
"VSAN",
"-",
"eligible",
"disks",
"for",
"a",
"given",
"host",
"or",
"list",
"of",
"host_names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1877-L1947 | train |
saltstack/salt | salt/modules/vsphere.py | system_info | def system_info(host, username, password, protocol=None, port=None):
'''
Return system information about a VMware environment.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
CLI Example:
.. code-block:: bash
salt '*' vsphere.system_info 1.2.3.4 root bad-password
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
ret = salt.utils.vmware.get_inventory(service_instance).about.__dict__
if 'apiType' in ret:
if ret['apiType'] == 'HostAgent':
ret = dictupdate.update(ret, salt.utils.vmware.get_hardware_grains(service_instance))
return ret | python | def system_info(host, username, password, protocol=None, port=None):
'''
Return system information about a VMware environment.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
CLI Example:
.. code-block:: bash
salt '*' vsphere.system_info 1.2.3.4 root bad-password
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
ret = salt.utils.vmware.get_inventory(service_instance).about.__dict__
if 'apiType' in ret:
if ret['apiType'] == 'HostAgent':
ret = dictupdate.update(ret, salt.utils.vmware.get_hardware_grains(service_instance))
return ret | [
"def",
"system_info",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_instance",
"(",
"host",
"=",
"host",
",... | Return system information about a VMware environment.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
CLI Example:
.. code-block:: bash
salt '*' vsphere.system_info 1.2.3.4 root bad-password | [
"Return",
"system",
"information",
"about",
"a",
"VMware",
"environment",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L1973-L2009 | train |
saltstack/salt | salt/modules/vsphere.py | list_datacenters | def list_datacenters(host, username, password, protocol=None, port=None):
'''
Returns a list of datacenters for the the specified host.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
CLI Example:
.. code-block:: bash
salt '*' vsphere.list_datacenters 1.2.3.4 root bad-password
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
return salt.utils.vmware.list_datacenters(service_instance) | python | def list_datacenters(host, username, password, protocol=None, port=None):
'''
Returns a list of datacenters for the the specified host.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
CLI Example:
.. code-block:: bash
salt '*' vsphere.list_datacenters 1.2.3.4 root bad-password
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
return salt.utils.vmware.list_datacenters(service_instance) | [
"def",
"list_datacenters",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_instance",
"(",
"host",
"=",
"host",... | Returns a list of datacenters for the the specified host.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
CLI Example:
.. code-block:: bash
salt '*' vsphere.list_datacenters 1.2.3.4 root bad-password | [
"Returns",
"a",
"list",
"of",
"datacenters",
"for",
"the",
"the",
"specified",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L2014-L2047 | train |
saltstack/salt | salt/modules/vsphere.py | list_ssds | def list_ssds(host, username, password, protocol=None, port=None, host_names=None):
'''
Returns a list of SSDs for the given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter the hosts for which to retrieve SSDs.
If host_names is not provided, SSDs will be retrieved for the
``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.list_ssds my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.list_ssds my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
names = []
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
disks = _get_host_ssds(host_ref)
for disk in disks:
names.append(disk.canonicalName)
ret.update({host_name: names})
return ret | python | def list_ssds(host, username, password, protocol=None, port=None, host_names=None):
'''
Returns a list of SSDs for the given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter the hosts for which to retrieve SSDs.
If host_names is not provided, SSDs will be retrieved for the
``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.list_ssds my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.list_ssds my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
names = []
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
disks = _get_host_ssds(host_ref)
for disk in disks:
names.append(disk.canonicalName)
ret.update({host_name: names})
return ret | [
"def",
"list_ssds",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_instance",
... | Returns a list of SSDs for the given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter the hosts for which to retrieve SSDs.
If host_names is not provided, SSDs will be retrieved for the
``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.list_ssds my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.list_ssds my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Returns",
"a",
"list",
"of",
"SSDs",
"for",
"the",
"given",
"host",
"or",
"list",
"of",
"host_names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L2424-L2480 | train |
saltstack/salt | salt/modules/vsphere.py | set_ntp_config | def set_ntp_config(host, username, password, ntp_servers, protocol=None, port=None, host_names=None):
'''
Set NTP configuration for a given host of list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
ntp_servers
A list of servers that should be added to and configured for the specified
host's NTP configuration.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter which hosts to configure ntp servers.
If host_names is not provided, the NTP servers will be configured for the
``host`` location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.ntp_configure my.esxi.host root bad-password '[192.174.1.100, 192.174.1.200]'
# Used for connecting to a vCenter Server
salt '*' vsphere.ntp_configure my.vcenter.location root bad-password '[192.174.1.100, 192.174.1.200]' \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
if not isinstance(ntp_servers, list):
raise CommandExecutionError('\'ntp_servers\' must be a list.')
# Get NTP Config Object from ntp_servers
ntp_config = vim.HostNtpConfig(server=ntp_servers)
# Get DateTimeConfig object from ntp_config
date_config = vim.HostDateTimeConfig(ntpConfig=ntp_config)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
date_time_manager = _get_date_time_mgr(host_ref)
log.debug('Configuring NTP Servers \'%s\' for host \'%s\'.', ntp_servers, host_name)
try:
date_time_manager.UpdateDateTimeConfig(config=date_config)
except vim.fault.HostConfigFault as err:
msg = 'vsphere.ntp_configure_servers failed: {0}'.format(err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
ret.update({host_name: {'NTP Servers': ntp_config}})
return ret | python | def set_ntp_config(host, username, password, ntp_servers, protocol=None, port=None, host_names=None):
'''
Set NTP configuration for a given host of list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
ntp_servers
A list of servers that should be added to and configured for the specified
host's NTP configuration.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter which hosts to configure ntp servers.
If host_names is not provided, the NTP servers will be configured for the
``host`` location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.ntp_configure my.esxi.host root bad-password '[192.174.1.100, 192.174.1.200]'
# Used for connecting to a vCenter Server
salt '*' vsphere.ntp_configure my.vcenter.location root bad-password '[192.174.1.100, 192.174.1.200]' \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
if not isinstance(ntp_servers, list):
raise CommandExecutionError('\'ntp_servers\' must be a list.')
# Get NTP Config Object from ntp_servers
ntp_config = vim.HostNtpConfig(server=ntp_servers)
# Get DateTimeConfig object from ntp_config
date_config = vim.HostDateTimeConfig(ntpConfig=ntp_config)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
date_time_manager = _get_date_time_mgr(host_ref)
log.debug('Configuring NTP Servers \'%s\' for host \'%s\'.', ntp_servers, host_name)
try:
date_time_manager.UpdateDateTimeConfig(config=date_config)
except vim.fault.HostConfigFault as err:
msg = 'vsphere.ntp_configure_servers failed: {0}'.format(err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
ret.update({host_name: {'NTP Servers': ntp_config}})
return ret | [
"def",
"set_ntp_config",
"(",
"host",
",",
"username",
",",
"password",
",",
"ntp_servers",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".... | Set NTP configuration for a given host of list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
ntp_servers
A list of servers that should be added to and configured for the specified
host's NTP configuration.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter which hosts to configure ntp servers.
If host_names is not provided, the NTP servers will be configured for the
``host`` location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.ntp_configure my.esxi.host root bad-password '[192.174.1.100, 192.174.1.200]'
# Used for connecting to a vCenter Server
salt '*' vsphere.ntp_configure my.vcenter.location root bad-password '[192.174.1.100, 192.174.1.200]' \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Set",
"NTP",
"configuration",
"for",
"a",
"given",
"host",
"of",
"list",
"of",
"host_names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L2553-L2628 | train |
saltstack/salt | salt/modules/vsphere.py | service_start | def service_start(host,
username,
password,
service_name,
protocol=None,
port=None,
host_names=None):
'''
Start the named service for the given host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
service_name
The name of the service for which to set the policy. Supported service names are:
- DCUI
- TSM
- SSH
- lbtd
- lsassd
- lwiod
- netlogond
- ntpd
- sfcbd-watchdog
- snmpd
- vprobed
- vpxa
- xorg
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to start the service.
If host_names is not provided, the service will be started for the ``host``
location instead. This is useful for when service instance connection information
is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.service_start my.esxi.host root bad-password 'ntpd'
# Used for connecting to a vCenter Server
salt '*' vsphere.service_start my.vcenter.location root bad-password 'ntpd' \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
valid_services = ['DCUI', 'TSM', 'SSH', 'ssh', 'lbtd', 'lsassd', 'lwiod', 'netlogond',
'ntpd', 'sfcbd-watchdog', 'snmpd', 'vprobed', 'vpxa', 'xorg']
ret = {}
# Don't require users to know that VMware lists the ssh service as TSM-SSH
if service_name == 'SSH' or service_name == 'ssh':
temp_service_name = 'TSM-SSH'
else:
temp_service_name = service_name
for host_name in host_names:
# Check if the service_name provided is a valid one.
# If we don't have a valid service, return. The service will be invalid for all hosts.
if service_name not in valid_services:
ret.update({host_name: {'Error': '{0} is not a valid service name.'.format(service_name)}})
return ret
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
service_manager = _get_service_manager(host_ref)
log.debug('Starting the \'%s\' service on %s.', service_name, host_name)
# Start the service
try:
service_manager.StartService(id=temp_service_name)
except vim.fault.HostConfigFault as err:
msg = '\'vsphere.service_start\' failed for host {0}: {1}'.format(host_name, err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
# Some services are restricted by the vSphere License Level.
except vim.fault.RestrictedVersion as err:
log.debug(err)
ret.update({host_name: {'Error': err}})
continue
ret.update({host_name: {'Service Started': True}})
return ret | python | def service_start(host,
username,
password,
service_name,
protocol=None,
port=None,
host_names=None):
'''
Start the named service for the given host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
service_name
The name of the service for which to set the policy. Supported service names are:
- DCUI
- TSM
- SSH
- lbtd
- lsassd
- lwiod
- netlogond
- ntpd
- sfcbd-watchdog
- snmpd
- vprobed
- vpxa
- xorg
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to start the service.
If host_names is not provided, the service will be started for the ``host``
location instead. This is useful for when service instance connection information
is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.service_start my.esxi.host root bad-password 'ntpd'
# Used for connecting to a vCenter Server
salt '*' vsphere.service_start my.vcenter.location root bad-password 'ntpd' \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
valid_services = ['DCUI', 'TSM', 'SSH', 'ssh', 'lbtd', 'lsassd', 'lwiod', 'netlogond',
'ntpd', 'sfcbd-watchdog', 'snmpd', 'vprobed', 'vpxa', 'xorg']
ret = {}
# Don't require users to know that VMware lists the ssh service as TSM-SSH
if service_name == 'SSH' or service_name == 'ssh':
temp_service_name = 'TSM-SSH'
else:
temp_service_name = service_name
for host_name in host_names:
# Check if the service_name provided is a valid one.
# If we don't have a valid service, return. The service will be invalid for all hosts.
if service_name not in valid_services:
ret.update({host_name: {'Error': '{0} is not a valid service name.'.format(service_name)}})
return ret
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
service_manager = _get_service_manager(host_ref)
log.debug('Starting the \'%s\' service on %s.', service_name, host_name)
# Start the service
try:
service_manager.StartService(id=temp_service_name)
except vim.fault.HostConfigFault as err:
msg = '\'vsphere.service_start\' failed for host {0}: {1}'.format(host_name, err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
# Some services are restricted by the vSphere License Level.
except vim.fault.RestrictedVersion as err:
log.debug(err)
ret.update({host_name: {'Error': err}})
continue
ret.update({host_name: {'Service Started': True}})
return ret | [
"def",
"service_start",
"(",
"host",
",",
"username",
",",
"password",
",",
"service_name",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".... | Start the named service for the given host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
service_name
The name of the service for which to set the policy. Supported service names are:
- DCUI
- TSM
- SSH
- lbtd
- lsassd
- lwiod
- netlogond
- ntpd
- sfcbd-watchdog
- snmpd
- vprobed
- vpxa
- xorg
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to start the service.
If host_names is not provided, the service will be started for the ``host``
location instead. This is useful for when service instance connection information
is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.service_start my.esxi.host root bad-password 'ntpd'
# Used for connecting to a vCenter Server
salt '*' vsphere.service_start my.vcenter.location root bad-password 'ntpd' \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Start",
"the",
"named",
"service",
"for",
"the",
"given",
"host",
"or",
"list",
"of",
"hosts",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L2633-L2739 | train |
saltstack/salt | salt/modules/vsphere.py | set_service_policy | def set_service_policy(host,
username,
password,
service_name,
service_policy,
protocol=None,
port=None,
host_names=None):
'''
Set the service name's policy for a given host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
service_name
The name of the service for which to set the policy. Supported service names are:
- DCUI
- TSM
- SSH
- lbtd
- lsassd
- lwiod
- netlogond
- ntpd
- sfcbd-watchdog
- snmpd
- vprobed
- vpxa
- xorg
service_policy
The policy to set for the service. For example, 'automatic'.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to set the service policy.
If host_names is not provided, the service policy information will be retrieved
for the ``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.set_service_policy my.esxi.host root bad-password 'ntpd' 'automatic'
# Used for connecting to a vCenter Server
salt '*' vsphere.set_service_policy my.vcenter.location root bad-password 'ntpd' 'automatic' \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
valid_services = ['DCUI', 'TSM', 'SSH', 'ssh', 'lbtd', 'lsassd', 'lwiod', 'netlogond',
'ntpd', 'sfcbd-watchdog', 'snmpd', 'vprobed', 'vpxa', 'xorg']
ret = {}
for host_name in host_names:
# Check if the service_name provided is a valid one.
# If we don't have a valid service, return. The service will be invalid for all hosts.
if service_name not in valid_services:
ret.update({host_name: {'Error': '{0} is not a valid service name.'.format(service_name)}})
return ret
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
service_manager = _get_service_manager(host_ref)
services = host_ref.configManager.serviceSystem.serviceInfo.service
# Services are stored in a general list - we need loop through the list and find
# service key that matches our service name.
for service in services:
service_key = None
# Find the service key based on the given service_name
if service.key == service_name:
service_key = service.key
elif service_name == 'ssh' or service_name == 'SSH':
if service.key == 'TSM-SSH':
service_key = 'TSM-SSH'
# If we have a service_key, we've found a match. Update the policy.
if service_key:
try:
service_manager.UpdateServicePolicy(id=service_key, policy=service_policy)
except vim.fault.NotFound:
msg = 'The service name \'{0}\' was not found.'.format(service_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
# Some services are restricted by the vSphere License Level.
except vim.fault.HostConfigFault as err:
msg = '\'vsphere.set_service_policy\' failed for host {0}: {1}'.format(host_name, err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
ret.update({host_name: True})
# If we made it this far, something else has gone wrong.
if ret.get(host_name) is None:
msg = 'Could not find service \'{0}\' for host \'{1}\'.'.format(service_name, host_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
return ret | python | def set_service_policy(host,
username,
password,
service_name,
service_policy,
protocol=None,
port=None,
host_names=None):
'''
Set the service name's policy for a given host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
service_name
The name of the service for which to set the policy. Supported service names are:
- DCUI
- TSM
- SSH
- lbtd
- lsassd
- lwiod
- netlogond
- ntpd
- sfcbd-watchdog
- snmpd
- vprobed
- vpxa
- xorg
service_policy
The policy to set for the service. For example, 'automatic'.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to set the service policy.
If host_names is not provided, the service policy information will be retrieved
for the ``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.set_service_policy my.esxi.host root bad-password 'ntpd' 'automatic'
# Used for connecting to a vCenter Server
salt '*' vsphere.set_service_policy my.vcenter.location root bad-password 'ntpd' 'automatic' \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
valid_services = ['DCUI', 'TSM', 'SSH', 'ssh', 'lbtd', 'lsassd', 'lwiod', 'netlogond',
'ntpd', 'sfcbd-watchdog', 'snmpd', 'vprobed', 'vpxa', 'xorg']
ret = {}
for host_name in host_names:
# Check if the service_name provided is a valid one.
# If we don't have a valid service, return. The service will be invalid for all hosts.
if service_name not in valid_services:
ret.update({host_name: {'Error': '{0} is not a valid service name.'.format(service_name)}})
return ret
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
service_manager = _get_service_manager(host_ref)
services = host_ref.configManager.serviceSystem.serviceInfo.service
# Services are stored in a general list - we need loop through the list and find
# service key that matches our service name.
for service in services:
service_key = None
# Find the service key based on the given service_name
if service.key == service_name:
service_key = service.key
elif service_name == 'ssh' or service_name == 'SSH':
if service.key == 'TSM-SSH':
service_key = 'TSM-SSH'
# If we have a service_key, we've found a match. Update the policy.
if service_key:
try:
service_manager.UpdateServicePolicy(id=service_key, policy=service_policy)
except vim.fault.NotFound:
msg = 'The service name \'{0}\' was not found.'.format(service_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
# Some services are restricted by the vSphere License Level.
except vim.fault.HostConfigFault as err:
msg = '\'vsphere.set_service_policy\' failed for host {0}: {1}'.format(host_name, err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
ret.update({host_name: True})
# If we made it this far, something else has gone wrong.
if ret.get(host_name) is None:
msg = 'Could not find service \'{0}\' for host \'{1}\'.'.format(service_name, host_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
return ret | [
"def",
"set_service_policy",
"(",
"host",
",",
"username",
",",
"password",
",",
"service_name",
",",
"service_policy",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
... | Set the service name's policy for a given host or list of hosts.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
service_name
The name of the service for which to set the policy. Supported service names are:
- DCUI
- TSM
- SSH
- lbtd
- lsassd
- lwiod
- netlogond
- ntpd
- sfcbd-watchdog
- snmpd
- vprobed
- vpxa
- xorg
service_policy
The policy to set for the service. For example, 'automatic'.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to tell
vCenter the hosts for which to set the service policy.
If host_names is not provided, the service policy information will be retrieved
for the ``host`` location instead. This is useful for when service instance
connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.set_service_policy my.esxi.host root bad-password 'ntpd' 'automatic'
# Used for connecting to a vCenter Server
salt '*' vsphere.set_service_policy my.vcenter.location root bad-password 'ntpd' 'automatic' \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Set",
"the",
"service",
"name",
"s",
"policy",
"for",
"a",
"given",
"host",
"or",
"list",
"of",
"hosts",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L2966-L3090 | train |
saltstack/salt | salt/modules/vsphere.py | update_host_datetime | def update_host_datetime(host, username, password, protocol=None, port=None, host_names=None):
'''
Update the date/time on the given host or list of host_names. This function should be
used with caution since network delays and execution delays can result in time skews.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts should update their date/time.
If host_names is not provided, the date/time will be updated for the ``host``
location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.update_date_time my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.update_date_time my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
date_time_manager = _get_date_time_mgr(host_ref)
try:
date_time_manager.UpdateDateTime(datetime.datetime.utcnow())
except vim.fault.HostConfigFault as err:
msg = '\'vsphere.update_date_time\' failed for host {0}: {1}'.format(host_name, err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
ret.update({host_name: {'Datetime Updated': True}})
return ret | python | def update_host_datetime(host, username, password, protocol=None, port=None, host_names=None):
'''
Update the date/time on the given host or list of host_names. This function should be
used with caution since network delays and execution delays can result in time skews.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts should update their date/time.
If host_names is not provided, the date/time will be updated for the ``host``
location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.update_date_time my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.update_date_time my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
date_time_manager = _get_date_time_mgr(host_ref)
try:
date_time_manager.UpdateDateTime(datetime.datetime.utcnow())
except vim.fault.HostConfigFault as err:
msg = '\'vsphere.update_date_time\' failed for host {0}: {1}'.format(host_name, err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
ret.update({host_name: {'Datetime Updated': True}})
return ret | [
"def",
"update_host_datetime",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_... | Update the date/time on the given host or list of host_names. This function should be
used with caution since network delays and execution delays can result in time skews.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts should update their date/time.
If host_names is not provided, the date/time will be updated for the ``host``
location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.update_date_time my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.update_date_time my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Update",
"the",
"date",
"/",
"time",
"on",
"the",
"given",
"host",
"or",
"list",
"of",
"host_names",
".",
"This",
"function",
"should",
"be",
"used",
"with",
"caution",
"since",
"network",
"delays",
"and",
"execution",
"delays",
"can",
"result",
"in",
"ti... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3095-L3157 | train |
saltstack/salt | salt/modules/vsphere.py | update_host_password | def update_host_password(host, username, password, new_password, protocol=None, port=None):
'''
Update the password for a given host.
.. note:: Currently only works with connections to ESXi hosts. Does not work with vCenter servers.
host
The location of the ESXi host.
username
The username used to login to the ESXi host, such as ``root``.
password
The password used to login to the ESXi host.
new_password
The new password that will be updated for the provided username on the ESXi host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
CLI Example:
.. code-block:: bash
salt '*' vsphere.update_host_password my.esxi.host root original-bad-password new-bad-password
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
# Get LocalAccountManager object
account_manager = salt.utils.vmware.get_inventory(service_instance).accountManager
# Create user account specification object and assign id and password attributes
user_account = vim.host.LocalAccountManager.AccountSpecification()
user_account.id = username
user_account.password = new_password
# Update the password
try:
account_manager.UpdateUser(user_account)
except vmodl.fault.SystemError as err:
raise CommandExecutionError(err.msg)
except vim.fault.UserNotFound:
raise CommandExecutionError('\'vsphere.update_host_password\' failed for host {0}: '
'User was not found.'.format(host))
# If the username and password already exist, we don't need to do anything.
except vim.fault.AlreadyExists:
pass
return True | python | def update_host_password(host, username, password, new_password, protocol=None, port=None):
'''
Update the password for a given host.
.. note:: Currently only works with connections to ESXi hosts. Does not work with vCenter servers.
host
The location of the ESXi host.
username
The username used to login to the ESXi host, such as ``root``.
password
The password used to login to the ESXi host.
new_password
The new password that will be updated for the provided username on the ESXi host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
CLI Example:
.. code-block:: bash
salt '*' vsphere.update_host_password my.esxi.host root original-bad-password new-bad-password
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
# Get LocalAccountManager object
account_manager = salt.utils.vmware.get_inventory(service_instance).accountManager
# Create user account specification object and assign id and password attributes
user_account = vim.host.LocalAccountManager.AccountSpecification()
user_account.id = username
user_account.password = new_password
# Update the password
try:
account_manager.UpdateUser(user_account)
except vmodl.fault.SystemError as err:
raise CommandExecutionError(err.msg)
except vim.fault.UserNotFound:
raise CommandExecutionError('\'vsphere.update_host_password\' failed for host {0}: '
'User was not found.'.format(host))
# If the username and password already exist, we don't need to do anything.
except vim.fault.AlreadyExists:
pass
return True | [
"def",
"update_host_password",
"(",
"host",
",",
"username",
",",
"password",
",",
"new_password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_instance",
"(... | Update the password for a given host.
.. note:: Currently only works with connections to ESXi hosts. Does not work with vCenter servers.
host
The location of the ESXi host.
username
The username used to login to the ESXi host, such as ``root``.
password
The password used to login to the ESXi host.
new_password
The new password that will be updated for the provided username on the ESXi host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
CLI Example:
.. code-block:: bash
salt '*' vsphere.update_host_password my.esxi.host root original-bad-password new-bad-password | [
"Update",
"the",
"password",
"for",
"a",
"given",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3162-L3220 | train |
saltstack/salt | salt/modules/vsphere.py | vmotion_disable | def vmotion_disable(host, username, password, protocol=None, port=None, host_names=None):
'''
Disable vMotion for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts should disable VMotion.
If host_names is not provided, VMotion will be disabled for the ``host``
location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.vmotion_disable my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.vmotion_disable my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
vmotion_system = host_ref.configManager.vmotionSystem
# Disable VMotion for the host by removing the VNic selected to use for VMotion.
try:
vmotion_system.DeselectVnic()
except vim.fault.HostConfigFault as err:
msg = 'vsphere.vmotion_disable failed: {0}'.format(err)
log.debug(msg)
ret.update({host_name: {'Error': msg,
'VMotion Disabled': False}})
continue
ret.update({host_name: {'VMotion Disabled': True}})
return ret | python | def vmotion_disable(host, username, password, protocol=None, port=None, host_names=None):
'''
Disable vMotion for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts should disable VMotion.
If host_names is not provided, VMotion will be disabled for the ``host``
location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.vmotion_disable my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.vmotion_disable my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
vmotion_system = host_ref.configManager.vmotionSystem
# Disable VMotion for the host by removing the VNic selected to use for VMotion.
try:
vmotion_system.DeselectVnic()
except vim.fault.HostConfigFault as err:
msg = 'vsphere.vmotion_disable failed: {0}'.format(err)
log.debug(msg)
ret.update({host_name: {'Error': msg,
'VMotion Disabled': False}})
continue
ret.update({host_name: {'VMotion Disabled': True}})
return ret | [
"def",
"vmotion_disable",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_insta... | Disable vMotion for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts should disable VMotion.
If host_names is not provided, VMotion will be disabled for the ``host``
location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.vmotion_disable my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.vmotion_disable my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Disable",
"vMotion",
"for",
"a",
"given",
"host",
"or",
"list",
"of",
"host_names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3225-L3289 | train |
saltstack/salt | salt/modules/vsphere.py | vsan_add_disks | def vsan_add_disks(host, username, password, protocol=None, port=None, host_names=None):
'''
Add any VSAN-eligible disks to the VSAN System for the given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts need to add any VSAN-eligible disks to the host's
VSAN system.
If host_names is not provided, VSAN-eligible disks will be added to the hosts's
VSAN system for the ``host`` location instead. This is useful for when service
instance connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.vsan_add_disks my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.vsan_add_disks my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
response = _get_vsan_eligible_disks(service_instance, host, host_names)
ret = {}
for host_name, value in six.iteritems(response):
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
vsan_system = host_ref.configManager.vsanSystem
# We must have a VSAN Config in place before we can manipulate it.
if vsan_system is None:
msg = 'VSAN System Config Manager is unset for host \'{0}\'. ' \
'VSAN configuration cannot be changed without a configured ' \
'VSAN System.'.format(host_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
else:
eligible = value.get('Eligible')
error = value.get('Error')
if eligible and isinstance(eligible, list):
# If we have eligible, matching disks, add them to VSAN.
try:
task = vsan_system.AddDisks(eligible)
salt.utils.vmware.wait_for_task(task, host_name, 'Adding disks to VSAN', sleep_seconds=3)
except vim.fault.InsufficientDisks as err:
log.debug(err.msg)
ret.update({host_name: {'Error': err.msg}})
continue
except Exception as err:
msg = '\'vsphere.vsan_add_disks\' failed for host {0}: {1}'.format(host_name, err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
log.debug(
'Successfully added disks to the VSAN system for host \'%s\'.',
host_name
)
# We need to return ONLY the disk names, otherwise Message Pack can't deserialize the disk objects.
disk_names = []
for disk in eligible:
disk_names.append(disk.canonicalName)
ret.update({host_name: {'Disks Added': disk_names}})
elif eligible and isinstance(eligible, six.string_types):
# If we have a string type in the eligible value, we don't
# have any VSAN-eligible disks. Pull the message through.
ret.update({host_name: {'Disks Added': eligible}})
elif error:
# If we hit an error, populate the Error return dict for state functions.
ret.update({host_name: {'Error': error}})
else:
# If we made it this far, we somehow have eligible disks, but they didn't
# match the disk list and just got an empty list of matching disks.
ret.update({host_name: {'Disks Added': 'No new VSAN-eligible disks were found to add.'}})
return ret | python | def vsan_add_disks(host, username, password, protocol=None, port=None, host_names=None):
'''
Add any VSAN-eligible disks to the VSAN System for the given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts need to add any VSAN-eligible disks to the host's
VSAN system.
If host_names is not provided, VSAN-eligible disks will be added to the hosts's
VSAN system for the ``host`` location instead. This is useful for when service
instance connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.vsan_add_disks my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.vsan_add_disks my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
host_names = _check_hosts(service_instance, host, host_names)
response = _get_vsan_eligible_disks(service_instance, host, host_names)
ret = {}
for host_name, value in six.iteritems(response):
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
vsan_system = host_ref.configManager.vsanSystem
# We must have a VSAN Config in place before we can manipulate it.
if vsan_system is None:
msg = 'VSAN System Config Manager is unset for host \'{0}\'. ' \
'VSAN configuration cannot be changed without a configured ' \
'VSAN System.'.format(host_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
else:
eligible = value.get('Eligible')
error = value.get('Error')
if eligible and isinstance(eligible, list):
# If we have eligible, matching disks, add them to VSAN.
try:
task = vsan_system.AddDisks(eligible)
salt.utils.vmware.wait_for_task(task, host_name, 'Adding disks to VSAN', sleep_seconds=3)
except vim.fault.InsufficientDisks as err:
log.debug(err.msg)
ret.update({host_name: {'Error': err.msg}})
continue
except Exception as err:
msg = '\'vsphere.vsan_add_disks\' failed for host {0}: {1}'.format(host_name, err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
log.debug(
'Successfully added disks to the VSAN system for host \'%s\'.',
host_name
)
# We need to return ONLY the disk names, otherwise Message Pack can't deserialize the disk objects.
disk_names = []
for disk in eligible:
disk_names.append(disk.canonicalName)
ret.update({host_name: {'Disks Added': disk_names}})
elif eligible and isinstance(eligible, six.string_types):
# If we have a string type in the eligible value, we don't
# have any VSAN-eligible disks. Pull the message through.
ret.update({host_name: {'Disks Added': eligible}})
elif error:
# If we hit an error, populate the Error return dict for state functions.
ret.update({host_name: {'Error': error}})
else:
# If we made it this far, we somehow have eligible disks, but they didn't
# match the disk list and just got an empty list of matching disks.
ret.update({host_name: {'Disks Added': 'No new VSAN-eligible disks were found to add.'}})
return ret | [
"def",
"vsan_add_disks",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_instan... | Add any VSAN-eligible disks to the VSAN System for the given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts need to add any VSAN-eligible disks to the host's
VSAN system.
If host_names is not provided, VSAN-eligible disks will be added to the hosts's
VSAN system for the ``host`` location instead. This is useful for when service
instance connection information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.vsan_add_disks my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.vsan_add_disks my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Add",
"any",
"VSAN",
"-",
"eligible",
"disks",
"to",
"the",
"VSAN",
"System",
"for",
"the",
"given",
"host",
"or",
"list",
"of",
"host_names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3367-L3469 | train |
saltstack/salt | salt/modules/vsphere.py | vsan_disable | def vsan_disable(host, username, password, protocol=None, port=None, host_names=None):
'''
Disable VSAN for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts should disable VSAN.
If host_names is not provided, VSAN will be disabled for the ``host``
location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.vsan_disable my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.vsan_disable my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
# Create a VSAN Configuration Object and set the enabled attribute to True
vsan_config = vim.vsan.host.ConfigInfo()
vsan_config.enabled = False
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
vsan_system = host_ref.configManager.vsanSystem
# We must have a VSAN Config in place before we can manipulate it.
if vsan_system is None:
msg = 'VSAN System Config Manager is unset for host \'{0}\'. ' \
'VSAN configuration cannot be changed without a configured ' \
'VSAN System.'.format(host_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
else:
try:
# Disable vsan on the host
task = vsan_system.UpdateVsan_Task(vsan_config)
salt.utils.vmware.wait_for_task(task, host_name, 'Disabling VSAN', sleep_seconds=3)
except vmodl.fault.SystemError as err:
log.debug(err.msg)
ret.update({host_name: {'Error': err.msg}})
continue
except Exception as err:
msg = '\'vsphere.vsan_disable\' failed for host {0}: {1}'.format(host_name, err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
ret.update({host_name: {'VSAN Disabled': True}})
return ret | python | def vsan_disable(host, username, password, protocol=None, port=None, host_names=None):
'''
Disable VSAN for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts should disable VSAN.
If host_names is not provided, VSAN will be disabled for the ``host``
location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.vsan_disable my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.vsan_disable my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]'
'''
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
# Create a VSAN Configuration Object and set the enabled attribute to True
vsan_config = vim.vsan.host.ConfigInfo()
vsan_config.enabled = False
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
vsan_system = host_ref.configManager.vsanSystem
# We must have a VSAN Config in place before we can manipulate it.
if vsan_system is None:
msg = 'VSAN System Config Manager is unset for host \'{0}\'. ' \
'VSAN configuration cannot be changed without a configured ' \
'VSAN System.'.format(host_name)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
else:
try:
# Disable vsan on the host
task = vsan_system.UpdateVsan_Task(vsan_config)
salt.utils.vmware.wait_for_task(task, host_name, 'Disabling VSAN', sleep_seconds=3)
except vmodl.fault.SystemError as err:
log.debug(err.msg)
ret.update({host_name: {'Error': err.msg}})
continue
except Exception as err:
msg = '\'vsphere.vsan_disable\' failed for host {0}: {1}'.format(host_name, err)
log.debug(msg)
ret.update({host_name: {'Error': msg}})
continue
ret.update({host_name: {'VSAN Disabled': True}})
return ret | [
"def",
"vsan_disable",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_instance... | Disable VSAN for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
protocol. Default protocol is ``https``.
port
Optionally set to alternate port if the host is not using the default
port. Default port is ``443``.
host_names
List of ESXi host names. When the host, username, and password credentials
are provided for a vCenter Server, the host_names argument is required to
tell vCenter which hosts should disable VSAN.
If host_names is not provided, VSAN will be disabled for the ``host``
location instead. This is useful for when service instance connection
information is used for a single ESXi host.
CLI Example:
.. code-block:: bash
# Used for single ESXi host connection information
salt '*' vsphere.vsan_disable my.esxi.host root bad-password
# Used for connecting to a vCenter Server
salt '*' vsphere.vsan_disable my.vcenter.location root bad-password \
host_names='[esxi-1.host.com, esxi-2.host.com]' | [
"Disable",
"VSAN",
"for",
"a",
"given",
"host",
"or",
"list",
"of",
"host_names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3474-L3554 | train |
saltstack/salt | salt/modules/vsphere.py | _get_dvs_config_dict | def _get_dvs_config_dict(dvs_name, dvs_config):
'''
Returns the dict representation of the DVS config
dvs_name
The name of the DVS
dvs_config
The DVS config
'''
log.trace('Building the dict of the DVS \'%s\' config', dvs_name)
conf_dict = {'name': dvs_name,
'contact_email': dvs_config.contact.contact,
'contact_name': dvs_config.contact.name,
'description': dvs_config.description,
'lacp_api_version': dvs_config.lacpApiVersion,
'network_resource_control_version':
dvs_config.networkResourceControlVersion,
'network_resource_management_enabled':
dvs_config.networkResourceManagementEnabled,
'max_mtu': dvs_config.maxMtu}
if isinstance(dvs_config.uplinkPortPolicy,
vim.DVSNameArrayUplinkPortPolicy):
conf_dict.update(
{'uplink_names': dvs_config.uplinkPortPolicy.uplinkPortName})
return conf_dict | python | def _get_dvs_config_dict(dvs_name, dvs_config):
'''
Returns the dict representation of the DVS config
dvs_name
The name of the DVS
dvs_config
The DVS config
'''
log.trace('Building the dict of the DVS \'%s\' config', dvs_name)
conf_dict = {'name': dvs_name,
'contact_email': dvs_config.contact.contact,
'contact_name': dvs_config.contact.name,
'description': dvs_config.description,
'lacp_api_version': dvs_config.lacpApiVersion,
'network_resource_control_version':
dvs_config.networkResourceControlVersion,
'network_resource_management_enabled':
dvs_config.networkResourceManagementEnabled,
'max_mtu': dvs_config.maxMtu}
if isinstance(dvs_config.uplinkPortPolicy,
vim.DVSNameArrayUplinkPortPolicy):
conf_dict.update(
{'uplink_names': dvs_config.uplinkPortPolicy.uplinkPortName})
return conf_dict | [
"def",
"_get_dvs_config_dict",
"(",
"dvs_name",
",",
"dvs_config",
")",
":",
"log",
".",
"trace",
"(",
"'Building the dict of the DVS \\'%s\\' config'",
",",
"dvs_name",
")",
"conf_dict",
"=",
"{",
"'name'",
":",
"dvs_name",
",",
"'contact_email'",
":",
"dvs_config"... | Returns the dict representation of the DVS config
dvs_name
The name of the DVS
dvs_config
The DVS config | [
"Returns",
"the",
"dict",
"representation",
"of",
"the",
"DVS",
"config"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3642-L3667 | train |
saltstack/salt | salt/modules/vsphere.py | _get_dvs_link_discovery_protocol | def _get_dvs_link_discovery_protocol(dvs_name, dvs_link_disc_protocol):
'''
Returns the dict representation of the DVS link discovery protocol
dvs_name
The name of the DVS
dvs_link_disc_protocl
The DVS link discovery protocol
'''
log.trace('Building the dict of the DVS \'%s\' link discovery protocol', dvs_name)
return {'operation': dvs_link_disc_protocol.operation,
'protocol': dvs_link_disc_protocol.protocol} | python | def _get_dvs_link_discovery_protocol(dvs_name, dvs_link_disc_protocol):
'''
Returns the dict representation of the DVS link discovery protocol
dvs_name
The name of the DVS
dvs_link_disc_protocl
The DVS link discovery protocol
'''
log.trace('Building the dict of the DVS \'%s\' link discovery protocol', dvs_name)
return {'operation': dvs_link_disc_protocol.operation,
'protocol': dvs_link_disc_protocol.protocol} | [
"def",
"_get_dvs_link_discovery_protocol",
"(",
"dvs_name",
",",
"dvs_link_disc_protocol",
")",
":",
"log",
".",
"trace",
"(",
"'Building the dict of the DVS \\'%s\\' link discovery protocol'",
",",
"dvs_name",
")",
"return",
"{",
"'operation'",
":",
"dvs_link_disc_protocol",... | Returns the dict representation of the DVS link discovery protocol
dvs_name
The name of the DVS
dvs_link_disc_protocl
The DVS link discovery protocol | [
"Returns",
"the",
"dict",
"representation",
"of",
"the",
"DVS",
"link",
"discovery",
"protocol"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3670-L3682 | train |
saltstack/salt | salt/modules/vsphere.py | _get_dvs_product_info | def _get_dvs_product_info(dvs_name, dvs_product_info):
'''
Returns the dict representation of the DVS product_info
dvs_name
The name of the DVS
dvs_product_info
The DVS product info
'''
log.trace('Building the dict of the DVS \'%s\' product info', dvs_name)
return {'name': dvs_product_info.name,
'vendor': dvs_product_info.vendor,
'version': dvs_product_info.version} | python | def _get_dvs_product_info(dvs_name, dvs_product_info):
'''
Returns the dict representation of the DVS product_info
dvs_name
The name of the DVS
dvs_product_info
The DVS product info
'''
log.trace('Building the dict of the DVS \'%s\' product info', dvs_name)
return {'name': dvs_product_info.name,
'vendor': dvs_product_info.vendor,
'version': dvs_product_info.version} | [
"def",
"_get_dvs_product_info",
"(",
"dvs_name",
",",
"dvs_product_info",
")",
":",
"log",
".",
"trace",
"(",
"'Building the dict of the DVS \\'%s\\' product info'",
",",
"dvs_name",
")",
"return",
"{",
"'name'",
":",
"dvs_product_info",
".",
"name",
",",
"'vendor'",
... | Returns the dict representation of the DVS product_info
dvs_name
The name of the DVS
dvs_product_info
The DVS product info | [
"Returns",
"the",
"dict",
"representation",
"of",
"the",
"DVS",
"product_info"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3685-L3698 | train |
saltstack/salt | salt/modules/vsphere.py | _get_dvs_capability | def _get_dvs_capability(dvs_name, dvs_capability):
'''
Returns the dict representation of the DVS product_info
dvs_name
The name of the DVS
dvs_capability
The DVS capability
'''
log.trace('Building the dict of the DVS \'%s\' capability', dvs_name)
return {'operation_supported': dvs_capability.dvsOperationSupported,
'portgroup_operation_supported':
dvs_capability.dvPortGroupOperationSupported,
'port_operation_supported': dvs_capability.dvPortOperationSupported} | python | def _get_dvs_capability(dvs_name, dvs_capability):
'''
Returns the dict representation of the DVS product_info
dvs_name
The name of the DVS
dvs_capability
The DVS capability
'''
log.trace('Building the dict of the DVS \'%s\' capability', dvs_name)
return {'operation_supported': dvs_capability.dvsOperationSupported,
'portgroup_operation_supported':
dvs_capability.dvPortGroupOperationSupported,
'port_operation_supported': dvs_capability.dvPortOperationSupported} | [
"def",
"_get_dvs_capability",
"(",
"dvs_name",
",",
"dvs_capability",
")",
":",
"log",
".",
"trace",
"(",
"'Building the dict of the DVS \\'%s\\' capability'",
",",
"dvs_name",
")",
"return",
"{",
"'operation_supported'",
":",
"dvs_capability",
".",
"dvsOperationSupported... | Returns the dict representation of the DVS product_info
dvs_name
The name of the DVS
dvs_capability
The DVS capability | [
"Returns",
"the",
"dict",
"representation",
"of",
"the",
"DVS",
"product_info"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3701-L3715 | train |
saltstack/salt | salt/modules/vsphere.py | _get_dvs_infrastructure_traffic_resources | def _get_dvs_infrastructure_traffic_resources(dvs_name,
dvs_infra_traffic_ress):
'''
Returns a list of dict representations of the DVS infrastructure traffic
resource
dvs_name
The name of the DVS
dvs_infra_traffic_ress
The DVS infrastructure traffic resources
'''
log.trace('Building the dicts of the DVS \'%s\' infrastructure '
'traffic resources', dvs_name)
res_dicts = []
for res in dvs_infra_traffic_ress:
res_dict = {'key': res.key,
'limit': res.allocationInfo.limit,
'reservation': res.allocationInfo.reservation}
if res.allocationInfo.shares:
res_dict.update({'num_shares': res.allocationInfo.shares.shares,
'share_level': res.allocationInfo.shares.level})
res_dicts.append(res_dict)
return res_dicts | python | def _get_dvs_infrastructure_traffic_resources(dvs_name,
dvs_infra_traffic_ress):
'''
Returns a list of dict representations of the DVS infrastructure traffic
resource
dvs_name
The name of the DVS
dvs_infra_traffic_ress
The DVS infrastructure traffic resources
'''
log.trace('Building the dicts of the DVS \'%s\' infrastructure '
'traffic resources', dvs_name)
res_dicts = []
for res in dvs_infra_traffic_ress:
res_dict = {'key': res.key,
'limit': res.allocationInfo.limit,
'reservation': res.allocationInfo.reservation}
if res.allocationInfo.shares:
res_dict.update({'num_shares': res.allocationInfo.shares.shares,
'share_level': res.allocationInfo.shares.level})
res_dicts.append(res_dict)
return res_dicts | [
"def",
"_get_dvs_infrastructure_traffic_resources",
"(",
"dvs_name",
",",
"dvs_infra_traffic_ress",
")",
":",
"log",
".",
"trace",
"(",
"'Building the dicts of the DVS \\'%s\\' infrastructure '",
"'traffic resources'",
",",
"dvs_name",
")",
"res_dicts",
"=",
"[",
"]",
"for"... | Returns a list of dict representations of the DVS infrastructure traffic
resource
dvs_name
The name of the DVS
dvs_infra_traffic_ress
The DVS infrastructure traffic resources | [
"Returns",
"a",
"list",
"of",
"dict",
"representations",
"of",
"the",
"DVS",
"infrastructure",
"traffic",
"resource"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3718-L3741 | train |
saltstack/salt | salt/modules/vsphere.py | list_dvss | def list_dvss(datacenter=None, dvs_names=None, service_instance=None):
'''
Returns a list of distributed virtual switches (DVSs).
The list can be filtered by the datacenter or DVS names.
datacenter
The datacenter to look for DVSs in.
Default value is None.
dvs_names
List of DVS names to look for. If None, all DVSs are returned.
Default value is None.
.. code-block:: bash
salt '*' vsphere.list_dvss
salt '*' vsphere.list_dvss dvs_names=[dvs1,dvs2]
'''
ret_list = []
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
for dvs in salt.utils.vmware.get_dvss(dc_ref, dvs_names, (not dvs_names)):
dvs_dict = {}
# XXX: Because of how VMware did DVS object inheritance we can\'t
# be more restrictive when retrieving the dvs config, we have to
# retrieve the entire object
props = salt.utils.vmware.get_properties_of_managed_object(
dvs, ['name', 'config', 'capability', 'networkResourcePool'])
dvs_dict = _get_dvs_config_dict(props['name'], props['config'])
# Product info
dvs_dict.update(
{'product_info':
_get_dvs_product_info(props['name'],
props['config'].productInfo)})
# Link Discovery Protocol
if props['config'].linkDiscoveryProtocolConfig:
dvs_dict.update(
{'link_discovery_protocol':
_get_dvs_link_discovery_protocol(
props['name'],
props['config'].linkDiscoveryProtocolConfig)})
# Capability
dvs_dict.update({'capability':
_get_dvs_capability(props['name'],
props['capability'])})
# InfrastructureTrafficResourceConfig - available with vSphere 6.0
if hasattr(props['config'], 'infrastructureTrafficResourceConfig'):
dvs_dict.update({
'infrastructure_traffic_resource_pools':
_get_dvs_infrastructure_traffic_resources(
props['name'],
props['config'].infrastructureTrafficResourceConfig)})
ret_list.append(dvs_dict)
return ret_list | python | def list_dvss(datacenter=None, dvs_names=None, service_instance=None):
'''
Returns a list of distributed virtual switches (DVSs).
The list can be filtered by the datacenter or DVS names.
datacenter
The datacenter to look for DVSs in.
Default value is None.
dvs_names
List of DVS names to look for. If None, all DVSs are returned.
Default value is None.
.. code-block:: bash
salt '*' vsphere.list_dvss
salt '*' vsphere.list_dvss dvs_names=[dvs1,dvs2]
'''
ret_list = []
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
for dvs in salt.utils.vmware.get_dvss(dc_ref, dvs_names, (not dvs_names)):
dvs_dict = {}
# XXX: Because of how VMware did DVS object inheritance we can\'t
# be more restrictive when retrieving the dvs config, we have to
# retrieve the entire object
props = salt.utils.vmware.get_properties_of_managed_object(
dvs, ['name', 'config', 'capability', 'networkResourcePool'])
dvs_dict = _get_dvs_config_dict(props['name'], props['config'])
# Product info
dvs_dict.update(
{'product_info':
_get_dvs_product_info(props['name'],
props['config'].productInfo)})
# Link Discovery Protocol
if props['config'].linkDiscoveryProtocolConfig:
dvs_dict.update(
{'link_discovery_protocol':
_get_dvs_link_discovery_protocol(
props['name'],
props['config'].linkDiscoveryProtocolConfig)})
# Capability
dvs_dict.update({'capability':
_get_dvs_capability(props['name'],
props['capability'])})
# InfrastructureTrafficResourceConfig - available with vSphere 6.0
if hasattr(props['config'], 'infrastructureTrafficResourceConfig'):
dvs_dict.update({
'infrastructure_traffic_resource_pools':
_get_dvs_infrastructure_traffic_resources(
props['name'],
props['config'].infrastructureTrafficResourceConfig)})
ret_list.append(dvs_dict)
return ret_list | [
"def",
"list_dvss",
"(",
"datacenter",
"=",
"None",
",",
"dvs_names",
"=",
"None",
",",
"service_instance",
"=",
"None",
")",
":",
"ret_list",
"=",
"[",
"]",
"proxy_type",
"=",
"get_proxy_type",
"(",
")",
"if",
"proxy_type",
"==",
"'esxdatacenter'",
":",
"... | Returns a list of distributed virtual switches (DVSs).
The list can be filtered by the datacenter or DVS names.
datacenter
The datacenter to look for DVSs in.
Default value is None.
dvs_names
List of DVS names to look for. If None, all DVSs are returned.
Default value is None.
.. code-block:: bash
salt '*' vsphere.list_dvss
salt '*' vsphere.list_dvss dvs_names=[dvs1,dvs2] | [
"Returns",
"a",
"list",
"of",
"distributed",
"virtual",
"switches",
"(",
"DVSs",
")",
".",
"The",
"list",
"can",
"be",
"filtered",
"by",
"the",
"datacenter",
"or",
"DVS",
"names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3747-L3807 | train |
saltstack/salt | salt/modules/vsphere.py | _apply_dvs_config | def _apply_dvs_config(config_spec, config_dict):
'''
Applies the values of the config dict dictionary to a config spec
(vim.VMwareDVSConfigSpec)
'''
if config_dict.get('name'):
config_spec.name = config_dict['name']
if config_dict.get('contact_email') or config_dict.get('contact_name'):
if not config_spec.contact:
config_spec.contact = vim.DVSContactInfo()
config_spec.contact.contact = config_dict.get('contact_email')
config_spec.contact.name = config_dict.get('contact_name')
if config_dict.get('description'):
config_spec.description = config_dict.get('description')
if config_dict.get('max_mtu'):
config_spec.maxMtu = config_dict.get('max_mtu')
if config_dict.get('lacp_api_version'):
config_spec.lacpApiVersion = config_dict.get('lacp_api_version')
if config_dict.get('network_resource_control_version'):
config_spec.networkResourceControlVersion = \
config_dict.get('network_resource_control_version')
if config_dict.get('uplink_names'):
if not config_spec.uplinkPortPolicy or \
not isinstance(config_spec.uplinkPortPolicy,
vim.DVSNameArrayUplinkPortPolicy):
config_spec.uplinkPortPolicy = \
vim.DVSNameArrayUplinkPortPolicy()
config_spec.uplinkPortPolicy.uplinkPortName = \
config_dict['uplink_names'] | python | def _apply_dvs_config(config_spec, config_dict):
'''
Applies the values of the config dict dictionary to a config spec
(vim.VMwareDVSConfigSpec)
'''
if config_dict.get('name'):
config_spec.name = config_dict['name']
if config_dict.get('contact_email') or config_dict.get('contact_name'):
if not config_spec.contact:
config_spec.contact = vim.DVSContactInfo()
config_spec.contact.contact = config_dict.get('contact_email')
config_spec.contact.name = config_dict.get('contact_name')
if config_dict.get('description'):
config_spec.description = config_dict.get('description')
if config_dict.get('max_mtu'):
config_spec.maxMtu = config_dict.get('max_mtu')
if config_dict.get('lacp_api_version'):
config_spec.lacpApiVersion = config_dict.get('lacp_api_version')
if config_dict.get('network_resource_control_version'):
config_spec.networkResourceControlVersion = \
config_dict.get('network_resource_control_version')
if config_dict.get('uplink_names'):
if not config_spec.uplinkPortPolicy or \
not isinstance(config_spec.uplinkPortPolicy,
vim.DVSNameArrayUplinkPortPolicy):
config_spec.uplinkPortPolicy = \
vim.DVSNameArrayUplinkPortPolicy()
config_spec.uplinkPortPolicy.uplinkPortName = \
config_dict['uplink_names'] | [
"def",
"_apply_dvs_config",
"(",
"config_spec",
",",
"config_dict",
")",
":",
"if",
"config_dict",
".",
"get",
"(",
"'name'",
")",
":",
"config_spec",
".",
"name",
"=",
"config_dict",
"[",
"'name'",
"]",
"if",
"config_dict",
".",
"get",
"(",
"'contact_email'... | Applies the values of the config dict dictionary to a config spec
(vim.VMwareDVSConfigSpec) | [
"Applies",
"the",
"values",
"of",
"the",
"config",
"dict",
"dictionary",
"to",
"a",
"config",
"spec",
"(",
"vim",
".",
"VMwareDVSConfigSpec",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3810-L3839 | train |
saltstack/salt | salt/modules/vsphere.py | _apply_dvs_product_info | def _apply_dvs_product_info(product_info_spec, product_info_dict):
'''
Applies the values of the product_info_dict dictionary to a product info
spec (vim.DistributedVirtualSwitchProductSpec)
'''
if product_info_dict.get('name'):
product_info_spec.name = product_info_dict['name']
if product_info_dict.get('vendor'):
product_info_spec.vendor = product_info_dict['vendor']
if product_info_dict.get('version'):
product_info_spec.version = product_info_dict['version'] | python | def _apply_dvs_product_info(product_info_spec, product_info_dict):
'''
Applies the values of the product_info_dict dictionary to a product info
spec (vim.DistributedVirtualSwitchProductSpec)
'''
if product_info_dict.get('name'):
product_info_spec.name = product_info_dict['name']
if product_info_dict.get('vendor'):
product_info_spec.vendor = product_info_dict['vendor']
if product_info_dict.get('version'):
product_info_spec.version = product_info_dict['version'] | [
"def",
"_apply_dvs_product_info",
"(",
"product_info_spec",
",",
"product_info_dict",
")",
":",
"if",
"product_info_dict",
".",
"get",
"(",
"'name'",
")",
":",
"product_info_spec",
".",
"name",
"=",
"product_info_dict",
"[",
"'name'",
"]",
"if",
"product_info_dict",... | Applies the values of the product_info_dict dictionary to a product info
spec (vim.DistributedVirtualSwitchProductSpec) | [
"Applies",
"the",
"values",
"of",
"the",
"product_info_dict",
"dictionary",
"to",
"a",
"product",
"info",
"spec",
"(",
"vim",
".",
"DistributedVirtualSwitchProductSpec",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3851-L3861 | train |
saltstack/salt | salt/modules/vsphere.py | _apply_dvs_capability | def _apply_dvs_capability(capability_spec, capability_dict):
'''
Applies the values of the capability_dict dictionary to a DVS capability
object (vim.vim.DVSCapability)
'''
if 'operation_supported' in capability_dict:
capability_spec.dvsOperationSupported = \
capability_dict['operation_supported']
if 'port_operation_supported' in capability_dict:
capability_spec.dvPortOperationSupported = \
capability_dict['port_operation_supported']
if 'portgroup_operation_supported' in capability_dict:
capability_spec.dvPortGroupOperationSupported = \
capability_dict['portgroup_operation_supported'] | python | def _apply_dvs_capability(capability_spec, capability_dict):
'''
Applies the values of the capability_dict dictionary to a DVS capability
object (vim.vim.DVSCapability)
'''
if 'operation_supported' in capability_dict:
capability_spec.dvsOperationSupported = \
capability_dict['operation_supported']
if 'port_operation_supported' in capability_dict:
capability_spec.dvPortOperationSupported = \
capability_dict['port_operation_supported']
if 'portgroup_operation_supported' in capability_dict:
capability_spec.dvPortGroupOperationSupported = \
capability_dict['portgroup_operation_supported'] | [
"def",
"_apply_dvs_capability",
"(",
"capability_spec",
",",
"capability_dict",
")",
":",
"if",
"'operation_supported'",
"in",
"capability_dict",
":",
"capability_spec",
".",
"dvsOperationSupported",
"=",
"capability_dict",
"[",
"'operation_supported'",
"]",
"if",
"'port_... | Applies the values of the capability_dict dictionary to a DVS capability
object (vim.vim.DVSCapability) | [
"Applies",
"the",
"values",
"of",
"the",
"capability_dict",
"dictionary",
"to",
"a",
"DVS",
"capability",
"object",
"(",
"vim",
".",
"vim",
".",
"DVSCapability",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3864-L3877 | train |
saltstack/salt | salt/modules/vsphere.py | _apply_dvs_infrastructure_traffic_resources | def _apply_dvs_infrastructure_traffic_resources(infra_traffic_resources,
resource_dicts):
'''
Applies the values of the resource dictionaries to infra traffic resources,
creating the infra traffic resource if required
(vim.DistributedVirtualSwitchProductSpec)
'''
for res_dict in resource_dicts:
filtered_traffic_resources = \
[r for r in infra_traffic_resources if r.key == res_dict['key']]
if filtered_traffic_resources:
traffic_res = filtered_traffic_resources[0]
else:
traffic_res = vim.DvsHostInfrastructureTrafficResource()
traffic_res.key = res_dict['key']
traffic_res.allocationInfo = \
vim.DvsHostInfrastructureTrafficResourceAllocation()
infra_traffic_resources.append(traffic_res)
if res_dict.get('limit'):
traffic_res.allocationInfo.limit = res_dict['limit']
if res_dict.get('reservation'):
traffic_res.allocationInfo.reservation = res_dict['reservation']
if res_dict.get('num_shares') or res_dict.get('share_level'):
if not traffic_res.allocationInfo.shares:
traffic_res.allocationInfo.shares = vim.SharesInfo()
if res_dict.get('share_level'):
traffic_res.allocationInfo.shares.level = \
vim.SharesLevel(res_dict['share_level'])
if res_dict.get('num_shares'):
#XXX Even though we always set the number of shares if provided,
#the vCenter will ignore it unless the share level is 'custom'.
traffic_res.allocationInfo.shares.shares = res_dict['num_shares'] | python | def _apply_dvs_infrastructure_traffic_resources(infra_traffic_resources,
resource_dicts):
'''
Applies the values of the resource dictionaries to infra traffic resources,
creating the infra traffic resource if required
(vim.DistributedVirtualSwitchProductSpec)
'''
for res_dict in resource_dicts:
filtered_traffic_resources = \
[r for r in infra_traffic_resources if r.key == res_dict['key']]
if filtered_traffic_resources:
traffic_res = filtered_traffic_resources[0]
else:
traffic_res = vim.DvsHostInfrastructureTrafficResource()
traffic_res.key = res_dict['key']
traffic_res.allocationInfo = \
vim.DvsHostInfrastructureTrafficResourceAllocation()
infra_traffic_resources.append(traffic_res)
if res_dict.get('limit'):
traffic_res.allocationInfo.limit = res_dict['limit']
if res_dict.get('reservation'):
traffic_res.allocationInfo.reservation = res_dict['reservation']
if res_dict.get('num_shares') or res_dict.get('share_level'):
if not traffic_res.allocationInfo.shares:
traffic_res.allocationInfo.shares = vim.SharesInfo()
if res_dict.get('share_level'):
traffic_res.allocationInfo.shares.level = \
vim.SharesLevel(res_dict['share_level'])
if res_dict.get('num_shares'):
#XXX Even though we always set the number of shares if provided,
#the vCenter will ignore it unless the share level is 'custom'.
traffic_res.allocationInfo.shares.shares = res_dict['num_shares'] | [
"def",
"_apply_dvs_infrastructure_traffic_resources",
"(",
"infra_traffic_resources",
",",
"resource_dicts",
")",
":",
"for",
"res_dict",
"in",
"resource_dicts",
":",
"filtered_traffic_resources",
"=",
"[",
"r",
"for",
"r",
"in",
"infra_traffic_resources",
"if",
"r",
".... | Applies the values of the resource dictionaries to infra traffic resources,
creating the infra traffic resource if required
(vim.DistributedVirtualSwitchProductSpec) | [
"Applies",
"the",
"values",
"of",
"the",
"resource",
"dictionaries",
"to",
"infra",
"traffic",
"resources",
"creating",
"the",
"infra",
"traffic",
"resource",
"if",
"required",
"(",
"vim",
".",
"DistributedVirtualSwitchProductSpec",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3880-L3911 | train |
saltstack/salt | salt/modules/vsphere.py | _apply_dvs_network_resource_pools | def _apply_dvs_network_resource_pools(network_resource_pools, resource_dicts):
'''
Applies the values of the resource dictionaries to network resource pools,
creating the resource pools if required
(vim.DVSNetworkResourcePoolConfigSpec)
'''
for res_dict in resource_dicts:
ress = [r for r in network_resource_pools if r.key == res_dict['key']]
if ress:
res = ress[0]
else:
res = vim.DVSNetworkResourcePoolConfigSpec()
res.key = res_dict['key']
res.allocationInfo = \
vim.DVSNetworkResourcePoolAllocationInfo()
network_resource_pools.append(res)
if res_dict.get('limit'):
res.allocationInfo.limit = res_dict['limit']
if res_dict.get('num_shares') and res_dict.get('share_level'):
if not res.allocationInfo.shares:
res.allocationInfo.shares = vim.SharesInfo()
res.allocationInfo.shares.shares = res_dict['num_shares']
res.allocationInfo.shares.level = \
vim.SharesLevel(res_dict['share_level']) | python | def _apply_dvs_network_resource_pools(network_resource_pools, resource_dicts):
'''
Applies the values of the resource dictionaries to network resource pools,
creating the resource pools if required
(vim.DVSNetworkResourcePoolConfigSpec)
'''
for res_dict in resource_dicts:
ress = [r for r in network_resource_pools if r.key == res_dict['key']]
if ress:
res = ress[0]
else:
res = vim.DVSNetworkResourcePoolConfigSpec()
res.key = res_dict['key']
res.allocationInfo = \
vim.DVSNetworkResourcePoolAllocationInfo()
network_resource_pools.append(res)
if res_dict.get('limit'):
res.allocationInfo.limit = res_dict['limit']
if res_dict.get('num_shares') and res_dict.get('share_level'):
if not res.allocationInfo.shares:
res.allocationInfo.shares = vim.SharesInfo()
res.allocationInfo.shares.shares = res_dict['num_shares']
res.allocationInfo.shares.level = \
vim.SharesLevel(res_dict['share_level']) | [
"def",
"_apply_dvs_network_resource_pools",
"(",
"network_resource_pools",
",",
"resource_dicts",
")",
":",
"for",
"res_dict",
"in",
"resource_dicts",
":",
"ress",
"=",
"[",
"r",
"for",
"r",
"in",
"network_resource_pools",
"if",
"r",
".",
"key",
"==",
"res_dict",
... | Applies the values of the resource dictionaries to network resource pools,
creating the resource pools if required
(vim.DVSNetworkResourcePoolConfigSpec) | [
"Applies",
"the",
"values",
"of",
"the",
"resource",
"dictionaries",
"to",
"network",
"resource",
"pools",
"creating",
"the",
"resource",
"pools",
"if",
"required",
"(",
"vim",
".",
"DVSNetworkResourcePoolConfigSpec",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3914-L3937 | train |
saltstack/salt | salt/modules/vsphere.py | create_dvs | def create_dvs(dvs_dict, dvs_name, service_instance=None):
'''
Creates a distributed virtual switch (DVS).
Note: The ``dvs_name`` param will override any name set in ``dvs_dict``.
dvs_dict
Dict representation of the new DVS (example in salt.states.dvs)
dvs_name
Name of the DVS to be created.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_dvs dvs dict=$dvs_dict dvs_name=dvs_name
'''
log.trace('Creating dvs \'%s\' with dict = %s', dvs_name, dvs_dict)
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
# Make the name of the DVS consistent with the call
dvs_dict['name'] = dvs_name
# Build the config spec from the input
dvs_create_spec = vim.DVSCreateSpec()
dvs_create_spec.configSpec = vim.VMwareDVSConfigSpec()
_apply_dvs_config(dvs_create_spec.configSpec, dvs_dict)
if dvs_dict.get('product_info'):
dvs_create_spec.productInfo = vim.DistributedVirtualSwitchProductSpec()
_apply_dvs_product_info(dvs_create_spec.productInfo,
dvs_dict['product_info'])
if dvs_dict.get('capability'):
dvs_create_spec.capability = vim.DVSCapability()
_apply_dvs_capability(dvs_create_spec.capability,
dvs_dict['capability'])
if dvs_dict.get('link_discovery_protocol'):
dvs_create_spec.configSpec.linkDiscoveryProtocolConfig = \
vim.LinkDiscoveryProtocolConfig()
_apply_dvs_link_discovery_protocol(
dvs_create_spec.configSpec.linkDiscoveryProtocolConfig,
dvs_dict['link_discovery_protocol'])
if dvs_dict.get('infrastructure_traffic_resource_pools'):
dvs_create_spec.configSpec.infrastructureTrafficResourceConfig = []
_apply_dvs_infrastructure_traffic_resources(
dvs_create_spec.configSpec.infrastructureTrafficResourceConfig,
dvs_dict['infrastructure_traffic_resource_pools'])
log.trace('dvs_create_spec = %s', dvs_create_spec)
salt.utils.vmware.create_dvs(dc_ref, dvs_name, dvs_create_spec)
if 'network_resource_management_enabled' in dvs_dict:
dvs_refs = salt.utils.vmware.get_dvss(dc_ref,
dvs_names=[dvs_name])
if not dvs_refs:
raise VMwareObjectRetrievalError(
'DVS \'{0}\' wasn\'t found in datacenter \'{1}\''
''.format(dvs_name, datacenter))
dvs_ref = dvs_refs[0]
salt.utils.vmware.set_dvs_network_resource_management_enabled(
dvs_ref, dvs_dict['network_resource_management_enabled'])
return True | python | def create_dvs(dvs_dict, dvs_name, service_instance=None):
'''
Creates a distributed virtual switch (DVS).
Note: The ``dvs_name`` param will override any name set in ``dvs_dict``.
dvs_dict
Dict representation of the new DVS (example in salt.states.dvs)
dvs_name
Name of the DVS to be created.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_dvs dvs dict=$dvs_dict dvs_name=dvs_name
'''
log.trace('Creating dvs \'%s\' with dict = %s', dvs_name, dvs_dict)
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
# Make the name of the DVS consistent with the call
dvs_dict['name'] = dvs_name
# Build the config spec from the input
dvs_create_spec = vim.DVSCreateSpec()
dvs_create_spec.configSpec = vim.VMwareDVSConfigSpec()
_apply_dvs_config(dvs_create_spec.configSpec, dvs_dict)
if dvs_dict.get('product_info'):
dvs_create_spec.productInfo = vim.DistributedVirtualSwitchProductSpec()
_apply_dvs_product_info(dvs_create_spec.productInfo,
dvs_dict['product_info'])
if dvs_dict.get('capability'):
dvs_create_spec.capability = vim.DVSCapability()
_apply_dvs_capability(dvs_create_spec.capability,
dvs_dict['capability'])
if dvs_dict.get('link_discovery_protocol'):
dvs_create_spec.configSpec.linkDiscoveryProtocolConfig = \
vim.LinkDiscoveryProtocolConfig()
_apply_dvs_link_discovery_protocol(
dvs_create_spec.configSpec.linkDiscoveryProtocolConfig,
dvs_dict['link_discovery_protocol'])
if dvs_dict.get('infrastructure_traffic_resource_pools'):
dvs_create_spec.configSpec.infrastructureTrafficResourceConfig = []
_apply_dvs_infrastructure_traffic_resources(
dvs_create_spec.configSpec.infrastructureTrafficResourceConfig,
dvs_dict['infrastructure_traffic_resource_pools'])
log.trace('dvs_create_spec = %s', dvs_create_spec)
salt.utils.vmware.create_dvs(dc_ref, dvs_name, dvs_create_spec)
if 'network_resource_management_enabled' in dvs_dict:
dvs_refs = salt.utils.vmware.get_dvss(dc_ref,
dvs_names=[dvs_name])
if not dvs_refs:
raise VMwareObjectRetrievalError(
'DVS \'{0}\' wasn\'t found in datacenter \'{1}\''
''.format(dvs_name, datacenter))
dvs_ref = dvs_refs[0]
salt.utils.vmware.set_dvs_network_resource_management_enabled(
dvs_ref, dvs_dict['network_resource_management_enabled'])
return True | [
"def",
"create_dvs",
"(",
"dvs_dict",
",",
"dvs_name",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'Creating dvs \\'%s\\' with dict = %s'",
",",
"dvs_name",
",",
"dvs_dict",
")",
"proxy_type",
"=",
"get_proxy_type",
"(",
")",
"if",... | Creates a distributed virtual switch (DVS).
Note: The ``dvs_name`` param will override any name set in ``dvs_dict``.
dvs_dict
Dict representation of the new DVS (example in salt.states.dvs)
dvs_name
Name of the DVS to be created.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_dvs dvs dict=$dvs_dict dvs_name=dvs_name | [
"Creates",
"a",
"distributed",
"virtual",
"switch",
"(",
"DVS",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3943-L4008 | train |
saltstack/salt | salt/modules/vsphere.py | update_dvs | def update_dvs(dvs_dict, dvs, service_instance=None):
'''
Updates a distributed virtual switch (DVS).
Note: Updating the product info, capability, uplinks of a DVS is not
supported so the corresponding entries in ``dvs_dict`` will be
ignored.
dvs_dict
Dictionary with the values the DVS should be update with
(example in salt.states.dvs)
dvs
Name of the DVS to be updated.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.update_dvs dvs_dict=$dvs_dict dvs=dvs1
'''
# Remove ignored properties
log.trace('Updating dvs \'%s\' with dict = %s', dvs, dvs_dict)
for prop in ['product_info', 'capability', 'uplink_names', 'name']:
if prop in dvs_dict:
del dvs_dict[prop]
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' wasn\'t found in '
'datacenter \'{1}\''
''.format(dvs, datacenter))
dvs_ref = dvs_refs[0]
# Build the config spec from the input
dvs_props = salt.utils.vmware.get_properties_of_managed_object(
dvs_ref, ['config', 'capability'])
dvs_config = vim.VMwareDVSConfigSpec()
# Copy all of the properties in the config of the of the DVS to a
# DvsConfigSpec
skipped_properties = ['host']
for prop in dvs_config.__dict__.keys():
if prop in skipped_properties:
continue
if hasattr(dvs_props['config'], prop):
setattr(dvs_config, prop, getattr(dvs_props['config'], prop))
_apply_dvs_config(dvs_config, dvs_dict)
if dvs_dict.get('link_discovery_protocol'):
if not dvs_config.linkDiscoveryProtocolConfig:
dvs_config.linkDiscoveryProtocolConfig = \
vim.LinkDiscoveryProtocolConfig()
_apply_dvs_link_discovery_protocol(
dvs_config.linkDiscoveryProtocolConfig,
dvs_dict['link_discovery_protocol'])
if dvs_dict.get('infrastructure_traffic_resource_pools'):
if not dvs_config.infrastructureTrafficResourceConfig:
dvs_config.infrastructureTrafficResourceConfig = []
_apply_dvs_infrastructure_traffic_resources(
dvs_config.infrastructureTrafficResourceConfig,
dvs_dict['infrastructure_traffic_resource_pools'])
log.trace('dvs_config = %s', dvs_config)
salt.utils.vmware.update_dvs(dvs_ref, dvs_config_spec=dvs_config)
if 'network_resource_management_enabled' in dvs_dict:
salt.utils.vmware.set_dvs_network_resource_management_enabled(
dvs_ref, dvs_dict['network_resource_management_enabled'])
return True | python | def update_dvs(dvs_dict, dvs, service_instance=None):
'''
Updates a distributed virtual switch (DVS).
Note: Updating the product info, capability, uplinks of a DVS is not
supported so the corresponding entries in ``dvs_dict`` will be
ignored.
dvs_dict
Dictionary with the values the DVS should be update with
(example in salt.states.dvs)
dvs
Name of the DVS to be updated.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.update_dvs dvs_dict=$dvs_dict dvs=dvs1
'''
# Remove ignored properties
log.trace('Updating dvs \'%s\' with dict = %s', dvs, dvs_dict)
for prop in ['product_info', 'capability', 'uplink_names', 'name']:
if prop in dvs_dict:
del dvs_dict[prop]
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' wasn\'t found in '
'datacenter \'{1}\''
''.format(dvs, datacenter))
dvs_ref = dvs_refs[0]
# Build the config spec from the input
dvs_props = salt.utils.vmware.get_properties_of_managed_object(
dvs_ref, ['config', 'capability'])
dvs_config = vim.VMwareDVSConfigSpec()
# Copy all of the properties in the config of the of the DVS to a
# DvsConfigSpec
skipped_properties = ['host']
for prop in dvs_config.__dict__.keys():
if prop in skipped_properties:
continue
if hasattr(dvs_props['config'], prop):
setattr(dvs_config, prop, getattr(dvs_props['config'], prop))
_apply_dvs_config(dvs_config, dvs_dict)
if dvs_dict.get('link_discovery_protocol'):
if not dvs_config.linkDiscoveryProtocolConfig:
dvs_config.linkDiscoveryProtocolConfig = \
vim.LinkDiscoveryProtocolConfig()
_apply_dvs_link_discovery_protocol(
dvs_config.linkDiscoveryProtocolConfig,
dvs_dict['link_discovery_protocol'])
if dvs_dict.get('infrastructure_traffic_resource_pools'):
if not dvs_config.infrastructureTrafficResourceConfig:
dvs_config.infrastructureTrafficResourceConfig = []
_apply_dvs_infrastructure_traffic_resources(
dvs_config.infrastructureTrafficResourceConfig,
dvs_dict['infrastructure_traffic_resource_pools'])
log.trace('dvs_config = %s', dvs_config)
salt.utils.vmware.update_dvs(dvs_ref, dvs_config_spec=dvs_config)
if 'network_resource_management_enabled' in dvs_dict:
salt.utils.vmware.set_dvs_network_resource_management_enabled(
dvs_ref, dvs_dict['network_resource_management_enabled'])
return True | [
"def",
"update_dvs",
"(",
"dvs_dict",
",",
"dvs",
",",
"service_instance",
"=",
"None",
")",
":",
"# Remove ignored properties",
"log",
".",
"trace",
"(",
"'Updating dvs \\'%s\\' with dict = %s'",
",",
"dvs",
",",
"dvs_dict",
")",
"for",
"prop",
"in",
"[",
"'pro... | Updates a distributed virtual switch (DVS).
Note: Updating the product info, capability, uplinks of a DVS is not
supported so the corresponding entries in ``dvs_dict`` will be
ignored.
dvs_dict
Dictionary with the values the DVS should be update with
(example in salt.states.dvs)
dvs
Name of the DVS to be updated.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.update_dvs dvs_dict=$dvs_dict dvs=dvs1 | [
"Updates",
"a",
"distributed",
"virtual",
"switch",
"(",
"DVS",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4014-L4086 | train |
saltstack/salt | salt/modules/vsphere.py | _get_dvportgroup_out_shaping | def _get_dvportgroup_out_shaping(pg_name, pg_default_port_config):
'''
Returns the out shaping policy of a distributed virtual portgroup
pg_name
The name of the portgroup
pg_default_port_config
The dafault port config of the portgroup
'''
log.trace('Retrieving portgroup\'s \'%s\' out shaping config', pg_name)
out_shaping_policy = pg_default_port_config.outShapingPolicy
if not out_shaping_policy:
return {}
return {'average_bandwidth': out_shaping_policy.averageBandwidth.value,
'burst_size': out_shaping_policy.burstSize.value,
'enabled': out_shaping_policy.enabled.value,
'peak_bandwidth': out_shaping_policy.peakBandwidth.value} | python | def _get_dvportgroup_out_shaping(pg_name, pg_default_port_config):
'''
Returns the out shaping policy of a distributed virtual portgroup
pg_name
The name of the portgroup
pg_default_port_config
The dafault port config of the portgroup
'''
log.trace('Retrieving portgroup\'s \'%s\' out shaping config', pg_name)
out_shaping_policy = pg_default_port_config.outShapingPolicy
if not out_shaping_policy:
return {}
return {'average_bandwidth': out_shaping_policy.averageBandwidth.value,
'burst_size': out_shaping_policy.burstSize.value,
'enabled': out_shaping_policy.enabled.value,
'peak_bandwidth': out_shaping_policy.peakBandwidth.value} | [
"def",
"_get_dvportgroup_out_shaping",
"(",
"pg_name",
",",
"pg_default_port_config",
")",
":",
"log",
".",
"trace",
"(",
"'Retrieving portgroup\\'s \\'%s\\' out shaping config'",
",",
"pg_name",
")",
"out_shaping_policy",
"=",
"pg_default_port_config",
".",
"outShapingPolicy... | Returns the out shaping policy of a distributed virtual portgroup
pg_name
The name of the portgroup
pg_default_port_config
The dafault port config of the portgroup | [
"Returns",
"the",
"out",
"shaping",
"policy",
"of",
"a",
"distributed",
"virtual",
"portgroup"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4089-L4106 | train |
saltstack/salt | salt/modules/vsphere.py | _get_dvportgroup_security_policy | def _get_dvportgroup_security_policy(pg_name, pg_default_port_config):
'''
Returns the security policy of a distributed virtual portgroup
pg_name
The name of the portgroup
pg_default_port_config
The dafault port config of the portgroup
'''
log.trace('Retrieving portgroup\'s \'%s\' security policy config', pg_name)
sec_policy = pg_default_port_config.securityPolicy
if not sec_policy:
return {}
return {'allow_promiscuous': sec_policy.allowPromiscuous.value,
'forged_transmits': sec_policy.forgedTransmits.value,
'mac_changes': sec_policy.macChanges.value} | python | def _get_dvportgroup_security_policy(pg_name, pg_default_port_config):
'''
Returns the security policy of a distributed virtual portgroup
pg_name
The name of the portgroup
pg_default_port_config
The dafault port config of the portgroup
'''
log.trace('Retrieving portgroup\'s \'%s\' security policy config', pg_name)
sec_policy = pg_default_port_config.securityPolicy
if not sec_policy:
return {}
return {'allow_promiscuous': sec_policy.allowPromiscuous.value,
'forged_transmits': sec_policy.forgedTransmits.value,
'mac_changes': sec_policy.macChanges.value} | [
"def",
"_get_dvportgroup_security_policy",
"(",
"pg_name",
",",
"pg_default_port_config",
")",
":",
"log",
".",
"trace",
"(",
"'Retrieving portgroup\\'s \\'%s\\' security policy config'",
",",
"pg_name",
")",
"sec_policy",
"=",
"pg_default_port_config",
".",
"securityPolicy",... | Returns the security policy of a distributed virtual portgroup
pg_name
The name of the portgroup
pg_default_port_config
The dafault port config of the portgroup | [
"Returns",
"the",
"security",
"policy",
"of",
"a",
"distributed",
"virtual",
"portgroup"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4109-L4125 | train |
saltstack/salt | salt/modules/vsphere.py | _get_dvportgroup_teaming | def _get_dvportgroup_teaming(pg_name, pg_default_port_config):
'''
Returns the teaming of a distributed virtual portgroup
pg_name
The name of the portgroup
pg_default_port_config
The dafault port config of the portgroup
'''
log.trace('Retrieving portgroup\'s \'%s\' teaming config', pg_name)
teaming_policy = pg_default_port_config.uplinkTeamingPolicy
if not teaming_policy:
return {}
ret_dict = {'notify_switches': teaming_policy.notifySwitches.value,
'policy': teaming_policy.policy.value,
'reverse_policy': teaming_policy.reversePolicy.value,
'rolling_order': teaming_policy.rollingOrder.value}
if teaming_policy.failureCriteria:
failure_criteria = teaming_policy.failureCriteria
ret_dict.update({'failure_criteria': {
'check_beacon': failure_criteria.checkBeacon.value,
'check_duplex': failure_criteria.checkDuplex.value,
'check_error_percent': failure_criteria.checkErrorPercent.value,
'check_speed': failure_criteria.checkSpeed.value,
'full_duplex': failure_criteria.fullDuplex.value,
'percentage': failure_criteria.percentage.value,
'speed': failure_criteria.speed.value}})
if teaming_policy.uplinkPortOrder:
uplink_order = teaming_policy.uplinkPortOrder
ret_dict.update({'port_order': {
'active': uplink_order.activeUplinkPort,
'standby': uplink_order.standbyUplinkPort}})
return ret_dict | python | def _get_dvportgroup_teaming(pg_name, pg_default_port_config):
'''
Returns the teaming of a distributed virtual portgroup
pg_name
The name of the portgroup
pg_default_port_config
The dafault port config of the portgroup
'''
log.trace('Retrieving portgroup\'s \'%s\' teaming config', pg_name)
teaming_policy = pg_default_port_config.uplinkTeamingPolicy
if not teaming_policy:
return {}
ret_dict = {'notify_switches': teaming_policy.notifySwitches.value,
'policy': teaming_policy.policy.value,
'reverse_policy': teaming_policy.reversePolicy.value,
'rolling_order': teaming_policy.rollingOrder.value}
if teaming_policy.failureCriteria:
failure_criteria = teaming_policy.failureCriteria
ret_dict.update({'failure_criteria': {
'check_beacon': failure_criteria.checkBeacon.value,
'check_duplex': failure_criteria.checkDuplex.value,
'check_error_percent': failure_criteria.checkErrorPercent.value,
'check_speed': failure_criteria.checkSpeed.value,
'full_duplex': failure_criteria.fullDuplex.value,
'percentage': failure_criteria.percentage.value,
'speed': failure_criteria.speed.value}})
if teaming_policy.uplinkPortOrder:
uplink_order = teaming_policy.uplinkPortOrder
ret_dict.update({'port_order': {
'active': uplink_order.activeUplinkPort,
'standby': uplink_order.standbyUplinkPort}})
return ret_dict | [
"def",
"_get_dvportgroup_teaming",
"(",
"pg_name",
",",
"pg_default_port_config",
")",
":",
"log",
".",
"trace",
"(",
"'Retrieving portgroup\\'s \\'%s\\' teaming config'",
",",
"pg_name",
")",
"teaming_policy",
"=",
"pg_default_port_config",
".",
"uplinkTeamingPolicy",
"if"... | Returns the teaming of a distributed virtual portgroup
pg_name
The name of the portgroup
pg_default_port_config
The dafault port config of the portgroup | [
"Returns",
"the",
"teaming",
"of",
"a",
"distributed",
"virtual",
"portgroup"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4128-L4161 | train |
saltstack/salt | salt/modules/vsphere.py | _get_dvportgroup_dict | def _get_dvportgroup_dict(pg_ref):
'''
Returns a dictionary with a distributed virutal portgroup data
pg_ref
Portgroup reference
'''
props = salt.utils.vmware.get_properties_of_managed_object(
pg_ref, ['name', 'config.description', 'config.numPorts',
'config.type', 'config.defaultPortConfig'])
pg_dict = {'name': props['name'],
'description': props.get('config.description'),
'num_ports': props['config.numPorts'],
'type': props['config.type']}
if props['config.defaultPortConfig']:
dpg = props['config.defaultPortConfig']
if dpg.vlan and \
isinstance(dpg.vlan,
vim.VmwareDistributedVirtualSwitchVlanIdSpec):
pg_dict.update({'vlan_id': dpg.vlan.vlanId})
pg_dict.update({'out_shaping':
_get_dvportgroup_out_shaping(
props['name'],
props['config.defaultPortConfig'])})
pg_dict.update({'security_policy':
_get_dvportgroup_security_policy(
props['name'],
props['config.defaultPortConfig'])})
pg_dict.update({'teaming':
_get_dvportgroup_teaming(
props['name'],
props['config.defaultPortConfig'])})
return pg_dict | python | def _get_dvportgroup_dict(pg_ref):
'''
Returns a dictionary with a distributed virutal portgroup data
pg_ref
Portgroup reference
'''
props = salt.utils.vmware.get_properties_of_managed_object(
pg_ref, ['name', 'config.description', 'config.numPorts',
'config.type', 'config.defaultPortConfig'])
pg_dict = {'name': props['name'],
'description': props.get('config.description'),
'num_ports': props['config.numPorts'],
'type': props['config.type']}
if props['config.defaultPortConfig']:
dpg = props['config.defaultPortConfig']
if dpg.vlan and \
isinstance(dpg.vlan,
vim.VmwareDistributedVirtualSwitchVlanIdSpec):
pg_dict.update({'vlan_id': dpg.vlan.vlanId})
pg_dict.update({'out_shaping':
_get_dvportgroup_out_shaping(
props['name'],
props['config.defaultPortConfig'])})
pg_dict.update({'security_policy':
_get_dvportgroup_security_policy(
props['name'],
props['config.defaultPortConfig'])})
pg_dict.update({'teaming':
_get_dvportgroup_teaming(
props['name'],
props['config.defaultPortConfig'])})
return pg_dict | [
"def",
"_get_dvportgroup_dict",
"(",
"pg_ref",
")",
":",
"props",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_properties_of_managed_object",
"(",
"pg_ref",
",",
"[",
"'name'",
",",
"'config.description'",
",",
"'config.numPorts'",
",",
"'config.type'",
","... | Returns a dictionary with a distributed virutal portgroup data
pg_ref
Portgroup reference | [
"Returns",
"a",
"dictionary",
"with",
"a",
"distributed",
"virutal",
"portgroup",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4164-L4198 | train |
saltstack/salt | salt/modules/vsphere.py | list_dvportgroups | def list_dvportgroups(dvs=None, portgroup_names=None, service_instance=None):
'''
Returns a list of distributed virtual switch portgroups.
The list can be filtered by the portgroup names or by the DVS.
dvs
Name of the DVS containing the portgroups.
Default value is None.
portgroup_names
List of portgroup names to look for. If None, all portgroups are
returned.
Default value is None
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_dvporgroups
salt '*' vsphere.list_dvportgroups dvs=dvs1
salt '*' vsphere.list_dvportgroups portgroup_names=[pg1]
salt '*' vsphere.list_dvportgroups dvs=dvs1 portgroup_names=[pg1]
'''
ret_dict = []
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
if dvs:
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' was not '
'retrieved'.format(dvs))
dvs_ref = dvs_refs[0]
get_all_portgroups = True if not portgroup_names else False
for pg_ref in salt.utils.vmware.get_dvportgroups(
parent_ref=dvs_ref if dvs else dc_ref,
portgroup_names=portgroup_names,
get_all_portgroups=get_all_portgroups):
ret_dict.append(_get_dvportgroup_dict(pg_ref))
return ret_dict | python | def list_dvportgroups(dvs=None, portgroup_names=None, service_instance=None):
'''
Returns a list of distributed virtual switch portgroups.
The list can be filtered by the portgroup names or by the DVS.
dvs
Name of the DVS containing the portgroups.
Default value is None.
portgroup_names
List of portgroup names to look for. If None, all portgroups are
returned.
Default value is None
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_dvporgroups
salt '*' vsphere.list_dvportgroups dvs=dvs1
salt '*' vsphere.list_dvportgroups portgroup_names=[pg1]
salt '*' vsphere.list_dvportgroups dvs=dvs1 portgroup_names=[pg1]
'''
ret_dict = []
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
if dvs:
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' was not '
'retrieved'.format(dvs))
dvs_ref = dvs_refs[0]
get_all_portgroups = True if not portgroup_names else False
for pg_ref in salt.utils.vmware.get_dvportgroups(
parent_ref=dvs_ref if dvs else dc_ref,
portgroup_names=portgroup_names,
get_all_portgroups=get_all_portgroups):
ret_dict.append(_get_dvportgroup_dict(pg_ref))
return ret_dict | [
"def",
"list_dvportgroups",
"(",
"dvs",
"=",
"None",
",",
"portgroup_names",
"=",
"None",
",",
"service_instance",
"=",
"None",
")",
":",
"ret_dict",
"=",
"[",
"]",
"proxy_type",
"=",
"get_proxy_type",
"(",
")",
"if",
"proxy_type",
"==",
"'esxdatacenter'",
"... | Returns a list of distributed virtual switch portgroups.
The list can be filtered by the portgroup names or by the DVS.
dvs
Name of the DVS containing the portgroups.
Default value is None.
portgroup_names
List of portgroup names to look for. If None, all portgroups are
returned.
Default value is None
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_dvporgroups
salt '*' vsphere.list_dvportgroups dvs=dvs1
salt '*' vsphere.list_dvportgroups portgroup_names=[pg1]
salt '*' vsphere.list_dvportgroups dvs=dvs1 portgroup_names=[pg1] | [
"Returns",
"a",
"list",
"of",
"distributed",
"virtual",
"switch",
"portgroups",
".",
"The",
"list",
"can",
"be",
"filtered",
"by",
"the",
"portgroup",
"names",
"or",
"by",
"the",
"DVS",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4204-L4253 | train |
saltstack/salt | salt/modules/vsphere.py | list_uplink_dvportgroup | def list_uplink_dvportgroup(dvs, service_instance=None):
'''
Returns the uplink portgroup of a distributed virtual switch.
dvs
Name of the DVS containing the portgroup.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_uplink_dvportgroup dvs=dvs_name
'''
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' was not '
'retrieved'.format(dvs))
uplink_pg_ref = salt.utils.vmware.get_uplink_dvportgroup(dvs_refs[0])
return _get_dvportgroup_dict(uplink_pg_ref) | python | def list_uplink_dvportgroup(dvs, service_instance=None):
'''
Returns the uplink portgroup of a distributed virtual switch.
dvs
Name of the DVS containing the portgroup.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_uplink_dvportgroup dvs=dvs_name
'''
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' was not '
'retrieved'.format(dvs))
uplink_pg_ref = salt.utils.vmware.get_uplink_dvportgroup(dvs_refs[0])
return _get_dvportgroup_dict(uplink_pg_ref) | [
"def",
"list_uplink_dvportgroup",
"(",
"dvs",
",",
"service_instance",
"=",
"None",
")",
":",
"proxy_type",
"=",
"get_proxy_type",
"(",
")",
"if",
"proxy_type",
"==",
"'esxdatacenter'",
":",
"datacenter",
"=",
"__salt__",
"[",
"'esxdatacenter.get_details'",
"]",
"... | Returns the uplink portgroup of a distributed virtual switch.
dvs
Name of the DVS containing the portgroup.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_uplink_dvportgroup dvs=dvs_name | [
"Returns",
"the",
"uplink",
"portgroup",
"of",
"a",
"distributed",
"virtual",
"switch",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4259-L4286 | train |
saltstack/salt | salt/modules/vsphere.py | _apply_dvportgroup_out_shaping | def _apply_dvportgroup_out_shaping(pg_name, out_shaping, out_shaping_conf):
'''
Applies the values in out_shaping_conf to an out_shaping object
pg_name
The name of the portgroup
out_shaping
The vim.DVSTrafficShapingPolicy to apply the config to
out_shaping_conf
The out shaping config
'''
log.trace('Building portgroup\'s \'%s\' out shaping policy', pg_name)
if out_shaping_conf.get('average_bandwidth'):
out_shaping.averageBandwidth = vim.LongPolicy()
out_shaping.averageBandwidth.value = \
out_shaping_conf['average_bandwidth']
if out_shaping_conf.get('burst_size'):
out_shaping.burstSize = vim.LongPolicy()
out_shaping.burstSize.value = out_shaping_conf['burst_size']
if 'enabled' in out_shaping_conf:
out_shaping.enabled = vim.BoolPolicy()
out_shaping.enabled.value = out_shaping_conf['enabled']
if out_shaping_conf.get('peak_bandwidth'):
out_shaping.peakBandwidth = vim.LongPolicy()
out_shaping.peakBandwidth.value = out_shaping_conf['peak_bandwidth'] | python | def _apply_dvportgroup_out_shaping(pg_name, out_shaping, out_shaping_conf):
'''
Applies the values in out_shaping_conf to an out_shaping object
pg_name
The name of the portgroup
out_shaping
The vim.DVSTrafficShapingPolicy to apply the config to
out_shaping_conf
The out shaping config
'''
log.trace('Building portgroup\'s \'%s\' out shaping policy', pg_name)
if out_shaping_conf.get('average_bandwidth'):
out_shaping.averageBandwidth = vim.LongPolicy()
out_shaping.averageBandwidth.value = \
out_shaping_conf['average_bandwidth']
if out_shaping_conf.get('burst_size'):
out_shaping.burstSize = vim.LongPolicy()
out_shaping.burstSize.value = out_shaping_conf['burst_size']
if 'enabled' in out_shaping_conf:
out_shaping.enabled = vim.BoolPolicy()
out_shaping.enabled.value = out_shaping_conf['enabled']
if out_shaping_conf.get('peak_bandwidth'):
out_shaping.peakBandwidth = vim.LongPolicy()
out_shaping.peakBandwidth.value = out_shaping_conf['peak_bandwidth'] | [
"def",
"_apply_dvportgroup_out_shaping",
"(",
"pg_name",
",",
"out_shaping",
",",
"out_shaping_conf",
")",
":",
"log",
".",
"trace",
"(",
"'Building portgroup\\'s \\'%s\\' out shaping policy'",
",",
"pg_name",
")",
"if",
"out_shaping_conf",
".",
"get",
"(",
"'average_ba... | Applies the values in out_shaping_conf to an out_shaping object
pg_name
The name of the portgroup
out_shaping
The vim.DVSTrafficShapingPolicy to apply the config to
out_shaping_conf
The out shaping config | [
"Applies",
"the",
"values",
"in",
"out_shaping_conf",
"to",
"an",
"out_shaping",
"object"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4289-L4315 | train |
saltstack/salt | salt/modules/vsphere.py | _apply_dvportgroup_security_policy | def _apply_dvportgroup_security_policy(pg_name, sec_policy, sec_policy_conf):
'''
Applies the values in sec_policy_conf to a security policy object
pg_name
The name of the portgroup
sec_policy
The vim.DVSTrafficShapingPolicy to apply the config to
sec_policy_conf
The out shaping config
'''
log.trace('Building portgroup\'s \'%s\' security policy ', pg_name)
if 'allow_promiscuous' in sec_policy_conf:
sec_policy.allowPromiscuous = vim.BoolPolicy()
sec_policy.allowPromiscuous.value = \
sec_policy_conf['allow_promiscuous']
if 'forged_transmits' in sec_policy_conf:
sec_policy.forgedTransmits = vim.BoolPolicy()
sec_policy.forgedTransmits.value = sec_policy_conf['forged_transmits']
if 'mac_changes' in sec_policy_conf:
sec_policy.macChanges = vim.BoolPolicy()
sec_policy.macChanges.value = sec_policy_conf['mac_changes'] | python | def _apply_dvportgroup_security_policy(pg_name, sec_policy, sec_policy_conf):
'''
Applies the values in sec_policy_conf to a security policy object
pg_name
The name of the portgroup
sec_policy
The vim.DVSTrafficShapingPolicy to apply the config to
sec_policy_conf
The out shaping config
'''
log.trace('Building portgroup\'s \'%s\' security policy ', pg_name)
if 'allow_promiscuous' in sec_policy_conf:
sec_policy.allowPromiscuous = vim.BoolPolicy()
sec_policy.allowPromiscuous.value = \
sec_policy_conf['allow_promiscuous']
if 'forged_transmits' in sec_policy_conf:
sec_policy.forgedTransmits = vim.BoolPolicy()
sec_policy.forgedTransmits.value = sec_policy_conf['forged_transmits']
if 'mac_changes' in sec_policy_conf:
sec_policy.macChanges = vim.BoolPolicy()
sec_policy.macChanges.value = sec_policy_conf['mac_changes'] | [
"def",
"_apply_dvportgroup_security_policy",
"(",
"pg_name",
",",
"sec_policy",
",",
"sec_policy_conf",
")",
":",
"log",
".",
"trace",
"(",
"'Building portgroup\\'s \\'%s\\' security policy '",
",",
"pg_name",
")",
"if",
"'allow_promiscuous'",
"in",
"sec_policy_conf",
":"... | Applies the values in sec_policy_conf to a security policy object
pg_name
The name of the portgroup
sec_policy
The vim.DVSTrafficShapingPolicy to apply the config to
sec_policy_conf
The out shaping config | [
"Applies",
"the",
"values",
"in",
"sec_policy_conf",
"to",
"a",
"security",
"policy",
"object"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4318-L4341 | train |
saltstack/salt | salt/modules/vsphere.py | _apply_dvportgroup_teaming | def _apply_dvportgroup_teaming(pg_name, teaming, teaming_conf):
'''
Applies the values in teaming_conf to a teaming policy object
pg_name
The name of the portgroup
teaming
The vim.VmwareUplinkPortTeamingPolicy to apply the config to
teaming_conf
The teaming config
'''
log.trace('Building portgroup\'s \'%s\' teaming', pg_name)
if 'notify_switches' in teaming_conf:
teaming.notifySwitches = vim.BoolPolicy()
teaming.notifySwitches.value = teaming_conf['notify_switches']
if 'policy' in teaming_conf:
teaming.policy = vim.StringPolicy()
teaming.policy.value = teaming_conf['policy']
if 'reverse_policy' in teaming_conf:
teaming.reversePolicy = vim.BoolPolicy()
teaming.reversePolicy.value = teaming_conf['reverse_policy']
if 'rolling_order' in teaming_conf:
teaming.rollingOrder = vim.BoolPolicy()
teaming.rollingOrder.value = teaming_conf['rolling_order']
if 'failure_criteria' in teaming_conf:
if not teaming.failureCriteria:
teaming.failureCriteria = vim.DVSFailureCriteria()
failure_criteria_conf = teaming_conf['failure_criteria']
if 'check_beacon' in failure_criteria_conf:
teaming.failureCriteria.checkBeacon = vim.BoolPolicy()
teaming.failureCriteria.checkBeacon.value = \
failure_criteria_conf['check_beacon']
if 'check_duplex' in failure_criteria_conf:
teaming.failureCriteria.checkDuplex = vim.BoolPolicy()
teaming.failureCriteria.checkDuplex.value = \
failure_criteria_conf['check_duplex']
if 'check_error_percent' in failure_criteria_conf:
teaming.failureCriteria.checkErrorPercent = vim.BoolPolicy()
teaming.failureCriteria.checkErrorPercent.value = \
failure_criteria_conf['check_error_percent']
if 'check_speed' in failure_criteria_conf:
teaming.failureCriteria.checkSpeed = vim.StringPolicy()
teaming.failureCriteria.checkSpeed.value = \
failure_criteria_conf['check_speed']
if 'full_duplex' in failure_criteria_conf:
teaming.failureCriteria.fullDuplex = vim.BoolPolicy()
teaming.failureCriteria.fullDuplex.value = \
failure_criteria_conf['full_duplex']
if 'percentage' in failure_criteria_conf:
teaming.failureCriteria.percentage = vim.IntPolicy()
teaming.failureCriteria.percentage.value = \
failure_criteria_conf['percentage']
if 'speed' in failure_criteria_conf:
teaming.failureCriteria.speed = vim.IntPolicy()
teaming.failureCriteria.speed.value = \
failure_criteria_conf['speed']
if 'port_order' in teaming_conf:
if not teaming.uplinkPortOrder:
teaming.uplinkPortOrder = vim.VMwareUplinkPortOrderPolicy()
if 'active' in teaming_conf['port_order']:
teaming.uplinkPortOrder.activeUplinkPort = \
teaming_conf['port_order']['active']
if 'standby' in teaming_conf['port_order']:
teaming.uplinkPortOrder.standbyUplinkPort = \
teaming_conf['port_order']['standby'] | python | def _apply_dvportgroup_teaming(pg_name, teaming, teaming_conf):
'''
Applies the values in teaming_conf to a teaming policy object
pg_name
The name of the portgroup
teaming
The vim.VmwareUplinkPortTeamingPolicy to apply the config to
teaming_conf
The teaming config
'''
log.trace('Building portgroup\'s \'%s\' teaming', pg_name)
if 'notify_switches' in teaming_conf:
teaming.notifySwitches = vim.BoolPolicy()
teaming.notifySwitches.value = teaming_conf['notify_switches']
if 'policy' in teaming_conf:
teaming.policy = vim.StringPolicy()
teaming.policy.value = teaming_conf['policy']
if 'reverse_policy' in teaming_conf:
teaming.reversePolicy = vim.BoolPolicy()
teaming.reversePolicy.value = teaming_conf['reverse_policy']
if 'rolling_order' in teaming_conf:
teaming.rollingOrder = vim.BoolPolicy()
teaming.rollingOrder.value = teaming_conf['rolling_order']
if 'failure_criteria' in teaming_conf:
if not teaming.failureCriteria:
teaming.failureCriteria = vim.DVSFailureCriteria()
failure_criteria_conf = teaming_conf['failure_criteria']
if 'check_beacon' in failure_criteria_conf:
teaming.failureCriteria.checkBeacon = vim.BoolPolicy()
teaming.failureCriteria.checkBeacon.value = \
failure_criteria_conf['check_beacon']
if 'check_duplex' in failure_criteria_conf:
teaming.failureCriteria.checkDuplex = vim.BoolPolicy()
teaming.failureCriteria.checkDuplex.value = \
failure_criteria_conf['check_duplex']
if 'check_error_percent' in failure_criteria_conf:
teaming.failureCriteria.checkErrorPercent = vim.BoolPolicy()
teaming.failureCriteria.checkErrorPercent.value = \
failure_criteria_conf['check_error_percent']
if 'check_speed' in failure_criteria_conf:
teaming.failureCriteria.checkSpeed = vim.StringPolicy()
teaming.failureCriteria.checkSpeed.value = \
failure_criteria_conf['check_speed']
if 'full_duplex' in failure_criteria_conf:
teaming.failureCriteria.fullDuplex = vim.BoolPolicy()
teaming.failureCriteria.fullDuplex.value = \
failure_criteria_conf['full_duplex']
if 'percentage' in failure_criteria_conf:
teaming.failureCriteria.percentage = vim.IntPolicy()
teaming.failureCriteria.percentage.value = \
failure_criteria_conf['percentage']
if 'speed' in failure_criteria_conf:
teaming.failureCriteria.speed = vim.IntPolicy()
teaming.failureCriteria.speed.value = \
failure_criteria_conf['speed']
if 'port_order' in teaming_conf:
if not teaming.uplinkPortOrder:
teaming.uplinkPortOrder = vim.VMwareUplinkPortOrderPolicy()
if 'active' in teaming_conf['port_order']:
teaming.uplinkPortOrder.activeUplinkPort = \
teaming_conf['port_order']['active']
if 'standby' in teaming_conf['port_order']:
teaming.uplinkPortOrder.standbyUplinkPort = \
teaming_conf['port_order']['standby'] | [
"def",
"_apply_dvportgroup_teaming",
"(",
"pg_name",
",",
"teaming",
",",
"teaming_conf",
")",
":",
"log",
".",
"trace",
"(",
"'Building portgroup\\'s \\'%s\\' teaming'",
",",
"pg_name",
")",
"if",
"'notify_switches'",
"in",
"teaming_conf",
":",
"teaming",
".",
"not... | Applies the values in teaming_conf to a teaming policy object
pg_name
The name of the portgroup
teaming
The vim.VmwareUplinkPortTeamingPolicy to apply the config to
teaming_conf
The teaming config | [
"Applies",
"the",
"values",
"in",
"teaming_conf",
"to",
"a",
"teaming",
"policy",
"object"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4344-L4410 | train |
saltstack/salt | salt/modules/vsphere.py | _apply_dvportgroup_config | def _apply_dvportgroup_config(pg_name, pg_spec, pg_conf):
'''
Applies the values in conf to a distributed portgroup spec
pg_name
The name of the portgroup
pg_spec
The vim.DVPortgroupConfigSpec to apply the config to
pg_conf
The portgroup config
'''
log.trace('Building portgroup\'s \'%s\' spec', pg_name)
if 'name' in pg_conf:
pg_spec.name = pg_conf['name']
if 'description' in pg_conf:
pg_spec.description = pg_conf['description']
if 'num_ports' in pg_conf:
pg_spec.numPorts = pg_conf['num_ports']
if 'type' in pg_conf:
pg_spec.type = pg_conf['type']
if not pg_spec.defaultPortConfig:
for prop in ['vlan_id', 'out_shaping', 'security_policy', 'teaming']:
if prop in pg_conf:
pg_spec.defaultPortConfig = vim.VMwareDVSPortSetting()
if 'vlan_id' in pg_conf:
pg_spec.defaultPortConfig.vlan = \
vim.VmwareDistributedVirtualSwitchVlanIdSpec()
pg_spec.defaultPortConfig.vlan.vlanId = pg_conf['vlan_id']
if 'out_shaping' in pg_conf:
if not pg_spec.defaultPortConfig.outShapingPolicy:
pg_spec.defaultPortConfig.outShapingPolicy = \
vim.DVSTrafficShapingPolicy()
_apply_dvportgroup_out_shaping(
pg_name, pg_spec.defaultPortConfig.outShapingPolicy,
pg_conf['out_shaping'])
if 'security_policy' in pg_conf:
if not pg_spec.defaultPortConfig.securityPolicy:
pg_spec.defaultPortConfig.securityPolicy = \
vim.DVSSecurityPolicy()
_apply_dvportgroup_security_policy(
pg_name, pg_spec.defaultPortConfig.securityPolicy,
pg_conf['security_policy'])
if 'teaming' in pg_conf:
if not pg_spec.defaultPortConfig.uplinkTeamingPolicy:
pg_spec.defaultPortConfig.uplinkTeamingPolicy = \
vim.VmwareUplinkPortTeamingPolicy()
_apply_dvportgroup_teaming(
pg_name, pg_spec.defaultPortConfig.uplinkTeamingPolicy,
pg_conf['teaming']) | python | def _apply_dvportgroup_config(pg_name, pg_spec, pg_conf):
'''
Applies the values in conf to a distributed portgroup spec
pg_name
The name of the portgroup
pg_spec
The vim.DVPortgroupConfigSpec to apply the config to
pg_conf
The portgroup config
'''
log.trace('Building portgroup\'s \'%s\' spec', pg_name)
if 'name' in pg_conf:
pg_spec.name = pg_conf['name']
if 'description' in pg_conf:
pg_spec.description = pg_conf['description']
if 'num_ports' in pg_conf:
pg_spec.numPorts = pg_conf['num_ports']
if 'type' in pg_conf:
pg_spec.type = pg_conf['type']
if not pg_spec.defaultPortConfig:
for prop in ['vlan_id', 'out_shaping', 'security_policy', 'teaming']:
if prop in pg_conf:
pg_spec.defaultPortConfig = vim.VMwareDVSPortSetting()
if 'vlan_id' in pg_conf:
pg_spec.defaultPortConfig.vlan = \
vim.VmwareDistributedVirtualSwitchVlanIdSpec()
pg_spec.defaultPortConfig.vlan.vlanId = pg_conf['vlan_id']
if 'out_shaping' in pg_conf:
if not pg_spec.defaultPortConfig.outShapingPolicy:
pg_spec.defaultPortConfig.outShapingPolicy = \
vim.DVSTrafficShapingPolicy()
_apply_dvportgroup_out_shaping(
pg_name, pg_spec.defaultPortConfig.outShapingPolicy,
pg_conf['out_shaping'])
if 'security_policy' in pg_conf:
if not pg_spec.defaultPortConfig.securityPolicy:
pg_spec.defaultPortConfig.securityPolicy = \
vim.DVSSecurityPolicy()
_apply_dvportgroup_security_policy(
pg_name, pg_spec.defaultPortConfig.securityPolicy,
pg_conf['security_policy'])
if 'teaming' in pg_conf:
if not pg_spec.defaultPortConfig.uplinkTeamingPolicy:
pg_spec.defaultPortConfig.uplinkTeamingPolicy = \
vim.VmwareUplinkPortTeamingPolicy()
_apply_dvportgroup_teaming(
pg_name, pg_spec.defaultPortConfig.uplinkTeamingPolicy,
pg_conf['teaming']) | [
"def",
"_apply_dvportgroup_config",
"(",
"pg_name",
",",
"pg_spec",
",",
"pg_conf",
")",
":",
"log",
".",
"trace",
"(",
"'Building portgroup\\'s \\'%s\\' spec'",
",",
"pg_name",
")",
"if",
"'name'",
"in",
"pg_conf",
":",
"pg_spec",
".",
"name",
"=",
"pg_conf",
... | Applies the values in conf to a distributed portgroup spec
pg_name
The name of the portgroup
pg_spec
The vim.DVPortgroupConfigSpec to apply the config to
pg_conf
The portgroup config | [
"Applies",
"the",
"values",
"in",
"conf",
"to",
"a",
"distributed",
"portgroup",
"spec"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4413-L4464 | train |
saltstack/salt | salt/modules/vsphere.py | create_dvportgroup | def create_dvportgroup(portgroup_dict, portgroup_name, dvs,
service_instance=None):
'''
Creates a distributed virtual portgroup.
Note: The ``portgroup_name`` param will override any name already set
in ``portgroup_dict``.
portgroup_dict
Dictionary with the config values the portgroup should be created with
(example in salt.states.dvs).
portgroup_name
Name of the portgroup to be created.
dvs
Name of the DVS that will contain the portgroup.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_dvportgroup portgroup_dict=<dict>
portgroup_name=pg1 dvs=dvs1
'''
log.trace('Creating portgroup\'%s\' in dvs \'%s\' '
'with dict = %s', portgroup_name, dvs, portgroup_dict)
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' was not '
'retrieved'.format(dvs))
# Make the name of the dvportgroup consistent with the parameter
portgroup_dict['name'] = portgroup_name
spec = vim.DVPortgroupConfigSpec()
_apply_dvportgroup_config(portgroup_name, spec, portgroup_dict)
salt.utils.vmware.create_dvportgroup(dvs_refs[0], spec)
return True | python | def create_dvportgroup(portgroup_dict, portgroup_name, dvs,
service_instance=None):
'''
Creates a distributed virtual portgroup.
Note: The ``portgroup_name`` param will override any name already set
in ``portgroup_dict``.
portgroup_dict
Dictionary with the config values the portgroup should be created with
(example in salt.states.dvs).
portgroup_name
Name of the portgroup to be created.
dvs
Name of the DVS that will contain the portgroup.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_dvportgroup portgroup_dict=<dict>
portgroup_name=pg1 dvs=dvs1
'''
log.trace('Creating portgroup\'%s\' in dvs \'%s\' '
'with dict = %s', portgroup_name, dvs, portgroup_dict)
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' was not '
'retrieved'.format(dvs))
# Make the name of the dvportgroup consistent with the parameter
portgroup_dict['name'] = portgroup_name
spec = vim.DVPortgroupConfigSpec()
_apply_dvportgroup_config(portgroup_name, spec, portgroup_dict)
salt.utils.vmware.create_dvportgroup(dvs_refs[0], spec)
return True | [
"def",
"create_dvportgroup",
"(",
"portgroup_dict",
",",
"portgroup_name",
",",
"dvs",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'Creating portgroup\\'%s\\' in dvs \\'%s\\' '",
"'with dict = %s'",
",",
"portgroup_name",
",",
"dvs",
","... | Creates a distributed virtual portgroup.
Note: The ``portgroup_name`` param will override any name already set
in ``portgroup_dict``.
portgroup_dict
Dictionary with the config values the portgroup should be created with
(example in salt.states.dvs).
portgroup_name
Name of the portgroup to be created.
dvs
Name of the DVS that will contain the portgroup.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_dvportgroup portgroup_dict=<dict>
portgroup_name=pg1 dvs=dvs1 | [
"Creates",
"a",
"distributed",
"virtual",
"portgroup",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4470-L4515 | train |
saltstack/salt | salt/modules/vsphere.py | update_dvportgroup | def update_dvportgroup(portgroup_dict, portgroup, dvs, service_instance=True):
'''
Updates a distributed virtual portgroup.
portgroup_dict
Dictionary with the values the portgroup should be update with
(example in salt.states.dvs).
portgroup
Name of the portgroup to be updated.
dvs
Name of the DVS containing the portgroups.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.update_dvportgroup portgroup_dict=<dict>
portgroup=pg1
salt '*' vsphere.update_dvportgroup portgroup_dict=<dict>
portgroup=pg1 dvs=dvs1
'''
log.trace('Updating portgroup\'%s\' in dvs \'%s\' '
'with dict = %s', portgroup, dvs, portgroup_dict)
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' was not '
'retrieved'.format(dvs))
pg_refs = salt.utils.vmware.get_dvportgroups(dvs_refs[0],
portgroup_names=[portgroup])
if not pg_refs:
raise VMwareObjectRetrievalError('Portgroup \'{0}\' was not '
'retrieved'.format(portgroup))
pg_props = salt.utils.vmware.get_properties_of_managed_object(pg_refs[0],
['config'])
spec = vim.DVPortgroupConfigSpec()
# Copy existing properties in spec
for prop in ['autoExpand', 'configVersion', 'defaultPortConfig',
'description', 'name', 'numPorts', 'policy', 'portNameFormat',
'scope', 'type', 'vendorSpecificConfig']:
setattr(spec, prop, getattr(pg_props['config'], prop))
_apply_dvportgroup_config(portgroup, spec, portgroup_dict)
salt.utils.vmware.update_dvportgroup(pg_refs[0], spec)
return True | python | def update_dvportgroup(portgroup_dict, portgroup, dvs, service_instance=True):
'''
Updates a distributed virtual portgroup.
portgroup_dict
Dictionary with the values the portgroup should be update with
(example in salt.states.dvs).
portgroup
Name of the portgroup to be updated.
dvs
Name of the DVS containing the portgroups.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.update_dvportgroup portgroup_dict=<dict>
portgroup=pg1
salt '*' vsphere.update_dvportgroup portgroup_dict=<dict>
portgroup=pg1 dvs=dvs1
'''
log.trace('Updating portgroup\'%s\' in dvs \'%s\' '
'with dict = %s', portgroup, dvs, portgroup_dict)
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' was not '
'retrieved'.format(dvs))
pg_refs = salt.utils.vmware.get_dvportgroups(dvs_refs[0],
portgroup_names=[portgroup])
if not pg_refs:
raise VMwareObjectRetrievalError('Portgroup \'{0}\' was not '
'retrieved'.format(portgroup))
pg_props = salt.utils.vmware.get_properties_of_managed_object(pg_refs[0],
['config'])
spec = vim.DVPortgroupConfigSpec()
# Copy existing properties in spec
for prop in ['autoExpand', 'configVersion', 'defaultPortConfig',
'description', 'name', 'numPorts', 'policy', 'portNameFormat',
'scope', 'type', 'vendorSpecificConfig']:
setattr(spec, prop, getattr(pg_props['config'], prop))
_apply_dvportgroup_config(portgroup, spec, portgroup_dict)
salt.utils.vmware.update_dvportgroup(pg_refs[0], spec)
return True | [
"def",
"update_dvportgroup",
"(",
"portgroup_dict",
",",
"portgroup",
",",
"dvs",
",",
"service_instance",
"=",
"True",
")",
":",
"log",
".",
"trace",
"(",
"'Updating portgroup\\'%s\\' in dvs \\'%s\\' '",
"'with dict = %s'",
",",
"portgroup",
",",
"dvs",
",",
"portg... | Updates a distributed virtual portgroup.
portgroup_dict
Dictionary with the values the portgroup should be update with
(example in salt.states.dvs).
portgroup
Name of the portgroup to be updated.
dvs
Name of the DVS containing the portgroups.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.update_dvportgroup portgroup_dict=<dict>
portgroup=pg1
salt '*' vsphere.update_dvportgroup portgroup_dict=<dict>
portgroup=pg1 dvs=dvs1 | [
"Updates",
"a",
"distributed",
"virtual",
"portgroup",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4521-L4575 | train |
saltstack/salt | salt/modules/vsphere.py | remove_dvportgroup | def remove_dvportgroup(portgroup, dvs, service_instance=None):
'''
Removes a distributed virtual portgroup.
portgroup
Name of the portgroup to be removed.
dvs
Name of the DVS containing the portgroups.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.remove_dvportgroup portgroup=pg1 dvs=dvs1
'''
log.trace('Removing portgroup\'%s\' in dvs \'%s\'', portgroup, dvs)
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' was not '
'retrieved'.format(dvs))
pg_refs = salt.utils.vmware.get_dvportgroups(dvs_refs[0],
portgroup_names=[portgroup])
if not pg_refs:
raise VMwareObjectRetrievalError('Portgroup \'{0}\' was not '
'retrieved'.format(portgroup))
salt.utils.vmware.remove_dvportgroup(pg_refs[0])
return True | python | def remove_dvportgroup(portgroup, dvs, service_instance=None):
'''
Removes a distributed virtual portgroup.
portgroup
Name of the portgroup to be removed.
dvs
Name of the DVS containing the portgroups.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.remove_dvportgroup portgroup=pg1 dvs=dvs1
'''
log.trace('Removing portgroup\'%s\' in dvs \'%s\'', portgroup, dvs)
proxy_type = get_proxy_type()
if proxy_type == 'esxdatacenter':
datacenter = __salt__['esxdatacenter.get_details']()['datacenter']
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == 'esxcluster':
datacenter = __salt__['esxcluster.get_details']()['datacenter']
dc_ref = salt.utils.vmware.get_datacenter(service_instance, datacenter)
dvs_refs = salt.utils.vmware.get_dvss(dc_ref, dvs_names=[dvs])
if not dvs_refs:
raise VMwareObjectRetrievalError('DVS \'{0}\' was not '
'retrieved'.format(dvs))
pg_refs = salt.utils.vmware.get_dvportgroups(dvs_refs[0],
portgroup_names=[portgroup])
if not pg_refs:
raise VMwareObjectRetrievalError('Portgroup \'{0}\' was not '
'retrieved'.format(portgroup))
salt.utils.vmware.remove_dvportgroup(pg_refs[0])
return True | [
"def",
"remove_dvportgroup",
"(",
"portgroup",
",",
"dvs",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'Removing portgroup\\'%s\\' in dvs \\'%s\\''",
",",
"portgroup",
",",
"dvs",
")",
"proxy_type",
"=",
"get_proxy_type",
"(",
")",
... | Removes a distributed virtual portgroup.
portgroup
Name of the portgroup to be removed.
dvs
Name of the DVS containing the portgroups.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.remove_dvportgroup portgroup=pg1 dvs=dvs1 | [
"Removes",
"a",
"distributed",
"virtual",
"portgroup",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4581-L4617 | train |
saltstack/salt | salt/modules/vsphere.py | _get_policy_dict | def _get_policy_dict(policy):
'''Returns a dictionary representation of a policy'''
profile_dict = {'name': policy.name,
'description': policy.description,
'resource_type': policy.resourceType.resourceType}
subprofile_dicts = []
if isinstance(policy, pbm.profile.CapabilityBasedProfile) and \
isinstance(policy.constraints,
pbm.profile.SubProfileCapabilityConstraints):
for subprofile in policy.constraints.subProfiles:
subprofile_dict = {'name': subprofile.name,
'force_provision': subprofile.forceProvision}
cap_dicts = []
for cap in subprofile.capability:
cap_dict = {'namespace': cap.id.namespace,
'id': cap.id.id}
# We assume there is one constraint with one value set
val = cap.constraint[0].propertyInstance[0].value
if isinstance(val, pbm.capability.types.Range):
val_dict = {'type': 'range',
'min': val.min,
'max': val.max}
elif isinstance(val, pbm.capability.types.DiscreteSet):
val_dict = {'type': 'set',
'values': val.values}
else:
val_dict = {'type': 'scalar',
'value': val}
cap_dict['setting'] = val_dict
cap_dicts.append(cap_dict)
subprofile_dict['capabilities'] = cap_dicts
subprofile_dicts.append(subprofile_dict)
profile_dict['subprofiles'] = subprofile_dicts
return profile_dict | python | def _get_policy_dict(policy):
'''Returns a dictionary representation of a policy'''
profile_dict = {'name': policy.name,
'description': policy.description,
'resource_type': policy.resourceType.resourceType}
subprofile_dicts = []
if isinstance(policy, pbm.profile.CapabilityBasedProfile) and \
isinstance(policy.constraints,
pbm.profile.SubProfileCapabilityConstraints):
for subprofile in policy.constraints.subProfiles:
subprofile_dict = {'name': subprofile.name,
'force_provision': subprofile.forceProvision}
cap_dicts = []
for cap in subprofile.capability:
cap_dict = {'namespace': cap.id.namespace,
'id': cap.id.id}
# We assume there is one constraint with one value set
val = cap.constraint[0].propertyInstance[0].value
if isinstance(val, pbm.capability.types.Range):
val_dict = {'type': 'range',
'min': val.min,
'max': val.max}
elif isinstance(val, pbm.capability.types.DiscreteSet):
val_dict = {'type': 'set',
'values': val.values}
else:
val_dict = {'type': 'scalar',
'value': val}
cap_dict['setting'] = val_dict
cap_dicts.append(cap_dict)
subprofile_dict['capabilities'] = cap_dicts
subprofile_dicts.append(subprofile_dict)
profile_dict['subprofiles'] = subprofile_dicts
return profile_dict | [
"def",
"_get_policy_dict",
"(",
"policy",
")",
":",
"profile_dict",
"=",
"{",
"'name'",
":",
"policy",
".",
"name",
",",
"'description'",
":",
"policy",
".",
"description",
",",
"'resource_type'",
":",
"policy",
".",
"resourceType",
".",
"resourceType",
"}",
... | Returns a dictionary representation of a policy | [
"Returns",
"a",
"dictionary",
"representation",
"of",
"a",
"policy"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4620-L4654 | train |
saltstack/salt | salt/modules/vsphere.py | list_storage_policies | def list_storage_policies(policy_names=None, service_instance=None):
'''
Returns a list of storage policies.
policy_names
Names of policies to list. If None, all policies are listed.
Default is None.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_storage_policies
salt '*' vsphere.list_storage_policy policy_names=[policy_name]
'''
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
if not policy_names:
policies = salt.utils.pbm.get_storage_policies(profile_manager,
get_all_policies=True)
else:
policies = salt.utils.pbm.get_storage_policies(profile_manager,
policy_names)
return [_get_policy_dict(p) for p in policies] | python | def list_storage_policies(policy_names=None, service_instance=None):
'''
Returns a list of storage policies.
policy_names
Names of policies to list. If None, all policies are listed.
Default is None.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_storage_policies
salt '*' vsphere.list_storage_policy policy_names=[policy_name]
'''
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
if not policy_names:
policies = salt.utils.pbm.get_storage_policies(profile_manager,
get_all_policies=True)
else:
policies = salt.utils.pbm.get_storage_policies(profile_manager,
policy_names)
return [_get_policy_dict(p) for p in policies] | [
"def",
"list_storage_policies",
"(",
"policy_names",
"=",
"None",
",",
"service_instance",
"=",
"None",
")",
":",
"profile_manager",
"=",
"salt",
".",
"utils",
".",
"pbm",
".",
"get_profile_manager",
"(",
"service_instance",
")",
"if",
"not",
"policy_names",
":"... | Returns a list of storage policies.
policy_names
Names of policies to list. If None, all policies are listed.
Default is None.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_storage_policies
salt '*' vsphere.list_storage_policy policy_names=[policy_name] | [
"Returns",
"a",
"list",
"of",
"storage",
"policies",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4660-L4685 | train |
saltstack/salt | salt/modules/vsphere.py | list_default_vsan_policy | def list_default_vsan_policy(service_instance=None):
'''
Returns the default vsan storage policy.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_storage_policies
salt '*' vsphere.list_storage_policy policy_names=[policy_name]
'''
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
policies = salt.utils.pbm.get_storage_policies(profile_manager,
get_all_policies=True)
def_policies = [p for p in policies
if p.systemCreatedProfileType == 'VsanDefaultProfile']
if not def_policies:
raise VMwareObjectRetrievalError('Default VSAN policy was not '
'retrieved')
return _get_policy_dict(def_policies[0]) | python | def list_default_vsan_policy(service_instance=None):
'''
Returns the default vsan storage policy.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_storage_policies
salt '*' vsphere.list_storage_policy policy_names=[policy_name]
'''
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
policies = salt.utils.pbm.get_storage_policies(profile_manager,
get_all_policies=True)
def_policies = [p for p in policies
if p.systemCreatedProfileType == 'VsanDefaultProfile']
if not def_policies:
raise VMwareObjectRetrievalError('Default VSAN policy was not '
'retrieved')
return _get_policy_dict(def_policies[0]) | [
"def",
"list_default_vsan_policy",
"(",
"service_instance",
"=",
"None",
")",
":",
"profile_manager",
"=",
"salt",
".",
"utils",
".",
"pbm",
".",
"get_profile_manager",
"(",
"service_instance",
")",
"policies",
"=",
"salt",
".",
"utils",
".",
"pbm",
".",
"get_... | Returns the default vsan storage policy.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_storage_policies
salt '*' vsphere.list_storage_policy policy_names=[policy_name] | [
"Returns",
"the",
"default",
"vsan",
"storage",
"policy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4691-L4713 | train |
saltstack/salt | salt/modules/vsphere.py | list_capability_definitions | def list_capability_definitions(service_instance=None):
'''
Returns a list of the metadata of all capabilities in the vCenter.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_capabilities
'''
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
ret_list = [_get_capability_definition_dict(c) for c in
salt.utils.pbm.get_capability_definitions(profile_manager)]
return ret_list | python | def list_capability_definitions(service_instance=None):
'''
Returns a list of the metadata of all capabilities in the vCenter.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_capabilities
'''
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
ret_list = [_get_capability_definition_dict(c) for c in
salt.utils.pbm.get_capability_definitions(profile_manager)]
return ret_list | [
"def",
"list_capability_definitions",
"(",
"service_instance",
"=",
"None",
")",
":",
"profile_manager",
"=",
"salt",
".",
"utils",
".",
"pbm",
".",
"get_profile_manager",
"(",
"service_instance",
")",
"ret_list",
"=",
"[",
"_get_capability_definition_dict",
"(",
"c... | Returns a list of the metadata of all capabilities in the vCenter.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_capabilities | [
"Returns",
"a",
"list",
"of",
"the",
"metadata",
"of",
"all",
"capabilities",
"in",
"the",
"vCenter",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4730-L4745 | train |
saltstack/salt | salt/modules/vsphere.py | _apply_policy_config | def _apply_policy_config(policy_spec, policy_dict):
'''Applies a policy dictionary to a policy spec'''
log.trace('policy_dict = %s', policy_dict)
if policy_dict.get('name'):
policy_spec.name = policy_dict['name']
if policy_dict.get('description'):
policy_spec.description = policy_dict['description']
if policy_dict.get('subprofiles'):
# Incremental changes to subprofiles and capabilities are not
# supported because they would complicate updates too much
# The whole configuration of all sub-profiles is expected and applied
policy_spec.constraints = pbm.profile.SubProfileCapabilityConstraints()
subprofiles = []
for subprofile_dict in policy_dict['subprofiles']:
subprofile_spec = \
pbm.profile.SubProfileCapabilityConstraints.SubProfile(
name=subprofile_dict['name'])
cap_specs = []
if subprofile_dict.get('force_provision'):
subprofile_spec.forceProvision = \
subprofile_dict['force_provision']
for cap_dict in subprofile_dict['capabilities']:
prop_inst_spec = pbm.capability.PropertyInstance(
id=cap_dict['id']
)
setting_type = cap_dict['setting']['type']
if setting_type == 'set':
prop_inst_spec.value = pbm.capability.types.DiscreteSet()
prop_inst_spec.value.values = cap_dict['setting']['values']
elif setting_type == 'range':
prop_inst_spec.value = pbm.capability.types.Range()
prop_inst_spec.value.max = cap_dict['setting']['max']
prop_inst_spec.value.min = cap_dict['setting']['min']
elif setting_type == 'scalar':
prop_inst_spec.value = cap_dict['setting']['value']
cap_spec = pbm.capability.CapabilityInstance(
id=pbm.capability.CapabilityMetadata.UniqueId(
id=cap_dict['id'],
namespace=cap_dict['namespace']),
constraint=[pbm.capability.ConstraintInstance(
propertyInstance=[prop_inst_spec])])
cap_specs.append(cap_spec)
subprofile_spec.capability = cap_specs
subprofiles.append(subprofile_spec)
policy_spec.constraints.subProfiles = subprofiles
log.trace('updated policy_spec = %s', policy_spec)
return policy_spec | python | def _apply_policy_config(policy_spec, policy_dict):
'''Applies a policy dictionary to a policy spec'''
log.trace('policy_dict = %s', policy_dict)
if policy_dict.get('name'):
policy_spec.name = policy_dict['name']
if policy_dict.get('description'):
policy_spec.description = policy_dict['description']
if policy_dict.get('subprofiles'):
# Incremental changes to subprofiles and capabilities are not
# supported because they would complicate updates too much
# The whole configuration of all sub-profiles is expected and applied
policy_spec.constraints = pbm.profile.SubProfileCapabilityConstraints()
subprofiles = []
for subprofile_dict in policy_dict['subprofiles']:
subprofile_spec = \
pbm.profile.SubProfileCapabilityConstraints.SubProfile(
name=subprofile_dict['name'])
cap_specs = []
if subprofile_dict.get('force_provision'):
subprofile_spec.forceProvision = \
subprofile_dict['force_provision']
for cap_dict in subprofile_dict['capabilities']:
prop_inst_spec = pbm.capability.PropertyInstance(
id=cap_dict['id']
)
setting_type = cap_dict['setting']['type']
if setting_type == 'set':
prop_inst_spec.value = pbm.capability.types.DiscreteSet()
prop_inst_spec.value.values = cap_dict['setting']['values']
elif setting_type == 'range':
prop_inst_spec.value = pbm.capability.types.Range()
prop_inst_spec.value.max = cap_dict['setting']['max']
prop_inst_spec.value.min = cap_dict['setting']['min']
elif setting_type == 'scalar':
prop_inst_spec.value = cap_dict['setting']['value']
cap_spec = pbm.capability.CapabilityInstance(
id=pbm.capability.CapabilityMetadata.UniqueId(
id=cap_dict['id'],
namespace=cap_dict['namespace']),
constraint=[pbm.capability.ConstraintInstance(
propertyInstance=[prop_inst_spec])])
cap_specs.append(cap_spec)
subprofile_spec.capability = cap_specs
subprofiles.append(subprofile_spec)
policy_spec.constraints.subProfiles = subprofiles
log.trace('updated policy_spec = %s', policy_spec)
return policy_spec | [
"def",
"_apply_policy_config",
"(",
"policy_spec",
",",
"policy_dict",
")",
":",
"log",
".",
"trace",
"(",
"'policy_dict = %s'",
",",
"policy_dict",
")",
"if",
"policy_dict",
".",
"get",
"(",
"'name'",
")",
":",
"policy_spec",
".",
"name",
"=",
"policy_dict",
... | Applies a policy dictionary to a policy spec | [
"Applies",
"a",
"policy",
"dictionary",
"to",
"a",
"policy",
"spec"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4748-L4794 | train |
saltstack/salt | salt/modules/vsphere.py | create_storage_policy | def create_storage_policy(policy_name, policy_dict, service_instance=None):
'''
Creates a storage policy.
Supported capability types: scalar, set, range.
policy_name
Name of the policy to create.
The value of the argument will override any existing name in
``policy_dict``.
policy_dict
Dictionary containing the changes to apply to the policy.
(example in salt.states.pbm)
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_storage_policy policy_name='policy name'
policy_dict="$policy_dict"
'''
log.trace('create storage policy \'%s\', dict = %s', policy_name, policy_dict)
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
policy_create_spec = pbm.profile.CapabilityBasedProfileCreateSpec()
# Hardcode the storage profile resource type
policy_create_spec.resourceType = pbm.profile.ResourceType(
resourceType=pbm.profile.ResourceTypeEnum.STORAGE)
# Set name argument
policy_dict['name'] = policy_name
log.trace('Setting policy values in policy_update_spec')
_apply_policy_config(policy_create_spec, policy_dict)
salt.utils.pbm.create_storage_policy(profile_manager, policy_create_spec)
return {'create_storage_policy': True} | python | def create_storage_policy(policy_name, policy_dict, service_instance=None):
'''
Creates a storage policy.
Supported capability types: scalar, set, range.
policy_name
Name of the policy to create.
The value of the argument will override any existing name in
``policy_dict``.
policy_dict
Dictionary containing the changes to apply to the policy.
(example in salt.states.pbm)
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_storage_policy policy_name='policy name'
policy_dict="$policy_dict"
'''
log.trace('create storage policy \'%s\', dict = %s', policy_name, policy_dict)
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
policy_create_spec = pbm.profile.CapabilityBasedProfileCreateSpec()
# Hardcode the storage profile resource type
policy_create_spec.resourceType = pbm.profile.ResourceType(
resourceType=pbm.profile.ResourceTypeEnum.STORAGE)
# Set name argument
policy_dict['name'] = policy_name
log.trace('Setting policy values in policy_update_spec')
_apply_policy_config(policy_create_spec, policy_dict)
salt.utils.pbm.create_storage_policy(profile_manager, policy_create_spec)
return {'create_storage_policy': True} | [
"def",
"create_storage_policy",
"(",
"policy_name",
",",
"policy_dict",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'create storage policy \\'%s\\', dict = %s'",
",",
"policy_name",
",",
"policy_dict",
")",
"profile_manager",
"=",
"salt"... | Creates a storage policy.
Supported capability types: scalar, set, range.
policy_name
Name of the policy to create.
The value of the argument will override any existing name in
``policy_dict``.
policy_dict
Dictionary containing the changes to apply to the policy.
(example in salt.states.pbm)
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_storage_policy policy_name='policy name'
policy_dict="$policy_dict" | [
"Creates",
"a",
"storage",
"policy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4800-L4835 | train |
saltstack/salt | salt/modules/vsphere.py | update_storage_policy | def update_storage_policy(policy, policy_dict, service_instance=None):
'''
Updates a storage policy.
Supported capability types: scalar, set, range.
policy
Name of the policy to update.
policy_dict
Dictionary containing the changes to apply to the policy.
(example in salt.states.pbm)
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.update_storage_policy policy='policy name'
policy_dict="$policy_dict"
'''
log.trace('updating storage policy, dict = %s', policy_dict)
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
policies = salt.utils.pbm.get_storage_policies(profile_manager, [policy])
if not policies:
raise VMwareObjectRetrievalError('Policy \'{0}\' was not found'
''.format(policy))
policy_ref = policies[0]
policy_update_spec = pbm.profile.CapabilityBasedProfileUpdateSpec()
log.trace('Setting policy values in policy_update_spec')
for prop in ['description', 'constraints']:
setattr(policy_update_spec, prop, getattr(policy_ref, prop))
_apply_policy_config(policy_update_spec, policy_dict)
salt.utils.pbm.update_storage_policy(profile_manager, policy_ref,
policy_update_spec)
return {'update_storage_policy': True} | python | def update_storage_policy(policy, policy_dict, service_instance=None):
'''
Updates a storage policy.
Supported capability types: scalar, set, range.
policy
Name of the policy to update.
policy_dict
Dictionary containing the changes to apply to the policy.
(example in salt.states.pbm)
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.update_storage_policy policy='policy name'
policy_dict="$policy_dict"
'''
log.trace('updating storage policy, dict = %s', policy_dict)
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
policies = salt.utils.pbm.get_storage_policies(profile_manager, [policy])
if not policies:
raise VMwareObjectRetrievalError('Policy \'{0}\' was not found'
''.format(policy))
policy_ref = policies[0]
policy_update_spec = pbm.profile.CapabilityBasedProfileUpdateSpec()
log.trace('Setting policy values in policy_update_spec')
for prop in ['description', 'constraints']:
setattr(policy_update_spec, prop, getattr(policy_ref, prop))
_apply_policy_config(policy_update_spec, policy_dict)
salt.utils.pbm.update_storage_policy(profile_manager, policy_ref,
policy_update_spec)
return {'update_storage_policy': True} | [
"def",
"update_storage_policy",
"(",
"policy",
",",
"policy_dict",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'updating storage policy, dict = %s'",
",",
"policy_dict",
")",
"profile_manager",
"=",
"salt",
".",
"utils",
".",
"pbm",
... | Updates a storage policy.
Supported capability types: scalar, set, range.
policy
Name of the policy to update.
policy_dict
Dictionary containing the changes to apply to the policy.
(example in salt.states.pbm)
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.update_storage_policy policy='policy name'
policy_dict="$policy_dict" | [
"Updates",
"a",
"storage",
"policy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4841-L4877 | train |
saltstack/salt | salt/modules/vsphere.py | list_default_storage_policy_of_datastore | def list_default_storage_policy_of_datastore(datastore, service_instance=None):
'''
Returns a list of datastores assign the the storage policies.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_default_storage_policy_of_datastore datastore=ds1
'''
log.trace('Listing the default storage policy of datastore \'%s\'', datastore)
# Find datastore
target_ref = _get_proxy_target(service_instance)
ds_refs = salt.utils.vmware.get_datastores(service_instance, target_ref,
datastore_names=[datastore])
if not ds_refs:
raise VMwareObjectRetrievalError('Datastore \'{0}\' was not '
'found'.format(datastore))
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
policy = salt.utils.pbm.get_default_storage_policy_of_datastore(
profile_manager, ds_refs[0])
return _get_policy_dict(policy) | python | def list_default_storage_policy_of_datastore(datastore, service_instance=None):
'''
Returns a list of datastores assign the the storage policies.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_default_storage_policy_of_datastore datastore=ds1
'''
log.trace('Listing the default storage policy of datastore \'%s\'', datastore)
# Find datastore
target_ref = _get_proxy_target(service_instance)
ds_refs = salt.utils.vmware.get_datastores(service_instance, target_ref,
datastore_names=[datastore])
if not ds_refs:
raise VMwareObjectRetrievalError('Datastore \'{0}\' was not '
'found'.format(datastore))
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
policy = salt.utils.pbm.get_default_storage_policy_of_datastore(
profile_manager, ds_refs[0])
return _get_policy_dict(policy) | [
"def",
"list_default_storage_policy_of_datastore",
"(",
"datastore",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'Listing the default storage policy of datastore \\'%s\\''",
",",
"datastore",
")",
"# Find datastore",
"target_ref",
"=",
"_get_p... | Returns a list of datastores assign the the storage policies.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_default_storage_policy_of_datastore datastore=ds1 | [
"Returns",
"a",
"list",
"of",
"datastores",
"assign",
"the",
"the",
"storage",
"policies",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4883-L4911 | train |
saltstack/salt | salt/modules/vsphere.py | assign_default_storage_policy_to_datastore | def assign_default_storage_policy_to_datastore(policy, datastore,
service_instance=None):
'''
Assigns a storage policy as the default policy to a datastore.
policy
Name of the policy to assign.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.assign_storage_policy_to_datastore
policy='policy name' datastore=ds1
'''
log.trace('Assigning policy %s to datastore %s', policy, datastore)
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
# Find policy
policies = salt.utils.pbm.get_storage_policies(profile_manager, [policy])
if not policies:
raise VMwareObjectRetrievalError('Policy \'{0}\' was not found'
''.format(policy))
policy_ref = policies[0]
# Find datastore
target_ref = _get_proxy_target(service_instance)
ds_refs = salt.utils.vmware.get_datastores(service_instance, target_ref,
datastore_names=[datastore])
if not ds_refs:
raise VMwareObjectRetrievalError('Datastore \'{0}\' was not '
'found'.format(datastore))
ds_ref = ds_refs[0]
salt.utils.pbm.assign_default_storage_policy_to_datastore(
profile_manager, policy_ref, ds_ref)
return True | python | def assign_default_storage_policy_to_datastore(policy, datastore,
service_instance=None):
'''
Assigns a storage policy as the default policy to a datastore.
policy
Name of the policy to assign.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.assign_storage_policy_to_datastore
policy='policy name' datastore=ds1
'''
log.trace('Assigning policy %s to datastore %s', policy, datastore)
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
# Find policy
policies = salt.utils.pbm.get_storage_policies(profile_manager, [policy])
if not policies:
raise VMwareObjectRetrievalError('Policy \'{0}\' was not found'
''.format(policy))
policy_ref = policies[0]
# Find datastore
target_ref = _get_proxy_target(service_instance)
ds_refs = salt.utils.vmware.get_datastores(service_instance, target_ref,
datastore_names=[datastore])
if not ds_refs:
raise VMwareObjectRetrievalError('Datastore \'{0}\' was not '
'found'.format(datastore))
ds_ref = ds_refs[0]
salt.utils.pbm.assign_default_storage_policy_to_datastore(
profile_manager, policy_ref, ds_ref)
return True | [
"def",
"assign_default_storage_policy_to_datastore",
"(",
"policy",
",",
"datastore",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'Assigning policy %s to datastore %s'",
",",
"policy",
",",
"datastore",
")",
"profile_manager",
"=",
"salt... | Assigns a storage policy as the default policy to a datastore.
policy
Name of the policy to assign.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.assign_storage_policy_to_datastore
policy='policy name' datastore=ds1 | [
"Assigns",
"a",
"storage",
"policy",
"as",
"the",
"default",
"policy",
"to",
"a",
"datastore",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4917-L4957 | train |
saltstack/salt | salt/modules/vsphere.py | list_datacenters_via_proxy | def list_datacenters_via_proxy(datacenter_names=None, service_instance=None):
'''
Returns a list of dict representations of VMware datacenters.
Connection is done via the proxy details.
Supported proxies: esxdatacenter
datacenter_names
List of datacenter names.
Default is None.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_datacenters_via_proxy
salt '*' vsphere.list_datacenters_via_proxy dc1
salt '*' vsphere.list_datacenters_via_proxy dc1,dc2
salt '*' vsphere.list_datacenters_via_proxy datacenter_names=[dc1, dc2]
'''
if not datacenter_names:
dc_refs = salt.utils.vmware.get_datacenters(service_instance,
get_all_datacenters=True)
else:
dc_refs = salt.utils.vmware.get_datacenters(service_instance,
datacenter_names)
return [{'name': salt.utils.vmware.get_managed_object_name(dc_ref)}
for dc_ref in dc_refs] | python | def list_datacenters_via_proxy(datacenter_names=None, service_instance=None):
'''
Returns a list of dict representations of VMware datacenters.
Connection is done via the proxy details.
Supported proxies: esxdatacenter
datacenter_names
List of datacenter names.
Default is None.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_datacenters_via_proxy
salt '*' vsphere.list_datacenters_via_proxy dc1
salt '*' vsphere.list_datacenters_via_proxy dc1,dc2
salt '*' vsphere.list_datacenters_via_proxy datacenter_names=[dc1, dc2]
'''
if not datacenter_names:
dc_refs = salt.utils.vmware.get_datacenters(service_instance,
get_all_datacenters=True)
else:
dc_refs = salt.utils.vmware.get_datacenters(service_instance,
datacenter_names)
return [{'name': salt.utils.vmware.get_managed_object_name(dc_ref)}
for dc_ref in dc_refs] | [
"def",
"list_datacenters_via_proxy",
"(",
"datacenter_names",
"=",
"None",
",",
"service_instance",
"=",
"None",
")",
":",
"if",
"not",
"datacenter_names",
":",
"dc_refs",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_datacenters",
"(",
"service_instance",
... | Returns a list of dict representations of VMware datacenters.
Connection is done via the proxy details.
Supported proxies: esxdatacenter
datacenter_names
List of datacenter names.
Default is None.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_datacenters_via_proxy
salt '*' vsphere.list_datacenters_via_proxy dc1
salt '*' vsphere.list_datacenters_via_proxy dc1,dc2
salt '*' vsphere.list_datacenters_via_proxy datacenter_names=[dc1, dc2] | [
"Returns",
"a",
"list",
"of",
"dict",
"representations",
"of",
"VMware",
"datacenters",
".",
"Connection",
"is",
"done",
"via",
"the",
"proxy",
"details",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L4963-L4996 | train |
saltstack/salt | salt/modules/vsphere.py | create_datacenter | def create_datacenter(datacenter_name, service_instance=None):
'''
Creates a datacenter.
Supported proxies: esxdatacenter
datacenter_name
The datacenter name
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_datacenter dc1
'''
salt.utils.vmware.create_datacenter(service_instance, datacenter_name)
return {'create_datacenter': True} | python | def create_datacenter(datacenter_name, service_instance=None):
'''
Creates a datacenter.
Supported proxies: esxdatacenter
datacenter_name
The datacenter name
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_datacenter dc1
'''
salt.utils.vmware.create_datacenter(service_instance, datacenter_name)
return {'create_datacenter': True} | [
"def",
"create_datacenter",
"(",
"datacenter_name",
",",
"service_instance",
"=",
"None",
")",
":",
"salt",
".",
"utils",
".",
"vmware",
".",
"create_datacenter",
"(",
"service_instance",
",",
"datacenter_name",
")",
"return",
"{",
"'create_datacenter'",
":",
"Tru... | Creates a datacenter.
Supported proxies: esxdatacenter
datacenter_name
The datacenter name
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.create_datacenter dc1 | [
"Creates",
"a",
"datacenter",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L5002-L5020 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.