repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/modules/win_system.py | get_pending_file_rename | def get_pending_file_rename():
'''
Determine whether there are pending file rename operations that require a
reboot.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if there are pending file rename operations, otherwise
``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_file_rename
'''
vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2')
key = r'SYSTEM\CurrentControlSet\Control\Session Manager'
# If any of the value names exist and have value data set,
# then a reboot is pending.
for vname in vnames:
reg_ret = __utils__['reg.read_value']('HKLM', key, vname)
if reg_ret['success']:
log.debug('Found key: %s', key)
if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'):
return True
else:
log.debug('Unable to access key: %s', key)
return False | python | def get_pending_file_rename():
'''
Determine whether there are pending file rename operations that require a
reboot.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if there are pending file rename operations, otherwise
``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_file_rename
'''
vnames = ('PendingFileRenameOperations', 'PendingFileRenameOperations2')
key = r'SYSTEM\CurrentControlSet\Control\Session Manager'
# If any of the value names exist and have value data set,
# then a reboot is pending.
for vname in vnames:
reg_ret = __utils__['reg.read_value']('HKLM', key, vname)
if reg_ret['success']:
log.debug('Found key: %s', key)
if reg_ret['vdata'] and (reg_ret['vdata'] != '(value not set)'):
return True
else:
log.debug('Unable to access key: %s', key)
return False | [
"def",
"get_pending_file_rename",
"(",
")",
":",
"vnames",
"=",
"(",
"'PendingFileRenameOperations'",
",",
"'PendingFileRenameOperations2'",
")",
"key",
"=",
"r'SYSTEM\\CurrentControlSet\\Control\\Session Manager'",
"# If any of the value names exist and have value data set,",
"# the... | Determine whether there are pending file rename operations that require a
reboot.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if there are pending file rename operations, otherwise
``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_file_rename | [
"Determine",
"whether",
"there",
"are",
"pending",
"file",
"rename",
"operations",
"that",
"require",
"a",
"reboot",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1335-L1368 | train |
saltstack/salt | salt/modules/win_system.py | get_pending_servermanager | def get_pending_servermanager():
'''
Determine whether there are pending Server Manager tasks that require a
reboot.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if there are pending Server Manager tasks, otherwise
``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_servermanager
'''
vname = 'CurrentRebootAttempts'
key = r'SOFTWARE\Microsoft\ServerManager'
# There are situations where it's possible to have '(value not set)' as
# the value data, and since an actual reboot won't be pending in that
# instance, just catch instances where we try unsuccessfully to cast as int.
reg_ret = __utils__['reg.read_value']('HKLM', key, vname)
if reg_ret['success']:
log.debug('Found key: %s', key)
try:
if int(reg_ret['vdata']) > 0:
return True
except ValueError:
pass
else:
log.debug('Unable to access key: %s', key)
return False | python | def get_pending_servermanager():
'''
Determine whether there are pending Server Manager tasks that require a
reboot.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if there are pending Server Manager tasks, otherwise
``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_servermanager
'''
vname = 'CurrentRebootAttempts'
key = r'SOFTWARE\Microsoft\ServerManager'
# There are situations where it's possible to have '(value not set)' as
# the value data, and since an actual reboot won't be pending in that
# instance, just catch instances where we try unsuccessfully to cast as int.
reg_ret = __utils__['reg.read_value']('HKLM', key, vname)
if reg_ret['success']:
log.debug('Found key: %s', key)
try:
if int(reg_ret['vdata']) > 0:
return True
except ValueError:
pass
else:
log.debug('Unable to access key: %s', key)
return False | [
"def",
"get_pending_servermanager",
"(",
")",
":",
"vname",
"=",
"'CurrentRebootAttempts'",
"key",
"=",
"r'SOFTWARE\\Microsoft\\ServerManager'",
"# There are situations where it's possible to have '(value not set)' as",
"# the value data, and since an actual reboot won't be pending in that",... | Determine whether there are pending Server Manager tasks that require a
reboot.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if there are pending Server Manager tasks, otherwise
``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_servermanager | [
"Determine",
"whether",
"there",
"are",
"pending",
"Server",
"Manager",
"tasks",
"that",
"require",
"a",
"reboot",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1371-L1407 | train |
saltstack/salt | salt/modules/win_system.py | get_pending_update | def get_pending_update():
'''
Determine whether there are pending updates that require a reboot.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if there are pending updates, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_update
'''
key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'
# So long as the registry key exists, a reboot is pending.
if __utils__['reg.key_exists']('HKLM', key):
log.debug('Key exists: %s', key)
return True
else:
log.debug('Key does not exist: %s', key)
return False | python | def get_pending_update():
'''
Determine whether there are pending updates that require a reboot.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if there are pending updates, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_update
'''
key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'
# So long as the registry key exists, a reboot is pending.
if __utils__['reg.key_exists']('HKLM', key):
log.debug('Key exists: %s', key)
return True
else:
log.debug('Key does not exist: %s', key)
return False | [
"def",
"get_pending_update",
"(",
")",
":",
"key",
"=",
"r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired'",
"# So long as the registry key exists, a reboot is pending.",
"if",
"__utils__",
"[",
"'reg.key_exists'",
"]",
"(",
"'HKLM'",
",",
... | Determine whether there are pending updates that require a reboot.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if there are pending updates, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_update | [
"Determine",
"whether",
"there",
"are",
"pending",
"updates",
"that",
"require",
"a",
"reboot",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1410-L1434 | train |
saltstack/salt | salt/modules/win_system.py | set_reboot_required_witnessed | def set_reboot_required_witnessed():
r'''
This function is used to remember that an event indicating that a reboot is
required was witnessed. This function relies on the salt-minion's ability to
create the following volatile registry key in the *HKLM* hive:
*SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data*
Because this registry key is volatile, it will not persist beyond the
current boot session. Also, in the scope of this key, the name *'Reboot
required'* will be assigned the value of *1*.
For the time being, this function is being used whenever an install
completes with exit code 3010 and can be extended where appropriate in the
future.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' system.set_reboot_required_witnessed
'''
return __utils__['reg.set_value'](
hive='HKLM',
key=MINION_VOLATILE_KEY,
volatile=True,
vname=REBOOT_REQUIRED_NAME,
vdata=1,
vtype='REG_DWORD') | python | def set_reboot_required_witnessed():
r'''
This function is used to remember that an event indicating that a reboot is
required was witnessed. This function relies on the salt-minion's ability to
create the following volatile registry key in the *HKLM* hive:
*SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data*
Because this registry key is volatile, it will not persist beyond the
current boot session. Also, in the scope of this key, the name *'Reboot
required'* will be assigned the value of *1*.
For the time being, this function is being used whenever an install
completes with exit code 3010 and can be extended where appropriate in the
future.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' system.set_reboot_required_witnessed
'''
return __utils__['reg.set_value'](
hive='HKLM',
key=MINION_VOLATILE_KEY,
volatile=True,
vname=REBOOT_REQUIRED_NAME,
vdata=1,
vtype='REG_DWORD') | [
"def",
"set_reboot_required_witnessed",
"(",
")",
":",
"return",
"__utils__",
"[",
"'reg.set_value'",
"]",
"(",
"hive",
"=",
"'HKLM'",
",",
"key",
"=",
"MINION_VOLATILE_KEY",
",",
"volatile",
"=",
"True",
",",
"vname",
"=",
"REBOOT_REQUIRED_NAME",
",",
"vdata",
... | r'''
This function is used to remember that an event indicating that a reboot is
required was witnessed. This function relies on the salt-minion's ability to
create the following volatile registry key in the *HKLM* hive:
*SYSTEM\\CurrentControlSet\\Services\\salt-minion\\Volatile-Data*
Because this registry key is volatile, it will not persist beyond the
current boot session. Also, in the scope of this key, the name *'Reboot
required'* will be assigned the value of *1*.
For the time being, this function is being used whenever an install
completes with exit code 3010 and can be extended where appropriate in the
future.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' system.set_reboot_required_witnessed | [
"r",
"This",
"function",
"is",
"used",
"to",
"remember",
"that",
"an",
"event",
"indicating",
"that",
"a",
"reboot",
"is",
"required",
"was",
"witnessed",
".",
"This",
"function",
"relies",
"on",
"the",
"salt",
"-",
"minion",
"s",
"ability",
"to",
"create"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1443-L1476 | train |
saltstack/salt | salt/modules/win_system.py | get_pending_reboot | def get_pending_reboot():
'''
Determine whether there is a reboot pending.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if the system is pending reboot, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_reboot
'''
# Order the checks for reboot pending in most to least likely.
checks = (get_pending_update,
get_pending_file_rename,
get_pending_servermanager,
get_pending_component_servicing,
get_reboot_required_witnessed,
get_pending_computer_name,
get_pending_domain_join)
for check in checks:
if check():
return True
return False | python | def get_pending_reboot():
'''
Determine whether there is a reboot pending.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if the system is pending reboot, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_reboot
'''
# Order the checks for reboot pending in most to least likely.
checks = (get_pending_update,
get_pending_file_rename,
get_pending_servermanager,
get_pending_component_servicing,
get_reboot_required_witnessed,
get_pending_computer_name,
get_pending_domain_join)
for check in checks:
if check():
return True
return False | [
"def",
"get_pending_reboot",
"(",
")",
":",
"# Order the checks for reboot pending in most to least likely.",
"checks",
"=",
"(",
"get_pending_update",
",",
"get_pending_file_rename",
",",
"get_pending_servermanager",
",",
"get_pending_component_servicing",
",",
"get_reboot_require... | Determine whether there is a reboot pending.
.. versionadded:: 2016.11.0
Returns:
bool: ``True`` if the system is pending reboot, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' system.get_pending_reboot | [
"Determine",
"whether",
"there",
"is",
"a",
"reboot",
"pending",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1508-L1537 | train |
saltstack/salt | salt/states/postgres_extension.py | present | def present(name,
if_not_exists=None,
schema=None,
ext_version=None,
from_version=None,
user=None,
maintenance_db=None,
db_user=None,
db_password=None,
db_host=None,
db_port=None):
'''
Ensure that the named extension is present.
.. note::
Before you can use the state to load an extension into a database, the
extension's supporting files must be already installed.
For more information about all of these options see ``CREATE EXTENSION`` SQL
command reference in the PostgreSQL documentation.
name
The name of the extension to be installed
if_not_exists
Add an ``IF NOT EXISTS`` parameter to the DDL statement
schema
Schema to install the extension into
ext_version
Version to install
from_version
Old extension version if already installed
user
System user all operations should be performed on behalf of
maintenance_db
Database to act on
db_user
Database username if different from config or default
db_password
User password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Extension {0} is already present'.format(name)}
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'user': db_user,
'password': db_password,
'host': db_host,
'port': db_port,
}
# check if extension exists
mode = 'create'
mtdata = __salt__['postgres.create_metadata'](
name,
schema=schema,
ext_version=ext_version,
**db_args)
# The extension is not present, install it!
toinstall = postgres._EXTENSION_NOT_INSTALLED in mtdata
if toinstall:
mode = 'install'
toupgrade = False
if postgres._EXTENSION_INSTALLED in mtdata:
for flag in [
postgres._EXTENSION_TO_MOVE,
postgres._EXTENSION_TO_UPGRADE
]:
if flag in mtdata:
toupgrade = True
mode = 'upgrade'
cret = None
if toinstall or toupgrade:
if __opts__['test']:
ret['result'] = None
if mode:
ret['comment'] = 'Extension {0} is set to be {1}ed'.format(
name, mode).replace('eed', 'ed')
return ret
cret = __salt__['postgres.create_extension'](
name=name,
if_not_exists=if_not_exists,
schema=schema,
ext_version=ext_version,
from_version=from_version,
**db_args)
if cret:
if mode.endswith('e'):
suffix = 'd'
else:
suffix = 'ed'
ret['comment'] = 'The extension {0} has been {1}{2}'.format(name, mode, suffix)
ret['changes'][name] = '{0}{1}'.format(mode.capitalize(), suffix)
elif cret is not None:
ret['comment'] = 'Failed to {1} extension {0}'.format(name, mode)
ret['result'] = False
return ret | python | def present(name,
if_not_exists=None,
schema=None,
ext_version=None,
from_version=None,
user=None,
maintenance_db=None,
db_user=None,
db_password=None,
db_host=None,
db_port=None):
'''
Ensure that the named extension is present.
.. note::
Before you can use the state to load an extension into a database, the
extension's supporting files must be already installed.
For more information about all of these options see ``CREATE EXTENSION`` SQL
command reference in the PostgreSQL documentation.
name
The name of the extension to be installed
if_not_exists
Add an ``IF NOT EXISTS`` parameter to the DDL statement
schema
Schema to install the extension into
ext_version
Version to install
from_version
Old extension version if already installed
user
System user all operations should be performed on behalf of
maintenance_db
Database to act on
db_user
Database username if different from config or default
db_password
User password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Extension {0} is already present'.format(name)}
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'user': db_user,
'password': db_password,
'host': db_host,
'port': db_port,
}
# check if extension exists
mode = 'create'
mtdata = __salt__['postgres.create_metadata'](
name,
schema=schema,
ext_version=ext_version,
**db_args)
# The extension is not present, install it!
toinstall = postgres._EXTENSION_NOT_INSTALLED in mtdata
if toinstall:
mode = 'install'
toupgrade = False
if postgres._EXTENSION_INSTALLED in mtdata:
for flag in [
postgres._EXTENSION_TO_MOVE,
postgres._EXTENSION_TO_UPGRADE
]:
if flag in mtdata:
toupgrade = True
mode = 'upgrade'
cret = None
if toinstall or toupgrade:
if __opts__['test']:
ret['result'] = None
if mode:
ret['comment'] = 'Extension {0} is set to be {1}ed'.format(
name, mode).replace('eed', 'ed')
return ret
cret = __salt__['postgres.create_extension'](
name=name,
if_not_exists=if_not_exists,
schema=schema,
ext_version=ext_version,
from_version=from_version,
**db_args)
if cret:
if mode.endswith('e'):
suffix = 'd'
else:
suffix = 'ed'
ret['comment'] = 'The extension {0} has been {1}{2}'.format(name, mode, suffix)
ret['changes'][name] = '{0}{1}'.format(mode.capitalize(), suffix)
elif cret is not None:
ret['comment'] = 'Failed to {1} extension {0}'.format(name, mode)
ret['result'] = False
return ret | [
"def",
"present",
"(",
"name",
",",
"if_not_exists",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"ext_version",
"=",
"None",
",",
"from_version",
"=",
"None",
",",
"user",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"db_user",
"=",
"None",
... | Ensure that the named extension is present.
.. note::
Before you can use the state to load an extension into a database, the
extension's supporting files must be already installed.
For more information about all of these options see ``CREATE EXTENSION`` SQL
command reference in the PostgreSQL documentation.
name
The name of the extension to be installed
if_not_exists
Add an ``IF NOT EXISTS`` parameter to the DDL statement
schema
Schema to install the extension into
ext_version
Version to install
from_version
Old extension version if already installed
user
System user all operations should be performed on behalf of
maintenance_db
Database to act on
db_user
Database username if different from config or default
db_password
User password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default | [
"Ensure",
"that",
"the",
"named",
"extension",
"is",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_extension.py#L36-L151 | train |
saltstack/salt | salt/states/postgres_extension.py | absent | def absent(name,
if_exists=None,
restrict=None,
cascade=None,
user=None,
maintenance_db=None,
db_user=None,
db_password=None,
db_host=None,
db_port=None):
'''
Ensure that the named extension is absent.
name
Extension name of the extension to remove
if_exists
Add if exist slug
restrict
Add restrict slug
cascade
Drop on cascade
user
System user all operations should be performed on behalf of
maintenance_db
Database to act on
db_user
Database username if different from config or default
db_password
User password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
# check if extension exists and remove it
exists = __salt__['postgres.is_installed_extension'](name, **db_args)
if exists:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Extension {0} is set to be removed'.format(name)
return ret
if __salt__['postgres.drop_extension'](name,
if_exists=if_exists,
restrict=restrict,
cascade=cascade,
**db_args):
ret['comment'] = 'Extension {0} has been removed'.format(name)
ret['changes'][name] = 'Absent'
return ret
else:
ret['result'] = False
ret['comment'] = 'Extension {0} failed to be removed'.format(name)
return ret
else:
ret['comment'] = 'Extension {0} is not present, so it cannot ' \
'be removed'.format(name)
return ret | python | def absent(name,
if_exists=None,
restrict=None,
cascade=None,
user=None,
maintenance_db=None,
db_user=None,
db_password=None,
db_host=None,
db_port=None):
'''
Ensure that the named extension is absent.
name
Extension name of the extension to remove
if_exists
Add if exist slug
restrict
Add restrict slug
cascade
Drop on cascade
user
System user all operations should be performed on behalf of
maintenance_db
Database to act on
db_user
Database username if different from config or default
db_password
User password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
# check if extension exists and remove it
exists = __salt__['postgres.is_installed_extension'](name, **db_args)
if exists:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Extension {0} is set to be removed'.format(name)
return ret
if __salt__['postgres.drop_extension'](name,
if_exists=if_exists,
restrict=restrict,
cascade=cascade,
**db_args):
ret['comment'] = 'Extension {0} has been removed'.format(name)
ret['changes'][name] = 'Absent'
return ret
else:
ret['result'] = False
ret['comment'] = 'Extension {0} failed to be removed'.format(name)
return ret
else:
ret['comment'] = 'Extension {0} is not present, so it cannot ' \
'be removed'.format(name)
return ret | [
"def",
"absent",
"(",
"name",
",",
"if_exists",
"=",
"None",
",",
"restrict",
"=",
"None",
",",
"cascade",
"=",
"None",
",",
"user",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"db_user",
"=",
"None",
",",
"db_password",
"=",
"None",
",",
"... | Ensure that the named extension is absent.
name
Extension name of the extension to remove
if_exists
Add if exist slug
restrict
Add restrict slug
cascade
Drop on cascade
user
System user all operations should be performed on behalf of
maintenance_db
Database to act on
db_user
Database username if different from config or default
db_password
User password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default | [
"Ensure",
"that",
"the",
"named",
"extension",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_extension.py#L154-L232 | train |
saltstack/salt | salt/auth/file.py | _get_file_auth_config | def _get_file_auth_config():
'''
Setup defaults and check configuration variables for auth backends
'''
config = {
'filetype': 'text',
'hashtype': 'plaintext',
'field_separator': ':',
'username_field': 1,
'password_field': 2,
}
for opt in __opts__['external_auth'][__virtualname__]:
if opt.startswith('^'):
config[opt[1:]] = __opts__['external_auth'][__virtualname__][opt]
if 'filename' not in config:
log.error('salt.auth.file: An authentication file must be specified '
'via external_auth:file:^filename')
return False
if not os.path.exists(config['filename']):
log.error('salt.auth.file: The configured external_auth:file:^filename (%s)'
'does not exist on the filesystem', config['filename'])
return False
config['username_field'] = int(config['username_field'])
config['password_field'] = int(config['password_field'])
return config | python | def _get_file_auth_config():
'''
Setup defaults and check configuration variables for auth backends
'''
config = {
'filetype': 'text',
'hashtype': 'plaintext',
'field_separator': ':',
'username_field': 1,
'password_field': 2,
}
for opt in __opts__['external_auth'][__virtualname__]:
if opt.startswith('^'):
config[opt[1:]] = __opts__['external_auth'][__virtualname__][opt]
if 'filename' not in config:
log.error('salt.auth.file: An authentication file must be specified '
'via external_auth:file:^filename')
return False
if not os.path.exists(config['filename']):
log.error('salt.auth.file: The configured external_auth:file:^filename (%s)'
'does not exist on the filesystem', config['filename'])
return False
config['username_field'] = int(config['username_field'])
config['password_field'] = int(config['password_field'])
return config | [
"def",
"_get_file_auth_config",
"(",
")",
":",
"config",
"=",
"{",
"'filetype'",
":",
"'text'",
",",
"'hashtype'",
":",
"'plaintext'",
",",
"'field_separator'",
":",
"':'",
",",
"'username_field'",
":",
"1",
",",
"'password_field'",
":",
"2",
",",
"}",
"for"... | Setup defaults and check configuration variables for auth backends | [
"Setup",
"defaults",
"and",
"check",
"configuration",
"variables",
"for",
"auth",
"backends"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L116-L146 | train |
saltstack/salt | salt/auth/file.py | _text | def _text(username, password, **kwargs):
'''
The text file function can authenticate plaintext and digest methods
that are available in the :py:func:`hashutil.digest <salt.modules.hashutil.digest>`
function.
'''
filename = kwargs['filename']
hashtype = kwargs['hashtype']
field_separator = kwargs['field_separator']
username_field = kwargs['username_field']-1
password_field = kwargs['password_field']-1
with salt.utils.files.fopen(filename, 'r') as pwfile:
for line in pwfile.readlines():
fields = line.strip().split(field_separator)
try:
this_username = fields[username_field]
except IndexError:
log.error('salt.auth.file: username field (%s) does not exist '
'in file %s', username_field, filename)
return False
try:
this_password = fields[password_field]
except IndexError:
log.error('salt.auth.file: password field (%s) does not exist '
'in file %s', password_field, filename)
return False
if this_username == username:
if hashtype == 'plaintext':
if this_password == password:
return True
else:
# Exceptions for unknown hash types will be raised by hashutil.digest
if this_password == __salt__['hashutil.digest'](password, hashtype):
return True
# Short circuit if we've already found the user but the password was wrong
return False
return False | python | def _text(username, password, **kwargs):
'''
The text file function can authenticate plaintext and digest methods
that are available in the :py:func:`hashutil.digest <salt.modules.hashutil.digest>`
function.
'''
filename = kwargs['filename']
hashtype = kwargs['hashtype']
field_separator = kwargs['field_separator']
username_field = kwargs['username_field']-1
password_field = kwargs['password_field']-1
with salt.utils.files.fopen(filename, 'r') as pwfile:
for line in pwfile.readlines():
fields = line.strip().split(field_separator)
try:
this_username = fields[username_field]
except IndexError:
log.error('salt.auth.file: username field (%s) does not exist '
'in file %s', username_field, filename)
return False
try:
this_password = fields[password_field]
except IndexError:
log.error('salt.auth.file: password field (%s) does not exist '
'in file %s', password_field, filename)
return False
if this_username == username:
if hashtype == 'plaintext':
if this_password == password:
return True
else:
# Exceptions for unknown hash types will be raised by hashutil.digest
if this_password == __salt__['hashutil.digest'](password, hashtype):
return True
# Short circuit if we've already found the user but the password was wrong
return False
return False | [
"def",
"_text",
"(",
"username",
",",
"password",
",",
"*",
"*",
"kwargs",
")",
":",
"filename",
"=",
"kwargs",
"[",
"'filename'",
"]",
"hashtype",
"=",
"kwargs",
"[",
"'hashtype'",
"]",
"field_separator",
"=",
"kwargs",
"[",
"'field_separator'",
"]",
"use... | The text file function can authenticate plaintext and digest methods
that are available in the :py:func:`hashutil.digest <salt.modules.hashutil.digest>`
function. | [
"The",
"text",
"file",
"function",
"can",
"authenticate",
"plaintext",
"and",
"digest",
"methods",
"that",
"are",
"available",
"in",
"the",
":",
"py",
":",
"func",
":",
"hashutil",
".",
"digest",
"<salt",
".",
"modules",
".",
"hashutil",
".",
"digest",
">"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L149-L190 | train |
saltstack/salt | salt/auth/file.py | _htpasswd | def _htpasswd(username, password, **kwargs):
'''
Provide authentication via Apache-style htpasswd files
'''
from passlib.apache import HtpasswdFile
pwfile = HtpasswdFile(kwargs['filename'])
# passlib below version 1.6 uses 'verify' function instead of 'check_password'
if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0:
return pwfile.verify(username, password)
else:
return pwfile.check_password(username, password) | python | def _htpasswd(username, password, **kwargs):
'''
Provide authentication via Apache-style htpasswd files
'''
from passlib.apache import HtpasswdFile
pwfile = HtpasswdFile(kwargs['filename'])
# passlib below version 1.6 uses 'verify' function instead of 'check_password'
if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0:
return pwfile.verify(username, password)
else:
return pwfile.check_password(username, password) | [
"def",
"_htpasswd",
"(",
"username",
",",
"password",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"passlib",
".",
"apache",
"import",
"HtpasswdFile",
"pwfile",
"=",
"HtpasswdFile",
"(",
"kwargs",
"[",
"'filename'",
"]",
")",
"# passlib below version 1.6 uses 'ver... | Provide authentication via Apache-style htpasswd files | [
"Provide",
"authentication",
"via",
"Apache",
"-",
"style",
"htpasswd",
"files"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L193-L206 | train |
saltstack/salt | salt/auth/file.py | _htdigest | def _htdigest(username, password, **kwargs):
'''
Provide authentication via Apache-style htdigest files
'''
realm = kwargs.get('realm', None)
if not realm:
log.error('salt.auth.file: A ^realm must be defined in '
'external_auth:file for htdigest filetype')
return False
from passlib.apache import HtdigestFile
pwfile = HtdigestFile(kwargs['filename'])
# passlib below version 1.6 uses 'verify' function instead of 'check_password'
if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0:
return pwfile.verify(username, realm, password)
else:
return pwfile.check_password(username, realm, password) | python | def _htdigest(username, password, **kwargs):
'''
Provide authentication via Apache-style htdigest files
'''
realm = kwargs.get('realm', None)
if not realm:
log.error('salt.auth.file: A ^realm must be defined in '
'external_auth:file for htdigest filetype')
return False
from passlib.apache import HtdigestFile
pwfile = HtdigestFile(kwargs['filename'])
# passlib below version 1.6 uses 'verify' function instead of 'check_password'
if salt.utils.versions.version_cmp(kwargs['passlib_version'], '1.6') < 0:
return pwfile.verify(username, realm, password)
else:
return pwfile.check_password(username, realm, password) | [
"def",
"_htdigest",
"(",
"username",
",",
"password",
",",
"*",
"*",
"kwargs",
")",
":",
"realm",
"=",
"kwargs",
".",
"get",
"(",
"'realm'",
",",
"None",
")",
"if",
"not",
"realm",
":",
"log",
".",
"error",
"(",
"'salt.auth.file: A ^realm must be defined i... | Provide authentication via Apache-style htdigest files | [
"Provide",
"authentication",
"via",
"Apache",
"-",
"style",
"htdigest",
"files"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L209-L228 | train |
saltstack/salt | salt/auth/file.py | _htfile | def _htfile(username, password, **kwargs):
'''
Gate function for _htpasswd and _htdigest authentication backends
'''
filetype = kwargs.get('filetype', 'htpasswd').lower()
try:
import passlib
kwargs['passlib_version'] = passlib.__version__
except ImportError:
log.error('salt.auth.file: The python-passlib library is required '
'for %s filetype', filetype)
return False
if filetype == 'htdigest':
return _htdigest(username, password, **kwargs)
else:
return _htpasswd(username, password, **kwargs) | python | def _htfile(username, password, **kwargs):
'''
Gate function for _htpasswd and _htdigest authentication backends
'''
filetype = kwargs.get('filetype', 'htpasswd').lower()
try:
import passlib
kwargs['passlib_version'] = passlib.__version__
except ImportError:
log.error('salt.auth.file: The python-passlib library is required '
'for %s filetype', filetype)
return False
if filetype == 'htdigest':
return _htdigest(username, password, **kwargs)
else:
return _htpasswd(username, password, **kwargs) | [
"def",
"_htfile",
"(",
"username",
",",
"password",
",",
"*",
"*",
"kwargs",
")",
":",
"filetype",
"=",
"kwargs",
".",
"get",
"(",
"'filetype'",
",",
"'htpasswd'",
")",
".",
"lower",
"(",
")",
"try",
":",
"import",
"passlib",
"kwargs",
"[",
"'passlib_v... | Gate function for _htpasswd and _htdigest authentication backends | [
"Gate",
"function",
"for",
"_htpasswd",
"and",
"_htdigest",
"authentication",
"backends"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L231-L249 | train |
saltstack/salt | salt/auth/file.py | auth | def auth(username, password):
'''
File based authentication
^filename
The path to the file to use for authentication.
^filetype
The type of file: ``text``, ``htpasswd``, ``htdigest``.
Default: ``text``
^realm
The realm required by htdigest authentication.
.. note::
The following parameters are only used with the ``text`` filetype.
^hashtype
The digest format of the password. Can be ``plaintext`` or any digest
available via :py:func:`hashutil.digest <salt.modules.hashutil.digest>`.
Default: ``plaintext``
^field_separator
The character to use as a delimiter between fields in a text file.
Default: ``:``
^username_field
The numbered field in the text file that contains the username, with
numbering beginning at 1 (one).
Default: ``1``
^password_field
The numbered field in the text file that contains the password, with
numbering beginning at 1 (one).
Default: ``2``
'''
config = _get_file_auth_config()
if not config:
return False
auth_function = FILETYPE_FUNCTION_MAP.get(config['filetype'], 'text')
return auth_function(username, password, **config) | python | def auth(username, password):
'''
File based authentication
^filename
The path to the file to use for authentication.
^filetype
The type of file: ``text``, ``htpasswd``, ``htdigest``.
Default: ``text``
^realm
The realm required by htdigest authentication.
.. note::
The following parameters are only used with the ``text`` filetype.
^hashtype
The digest format of the password. Can be ``plaintext`` or any digest
available via :py:func:`hashutil.digest <salt.modules.hashutil.digest>`.
Default: ``plaintext``
^field_separator
The character to use as a delimiter between fields in a text file.
Default: ``:``
^username_field
The numbered field in the text file that contains the username, with
numbering beginning at 1 (one).
Default: ``1``
^password_field
The numbered field in the text file that contains the password, with
numbering beginning at 1 (one).
Default: ``2``
'''
config = _get_file_auth_config()
if not config:
return False
auth_function = FILETYPE_FUNCTION_MAP.get(config['filetype'], 'text')
return auth_function(username, password, **config) | [
"def",
"auth",
"(",
"username",
",",
"password",
")",
":",
"config",
"=",
"_get_file_auth_config",
"(",
")",
"if",
"not",
"config",
":",
"return",
"False",
"auth_function",
"=",
"FILETYPE_FUNCTION_MAP",
".",
"get",
"(",
"config",
"[",
"'filetype'",
"]",
",",... | File based authentication
^filename
The path to the file to use for authentication.
^filetype
The type of file: ``text``, ``htpasswd``, ``htdigest``.
Default: ``text``
^realm
The realm required by htdigest authentication.
.. note::
The following parameters are only used with the ``text`` filetype.
^hashtype
The digest format of the password. Can be ``plaintext`` or any digest
available via :py:func:`hashutil.digest <salt.modules.hashutil.digest>`.
Default: ``plaintext``
^field_separator
The character to use as a delimiter between fields in a text file.
Default: ``:``
^username_field
The numbered field in the text file that contains the username, with
numbering beginning at 1 (one).
Default: ``1``
^password_field
The numbered field in the text file that contains the password, with
numbering beginning at 1 (one).
Default: ``2`` | [
"File",
"based",
"authentication"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/file.py#L259-L308 | train |
saltstack/salt | salt/states/openvswitch_bridge.py | present | def present(name, parent=None, vlan=None):
'''
Ensures that the named bridge exists, eventually creates it.
Args:
name: The name of the bridge.
parent: The name of the parent bridge (if the bridge shall be created
as a fake bridge). If specified, vlan must also be specified.
vlan: The VLAN ID of the bridge (if the bridge shall be created as a
fake bridge). If specified, parent must also be specified.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_bridge_created = 'Bridge {0} created.'.format(name)
comment_bridge_notcreated = 'Unable to create bridge: {0}.'.format(name)
comment_bridge_exists = 'Bridge {0} already exists.'.format(name)
comment_bridge_mismatch = ('Bridge {0} already exists, but has a different'
' parent or VLAN ID.').format(name)
changes_bridge_created = {name: {'old': 'Bridge {0} does not exist.'.format(name),
'new': 'Bridge {0} created'.format(name),
}
}
bridge_exists = __salt__['openvswitch.bridge_exists'](name)
if bridge_exists:
current_parent = __salt__['openvswitch.bridge_to_parent'](name)
if current_parent == name:
current_parent = None
current_vlan = __salt__['openvswitch.bridge_to_vlan'](name)
if current_vlan == 0:
current_vlan = None
# Dry run, test=true mode
if __opts__['test']:
if bridge_exists:
if current_parent == parent and current_vlan == vlan:
ret['result'] = True
ret['comment'] = comment_bridge_exists
else:
ret['result'] = False
ret['comment'] = comment_bridge_mismatch
else:
ret['result'] = None
ret['comment'] = comment_bridge_created
return ret
if bridge_exists:
if current_parent == parent and current_vlan == vlan:
ret['result'] = True
ret['comment'] = comment_bridge_exists
else:
ret['result'] = False
ret['comment'] = comment_bridge_mismatch
else:
bridge_create = __salt__['openvswitch.bridge_create'](
name, parent=parent, vlan=vlan)
if bridge_create:
ret['result'] = True
ret['comment'] = comment_bridge_created
ret['changes'] = changes_bridge_created
else:
ret['result'] = False
ret['comment'] = comment_bridge_notcreated
return ret | python | def present(name, parent=None, vlan=None):
'''
Ensures that the named bridge exists, eventually creates it.
Args:
name: The name of the bridge.
parent: The name of the parent bridge (if the bridge shall be created
as a fake bridge). If specified, vlan must also be specified.
vlan: The VLAN ID of the bridge (if the bridge shall be created as a
fake bridge). If specified, parent must also be specified.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_bridge_created = 'Bridge {0} created.'.format(name)
comment_bridge_notcreated = 'Unable to create bridge: {0}.'.format(name)
comment_bridge_exists = 'Bridge {0} already exists.'.format(name)
comment_bridge_mismatch = ('Bridge {0} already exists, but has a different'
' parent or VLAN ID.').format(name)
changes_bridge_created = {name: {'old': 'Bridge {0} does not exist.'.format(name),
'new': 'Bridge {0} created'.format(name),
}
}
bridge_exists = __salt__['openvswitch.bridge_exists'](name)
if bridge_exists:
current_parent = __salt__['openvswitch.bridge_to_parent'](name)
if current_parent == name:
current_parent = None
current_vlan = __salt__['openvswitch.bridge_to_vlan'](name)
if current_vlan == 0:
current_vlan = None
# Dry run, test=true mode
if __opts__['test']:
if bridge_exists:
if current_parent == parent and current_vlan == vlan:
ret['result'] = True
ret['comment'] = comment_bridge_exists
else:
ret['result'] = False
ret['comment'] = comment_bridge_mismatch
else:
ret['result'] = None
ret['comment'] = comment_bridge_created
return ret
if bridge_exists:
if current_parent == parent and current_vlan == vlan:
ret['result'] = True
ret['comment'] = comment_bridge_exists
else:
ret['result'] = False
ret['comment'] = comment_bridge_mismatch
else:
bridge_create = __salt__['openvswitch.bridge_create'](
name, parent=parent, vlan=vlan)
if bridge_create:
ret['result'] = True
ret['comment'] = comment_bridge_created
ret['changes'] = changes_bridge_created
else:
ret['result'] = False
ret['comment'] = comment_bridge_notcreated
return ret | [
"def",
"present",
"(",
"name",
",",
"parent",
"=",
"None",
",",
"vlan",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"# Comment and ... | Ensures that the named bridge exists, eventually creates it.
Args:
name: The name of the bridge.
parent: The name of the parent bridge (if the bridge shall be created
as a fake bridge). If specified, vlan must also be specified.
vlan: The VLAN ID of the bridge (if the bridge shall be created as a
fake bridge). If specified, parent must also be specified. | [
"Ensures",
"that",
"the",
"named",
"bridge",
"exists",
"eventually",
"creates",
"it",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/openvswitch_bridge.py#L17-L84 | train |
saltstack/salt | salt/states/openvswitch_bridge.py | absent | def absent(name):
'''
Ensures that the named bridge does not exist, eventually deletes it.
Args:
name: The name of the bridge.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_bridge_deleted = 'Bridge {0} deleted.'.format(name)
comment_bridge_notdeleted = 'Unable to delete bridge: {0}.'.format(name)
comment_bridge_notexists = 'Bridge {0} does not exist.'.format(name)
changes_bridge_deleted = {name: {'old': 'Bridge {0} exists.'.format(name),
'new': 'Bridge {0} deleted.'.format(name),
}
}
bridge_exists = __salt__['openvswitch.bridge_exists'](name)
# Dry run, test=true mode
if __opts__['test']:
if not bridge_exists:
ret['result'] = True
ret['comment'] = comment_bridge_notexists
else:
ret['result'] = None
ret['comment'] = comment_bridge_deleted
return ret
if not bridge_exists:
ret['result'] = True
ret['comment'] = comment_bridge_notexists
else:
bridge_delete = __salt__['openvswitch.bridge_delete'](name)
if bridge_delete:
ret['result'] = True
ret['comment'] = comment_bridge_deleted
ret['changes'] = changes_bridge_deleted
else:
ret['result'] = False
ret['comment'] = comment_bridge_notdeleted
return ret | python | def absent(name):
'''
Ensures that the named bridge does not exist, eventually deletes it.
Args:
name: The name of the bridge.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_bridge_deleted = 'Bridge {0} deleted.'.format(name)
comment_bridge_notdeleted = 'Unable to delete bridge: {0}.'.format(name)
comment_bridge_notexists = 'Bridge {0} does not exist.'.format(name)
changes_bridge_deleted = {name: {'old': 'Bridge {0} exists.'.format(name),
'new': 'Bridge {0} deleted.'.format(name),
}
}
bridge_exists = __salt__['openvswitch.bridge_exists'](name)
# Dry run, test=true mode
if __opts__['test']:
if not bridge_exists:
ret['result'] = True
ret['comment'] = comment_bridge_notexists
else:
ret['result'] = None
ret['comment'] = comment_bridge_deleted
return ret
if not bridge_exists:
ret['result'] = True
ret['comment'] = comment_bridge_notexists
else:
bridge_delete = __salt__['openvswitch.bridge_delete'](name)
if bridge_delete:
ret['result'] = True
ret['comment'] = comment_bridge_deleted
ret['changes'] = changes_bridge_deleted
else:
ret['result'] = False
ret['comment'] = comment_bridge_notdeleted
return ret | [
"def",
"absent",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"# Comment and change messages",
"comment_bridge_deleted",
"=",
"'Bridge {0} del... | Ensures that the named bridge does not exist, eventually deletes it.
Args:
name: The name of the bridge. | [
"Ensures",
"that",
"the",
"named",
"bridge",
"does",
"not",
"exist",
"eventually",
"deletes",
"it",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/openvswitch_bridge.py#L87-L133 | train |
saltstack/salt | salt/pillar/cmd_yamlex.py | ext_pillar | def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
command):
'''
Execute a command and read the output as YAMLEX
'''
try:
command = command.replace('%s', minion_id)
return deserialize(__salt__['cmd.run']('{0}'.format(command)))
except Exception:
log.critical('YAML data from %s failed to parse', command)
return {} | python | def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
command):
'''
Execute a command and read the output as YAMLEX
'''
try:
command = command.replace('%s', minion_id)
return deserialize(__salt__['cmd.run']('{0}'.format(command)))
except Exception:
log.critical('YAML data from %s failed to parse', command)
return {} | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"# pylint: disable=W0613",
"pillar",
",",
"# pylint: disable=W0613",
"command",
")",
":",
"try",
":",
"command",
"=",
"command",
".",
"replace",
"(",
"'%s'",
",",
"minion_id",
")",
"return",
"deserialize",
"(",
"__salt... | Execute a command and read the output as YAMLEX | [
"Execute",
"a",
"command",
"and",
"read",
"the",
"output",
"as",
"YAMLEX"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/cmd_yamlex.py#L19-L30 | train |
saltstack/salt | salt/states/kubernetes.py | deployment_absent | def deployment_absent(name, namespace='default', **kwargs):
'''
Ensures that the named deployment is absent from the given namespace.
name
The name of the deployment
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs)
if deployment is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The deployment does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The deployment is going to be deleted'
ret['result'] = None
return ret
res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs)
if res['code'] == 200:
ret['result'] = True
ret['changes'] = {
'kubernetes.deployment': {
'new': 'absent', 'old': 'present'}}
ret['comment'] = res['message']
else:
ret['comment'] = 'Something went wrong, response: {0}'.format(res)
return ret | python | def deployment_absent(name, namespace='default', **kwargs):
'''
Ensures that the named deployment is absent from the given namespace.
name
The name of the deployment
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs)
if deployment is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The deployment does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The deployment is going to be deleted'
ret['result'] = None
return ret
res = __salt__['kubernetes.delete_deployment'](name, namespace, **kwargs)
if res['code'] == 200:
ret['result'] = True
ret['changes'] = {
'kubernetes.deployment': {
'new': 'absent', 'old': 'present'}}
ret['comment'] = res['message']
else:
ret['comment'] = 'Something went wrong, response: {0}'.format(res)
return ret | [
"def",
"deployment_absent",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
... | Ensures that the named deployment is absent from the given namespace.
name
The name of the deployment
namespace
The name of the namespace | [
"Ensures",
"that",
"the",
"named",
"deployment",
"is",
"absent",
"from",
"the",
"given",
"namespace",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L111-L149 | train |
saltstack/salt | salt/states/kubernetes.py | deployment_present | def deployment_present(
name,
namespace='default',
metadata=None,
spec=None,
source='',
template='',
**kwargs):
'''
Ensures that the named deployment is present inside of the specified
namespace with the given metadata and spec.
If the deployment exists it will be replaced.
name
The name of the deployment.
namespace
The namespace holding the deployment. The 'default' one is going to be
used unless a different one is specified.
metadata
The metadata of the deployment object.
spec
The spec of the deployment object.
source
A file containing the definition of the deployment (metadata and
spec) in the official kubernetes format.
template
Template engine to be used to render the source file.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if (metadata or spec) and source:
return _error(
ret,
'\'source\' cannot be used in combination with \'metadata\' or '
'\'spec\''
)
if metadata is None:
metadata = {}
if spec is None:
spec = {}
deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs)
if deployment is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The deployment is going to be created'
return ret
res = __salt__['kubernetes.create_deployment'](name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes']['{0}.{1}'.format(namespace, name)] = {
'old': {},
'new': res}
else:
if __opts__['test']:
ret['result'] = None
return ret
# TODO: improve checks # pylint: disable=fixme
log.info('Forcing the recreation of the deployment')
ret['comment'] = 'The deployment is already present. Forcing recreation'
res = __salt__['kubernetes.replace_deployment'](
name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes'] = {
'metadata': metadata,
'spec': spec
}
ret['result'] = True
return ret | python | def deployment_present(
name,
namespace='default',
metadata=None,
spec=None,
source='',
template='',
**kwargs):
'''
Ensures that the named deployment is present inside of the specified
namespace with the given metadata and spec.
If the deployment exists it will be replaced.
name
The name of the deployment.
namespace
The namespace holding the deployment. The 'default' one is going to be
used unless a different one is specified.
metadata
The metadata of the deployment object.
spec
The spec of the deployment object.
source
A file containing the definition of the deployment (metadata and
spec) in the official kubernetes format.
template
Template engine to be used to render the source file.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if (metadata or spec) and source:
return _error(
ret,
'\'source\' cannot be used in combination with \'metadata\' or '
'\'spec\''
)
if metadata is None:
metadata = {}
if spec is None:
spec = {}
deployment = __salt__['kubernetes.show_deployment'](name, namespace, **kwargs)
if deployment is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The deployment is going to be created'
return ret
res = __salt__['kubernetes.create_deployment'](name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes']['{0}.{1}'.format(namespace, name)] = {
'old': {},
'new': res}
else:
if __opts__['test']:
ret['result'] = None
return ret
# TODO: improve checks # pylint: disable=fixme
log.info('Forcing the recreation of the deployment')
ret['comment'] = 'The deployment is already present. Forcing recreation'
res = __salt__['kubernetes.replace_deployment'](
name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes'] = {
'metadata': metadata,
'spec': spec
}
ret['result'] = True
return ret | [
"def",
"deployment_present",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"metadata",
"=",
"None",
",",
"spec",
"=",
"None",
",",
"source",
"=",
"''",
",",
"template",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
... | Ensures that the named deployment is present inside of the specified
namespace with the given metadata and spec.
If the deployment exists it will be replaced.
name
The name of the deployment.
namespace
The namespace holding the deployment. The 'default' one is going to be
used unless a different one is specified.
metadata
The metadata of the deployment object.
spec
The spec of the deployment object.
source
A file containing the definition of the deployment (metadata and
spec) in the official kubernetes format.
template
Template engine to be used to render the source file. | [
"Ensures",
"that",
"the",
"named",
"deployment",
"is",
"present",
"inside",
"of",
"the",
"specified",
"namespace",
"with",
"the",
"given",
"metadata",
"and",
"spec",
".",
"If",
"the",
"deployment",
"exists",
"it",
"will",
"be",
"replaced",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L152-L244 | train |
saltstack/salt | salt/states/kubernetes.py | service_present | def service_present(
name,
namespace='default',
metadata=None,
spec=None,
source='',
template='',
**kwargs):
'''
Ensures that the named service is present inside of the specified namespace
with the given metadata and spec.
If the deployment exists it will be replaced.
name
The name of the service.
namespace
The namespace holding the service. The 'default' one is going to be
used unless a different one is specified.
metadata
The metadata of the service object.
spec
The spec of the service object.
source
A file containing the definition of the service (metadata and
spec) in the official kubernetes format.
template
Template engine to be used to render the source file.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if (metadata or spec) and source:
return _error(
ret,
'\'source\' cannot be used in combination with \'metadata\' or '
'\'spec\''
)
if metadata is None:
metadata = {}
if spec is None:
spec = {}
service = __salt__['kubernetes.show_service'](name, namespace, **kwargs)
if service is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The service is going to be created'
return ret
res = __salt__['kubernetes.create_service'](name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes']['{0}.{1}'.format(namespace, name)] = {
'old': {},
'new': res}
else:
if __opts__['test']:
ret['result'] = None
return ret
# TODO: improve checks # pylint: disable=fixme
log.info('Forcing the recreation of the service')
ret['comment'] = 'The service is already present. Forcing recreation'
res = __salt__['kubernetes.replace_service'](
name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
old_service=service,
saltenv=__env__,
**kwargs)
ret['changes'] = {
'metadata': metadata,
'spec': spec
}
ret['result'] = True
return ret | python | def service_present(
name,
namespace='default',
metadata=None,
spec=None,
source='',
template='',
**kwargs):
'''
Ensures that the named service is present inside of the specified namespace
with the given metadata and spec.
If the deployment exists it will be replaced.
name
The name of the service.
namespace
The namespace holding the service. The 'default' one is going to be
used unless a different one is specified.
metadata
The metadata of the service object.
spec
The spec of the service object.
source
A file containing the definition of the service (metadata and
spec) in the official kubernetes format.
template
Template engine to be used to render the source file.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if (metadata or spec) and source:
return _error(
ret,
'\'source\' cannot be used in combination with \'metadata\' or '
'\'spec\''
)
if metadata is None:
metadata = {}
if spec is None:
spec = {}
service = __salt__['kubernetes.show_service'](name, namespace, **kwargs)
if service is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The service is going to be created'
return ret
res = __salt__['kubernetes.create_service'](name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes']['{0}.{1}'.format(namespace, name)] = {
'old': {},
'new': res}
else:
if __opts__['test']:
ret['result'] = None
return ret
# TODO: improve checks # pylint: disable=fixme
log.info('Forcing the recreation of the service')
ret['comment'] = 'The service is already present. Forcing recreation'
res = __salt__['kubernetes.replace_service'](
name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
old_service=service,
saltenv=__env__,
**kwargs)
ret['changes'] = {
'metadata': metadata,
'spec': spec
}
ret['result'] = True
return ret | [
"def",
"service_present",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"metadata",
"=",
"None",
",",
"spec",
"=",
"None",
",",
"source",
"=",
"''",
",",
"template",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
"... | Ensures that the named service is present inside of the specified namespace
with the given metadata and spec.
If the deployment exists it will be replaced.
name
The name of the service.
namespace
The namespace holding the service. The 'default' one is going to be
used unless a different one is specified.
metadata
The metadata of the service object.
spec
The spec of the service object.
source
A file containing the definition of the service (metadata and
spec) in the official kubernetes format.
template
Template engine to be used to render the source file. | [
"Ensures",
"that",
"the",
"named",
"service",
"is",
"present",
"inside",
"of",
"the",
"specified",
"namespace",
"with",
"the",
"given",
"metadata",
"and",
"spec",
".",
"If",
"the",
"deployment",
"exists",
"it",
"will",
"be",
"replaced",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L247-L340 | train |
saltstack/salt | salt/states/kubernetes.py | service_absent | def service_absent(name, namespace='default', **kwargs):
'''
Ensures that the named service is absent from the given namespace.
name
The name of the service
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
service = __salt__['kubernetes.show_service'](name, namespace, **kwargs)
if service is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The service does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The service is going to be deleted'
ret['result'] = None
return ret
res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs)
if res['code'] == 200:
ret['result'] = True
ret['changes'] = {
'kubernetes.service': {
'new': 'absent', 'old': 'present'}}
ret['comment'] = res['message']
else:
ret['comment'] = 'Something went wrong, response: {0}'.format(res)
return ret | python | def service_absent(name, namespace='default', **kwargs):
'''
Ensures that the named service is absent from the given namespace.
name
The name of the service
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
service = __salt__['kubernetes.show_service'](name, namespace, **kwargs)
if service is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The service does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The service is going to be deleted'
ret['result'] = None
return ret
res = __salt__['kubernetes.delete_service'](name, namespace, **kwargs)
if res['code'] == 200:
ret['result'] = True
ret['changes'] = {
'kubernetes.service': {
'new': 'absent', 'old': 'present'}}
ret['comment'] = res['message']
else:
ret['comment'] = 'Something went wrong, response: {0}'.format(res)
return ret | [
"def",
"service_absent",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"... | Ensures that the named service is absent from the given namespace.
name
The name of the service
namespace
The name of the namespace | [
"Ensures",
"that",
"the",
"named",
"service",
"is",
"absent",
"from",
"the",
"given",
"namespace",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L343-L381 | train |
saltstack/salt | salt/states/kubernetes.py | namespace_absent | def namespace_absent(name, **kwargs):
'''
Ensures that the named namespace is absent.
name
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
namespace = __salt__['kubernetes.show_namespace'](name, **kwargs)
if namespace is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The namespace does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The namespace is going to be deleted'
ret['result'] = None
return ret
res = __salt__['kubernetes.delete_namespace'](name, **kwargs)
if (
res['code'] == 200 or
(
isinstance(res['status'], six.string_types) and
'Terminating' in res['status']
) or
(
isinstance(res['status'], dict) and
res['status']['phase'] == 'Terminating'
)):
ret['result'] = True
ret['changes'] = {
'kubernetes.namespace': {
'new': 'absent', 'old': 'present'}}
if res['message']:
ret['comment'] = res['message']
else:
ret['comment'] = 'Terminating'
else:
ret['comment'] = 'Something went wrong, response: {0}'.format(res)
return ret | python | def namespace_absent(name, **kwargs):
'''
Ensures that the named namespace is absent.
name
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
namespace = __salt__['kubernetes.show_namespace'](name, **kwargs)
if namespace is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The namespace does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The namespace is going to be deleted'
ret['result'] = None
return ret
res = __salt__['kubernetes.delete_namespace'](name, **kwargs)
if (
res['code'] == 200 or
(
isinstance(res['status'], six.string_types) and
'Terminating' in res['status']
) or
(
isinstance(res['status'], dict) and
res['status']['phase'] == 'Terminating'
)):
ret['result'] = True
ret['changes'] = {
'kubernetes.namespace': {
'new': 'absent', 'old': 'present'}}
if res['message']:
ret['comment'] = res['message']
else:
ret['comment'] = 'Terminating'
else:
ret['comment'] = 'Something went wrong, response: {0}'.format(res)
return ret | [
"def",
"namespace_absent",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"namespace",
"=",
"__salt__",
"[",
... | Ensures that the named namespace is absent.
name
The name of the namespace | [
"Ensures",
"that",
"the",
"named",
"namespace",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L384-L431 | train |
saltstack/salt | salt/states/kubernetes.py | namespace_present | def namespace_present(name, **kwargs):
'''
Ensures that the named namespace is present.
name
The name of the namespace.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
namespace = __salt__['kubernetes.show_namespace'](name, **kwargs)
if namespace is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The namespace is going to be created'
return ret
res = __salt__['kubernetes.create_namespace'](name, **kwargs)
ret['result'] = True
ret['changes']['namespace'] = {
'old': {},
'new': res}
else:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The namespace already exists'
return ret | python | def namespace_present(name, **kwargs):
'''
Ensures that the named namespace is present.
name
The name of the namespace.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
namespace = __salt__['kubernetes.show_namespace'](name, **kwargs)
if namespace is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The namespace is going to be created'
return ret
res = __salt__['kubernetes.create_namespace'](name, **kwargs)
ret['result'] = True
ret['changes']['namespace'] = {
'old': {},
'new': res}
else:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The namespace already exists'
return ret | [
"def",
"namespace_present",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"namespace",
"=",
"__salt__",
"[",
... | Ensures that the named namespace is present.
name
The name of the namespace. | [
"Ensures",
"that",
"the",
"named",
"namespace",
"is",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L434-L464 | train |
saltstack/salt | salt/states/kubernetes.py | secret_absent | def secret_absent(name, namespace='default', **kwargs):
'''
Ensures that the named secret is absent from the given namespace.
name
The name of the secret
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs)
if secret is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The secret does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The secret is going to be deleted'
ret['result'] = None
return ret
__salt__['kubernetes.delete_secret'](name, namespace, **kwargs)
# As for kubernetes 1.6.4 doesn't set a code when deleting a secret
# The kubernetes module will raise an exception if the kubernetes
# server will return an error
ret['result'] = True
ret['changes'] = {
'kubernetes.secret': {
'new': 'absent', 'old': 'present'}}
ret['comment'] = 'Secret deleted'
return ret | python | def secret_absent(name, namespace='default', **kwargs):
'''
Ensures that the named secret is absent from the given namespace.
name
The name of the secret
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs)
if secret is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The secret does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The secret is going to be deleted'
ret['result'] = None
return ret
__salt__['kubernetes.delete_secret'](name, namespace, **kwargs)
# As for kubernetes 1.6.4 doesn't set a code when deleting a secret
# The kubernetes module will raise an exception if the kubernetes
# server will return an error
ret['result'] = True
ret['changes'] = {
'kubernetes.secret': {
'new': 'absent', 'old': 'present'}}
ret['comment'] = 'Secret deleted'
return ret | [
"def",
"secret_absent",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"s... | Ensures that the named secret is absent from the given namespace.
name
The name of the secret
namespace
The name of the namespace | [
"Ensures",
"that",
"the",
"named",
"secret",
"is",
"absent",
"from",
"the",
"given",
"namespace",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L467-L505 | train |
saltstack/salt | salt/states/kubernetes.py | secret_present | def secret_present(
name,
namespace='default',
data=None,
source=None,
template=None,
**kwargs):
'''
Ensures that the named secret is present inside of the specified namespace
with the given data.
If the secret exists it will be replaced.
name
The name of the secret.
namespace
The namespace holding the secret. The 'default' one is going to be
used unless a different one is specified.
data
The dictionary holding the secrets.
source
A file containing the data of the secret in plain format.
template
Template engine to be used to render the source file.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if data and source:
return _error(
ret,
'\'source\' cannot be used in combination with \'data\''
)
secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs)
if secret is None:
if data is None:
data = {}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The secret is going to be created'
return ret
res = __salt__['kubernetes.create_secret'](name=name,
namespace=namespace,
data=data,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes']['{0}.{1}'.format(namespace, name)] = {
'old': {},
'new': res}
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The secret is going to be replaced'
return ret
# TODO: improve checks # pylint: disable=fixme
log.info('Forcing the recreation of the service')
ret['comment'] = 'The secret is already present. Forcing recreation'
res = __salt__['kubernetes.replace_secret'](
name=name,
namespace=namespace,
data=data,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes'] = {
# Omit values from the return. They are unencrypted
# and can contain sensitive data.
'data': list(res['data'])
}
ret['result'] = True
return ret | python | def secret_present(
name,
namespace='default',
data=None,
source=None,
template=None,
**kwargs):
'''
Ensures that the named secret is present inside of the specified namespace
with the given data.
If the secret exists it will be replaced.
name
The name of the secret.
namespace
The namespace holding the secret. The 'default' one is going to be
used unless a different one is specified.
data
The dictionary holding the secrets.
source
A file containing the data of the secret in plain format.
template
Template engine to be used to render the source file.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if data and source:
return _error(
ret,
'\'source\' cannot be used in combination with \'data\''
)
secret = __salt__['kubernetes.show_secret'](name, namespace, **kwargs)
if secret is None:
if data is None:
data = {}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The secret is going to be created'
return ret
res = __salt__['kubernetes.create_secret'](name=name,
namespace=namespace,
data=data,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes']['{0}.{1}'.format(namespace, name)] = {
'old': {},
'new': res}
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The secret is going to be replaced'
return ret
# TODO: improve checks # pylint: disable=fixme
log.info('Forcing the recreation of the service')
ret['comment'] = 'The secret is already present. Forcing recreation'
res = __salt__['kubernetes.replace_secret'](
name=name,
namespace=namespace,
data=data,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes'] = {
# Omit values from the return. They are unencrypted
# and can contain sensitive data.
'data': list(res['data'])
}
ret['result'] = True
return ret | [
"def",
"secret_present",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"data",
"=",
"None",
",",
"source",
"=",
"None",
",",
"template",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",... | Ensures that the named secret is present inside of the specified namespace
with the given data.
If the secret exists it will be replaced.
name
The name of the secret.
namespace
The namespace holding the secret. The 'default' one is going to be
used unless a different one is specified.
data
The dictionary holding the secrets.
source
A file containing the data of the secret in plain format.
template
Template engine to be used to render the source file. | [
"Ensures",
"that",
"the",
"named",
"secret",
"is",
"present",
"inside",
"of",
"the",
"specified",
"namespace",
"with",
"the",
"given",
"data",
".",
"If",
"the",
"secret",
"exists",
"it",
"will",
"be",
"replaced",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L508-L592 | train |
saltstack/salt | salt/states/kubernetes.py | configmap_absent | def configmap_absent(name, namespace='default', **kwargs):
'''
Ensures that the named configmap is absent from the given namespace.
name
The name of the configmap
namespace
The namespace holding the configmap. The 'default' one is going to be
used unless a different one is specified.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs)
if configmap is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The configmap does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The configmap is going to be deleted'
ret['result'] = None
return ret
__salt__['kubernetes.delete_configmap'](name, namespace, **kwargs)
# As for kubernetes 1.6.4 doesn't set a code when deleting a configmap
# The kubernetes module will raise an exception if the kubernetes
# server will return an error
ret['result'] = True
ret['changes'] = {
'kubernetes.configmap': {
'new': 'absent', 'old': 'present'}}
ret['comment'] = 'ConfigMap deleted'
return ret | python | def configmap_absent(name, namespace='default', **kwargs):
'''
Ensures that the named configmap is absent from the given namespace.
name
The name of the configmap
namespace
The namespace holding the configmap. The 'default' one is going to be
used unless a different one is specified.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs)
if configmap is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The configmap does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The configmap is going to be deleted'
ret['result'] = None
return ret
__salt__['kubernetes.delete_configmap'](name, namespace, **kwargs)
# As for kubernetes 1.6.4 doesn't set a code when deleting a configmap
# The kubernetes module will raise an exception if the kubernetes
# server will return an error
ret['result'] = True
ret['changes'] = {
'kubernetes.configmap': {
'new': 'absent', 'old': 'present'}}
ret['comment'] = 'ConfigMap deleted'
return ret | [
"def",
"configmap_absent",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
... | Ensures that the named configmap is absent from the given namespace.
name
The name of the configmap
namespace
The namespace holding the configmap. The 'default' one is going to be
used unless a different one is specified. | [
"Ensures",
"that",
"the",
"named",
"configmap",
"is",
"absent",
"from",
"the",
"given",
"namespace",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L595-L634 | train |
saltstack/salt | salt/states/kubernetes.py | configmap_present | def configmap_present(
name,
namespace='default',
data=None,
source=None,
template=None,
**kwargs):
'''
Ensures that the named configmap is present inside of the specified namespace
with the given data.
If the configmap exists it will be replaced.
name
The name of the configmap.
namespace
The namespace holding the configmap. The 'default' one is going to be
used unless a different one is specified.
data
The dictionary holding the configmaps.
source
A file containing the data of the configmap in plain format.
template
Template engine to be used to render the source file.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if data and source:
return _error(
ret,
'\'source\' cannot be used in combination with \'data\''
)
elif data is None:
data = {}
configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs)
if configmap is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The configmap is going to be created'
return ret
res = __salt__['kubernetes.create_configmap'](name=name,
namespace=namespace,
data=data,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes']['{0}.{1}'.format(namespace, name)] = {
'old': {},
'new': res}
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The configmap is going to be replaced'
return ret
# TODO: improve checks # pylint: disable=fixme
log.info('Forcing the recreation of the service')
ret['comment'] = 'The configmap is already present. Forcing recreation'
res = __salt__['kubernetes.replace_configmap'](
name=name,
namespace=namespace,
data=data,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes'] = {
'data': res['data']
}
ret['result'] = True
return ret | python | def configmap_present(
name,
namespace='default',
data=None,
source=None,
template=None,
**kwargs):
'''
Ensures that the named configmap is present inside of the specified namespace
with the given data.
If the configmap exists it will be replaced.
name
The name of the configmap.
namespace
The namespace holding the configmap. The 'default' one is going to be
used unless a different one is specified.
data
The dictionary holding the configmaps.
source
A file containing the data of the configmap in plain format.
template
Template engine to be used to render the source file.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if data and source:
return _error(
ret,
'\'source\' cannot be used in combination with \'data\''
)
elif data is None:
data = {}
configmap = __salt__['kubernetes.show_configmap'](name, namespace, **kwargs)
if configmap is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The configmap is going to be created'
return ret
res = __salt__['kubernetes.create_configmap'](name=name,
namespace=namespace,
data=data,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes']['{0}.{1}'.format(namespace, name)] = {
'old': {},
'new': res}
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The configmap is going to be replaced'
return ret
# TODO: improve checks # pylint: disable=fixme
log.info('Forcing the recreation of the service')
ret['comment'] = 'The configmap is already present. Forcing recreation'
res = __salt__['kubernetes.replace_configmap'](
name=name,
namespace=namespace,
data=data,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes'] = {
'data': res['data']
}
ret['result'] = True
return ret | [
"def",
"configmap_present",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"data",
"=",
"None",
",",
"source",
"=",
"None",
",",
"template",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes... | Ensures that the named configmap is present inside of the specified namespace
with the given data.
If the configmap exists it will be replaced.
name
The name of the configmap.
namespace
The namespace holding the configmap. The 'default' one is going to be
used unless a different one is specified.
data
The dictionary holding the configmaps.
source
A file containing the data of the configmap in plain format.
template
Template engine to be used to render the source file. | [
"Ensures",
"that",
"the",
"named",
"configmap",
"is",
"present",
"inside",
"of",
"the",
"specified",
"namespace",
"with",
"the",
"given",
"data",
".",
"If",
"the",
"configmap",
"exists",
"it",
"will",
"be",
"replaced",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L637-L717 | train |
saltstack/salt | salt/states/kubernetes.py | pod_absent | def pod_absent(name, namespace='default', **kwargs):
'''
Ensures that the named pod is absent from the given namespace.
name
The name of the pod
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs)
if pod is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The pod does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The pod is going to be deleted'
ret['result'] = None
return ret
res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs)
if res['code'] == 200 or res['code'] is None:
ret['result'] = True
ret['changes'] = {
'kubernetes.pod': {
'new': 'absent', 'old': 'present'}}
if res['code'] is None:
ret['comment'] = 'In progress'
else:
ret['comment'] = res['message']
else:
ret['comment'] = 'Something went wrong, response: {0}'.format(res)
return ret | python | def pod_absent(name, namespace='default', **kwargs):
'''
Ensures that the named pod is absent from the given namespace.
name
The name of the pod
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs)
if pod is None:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The pod does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The pod is going to be deleted'
ret['result'] = None
return ret
res = __salt__['kubernetes.delete_pod'](name, namespace, **kwargs)
if res['code'] == 200 or res['code'] is None:
ret['result'] = True
ret['changes'] = {
'kubernetes.pod': {
'new': 'absent', 'old': 'present'}}
if res['code'] is None:
ret['comment'] = 'In progress'
else:
ret['comment'] = res['message']
else:
ret['comment'] = 'Something went wrong, response: {0}'.format(res)
return ret | [
"def",
"pod_absent",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"pod"... | Ensures that the named pod is absent from the given namespace.
name
The name of the pod
namespace
The name of the namespace | [
"Ensures",
"that",
"the",
"named",
"pod",
"is",
"absent",
"from",
"the",
"given",
"namespace",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L720-L761 | train |
saltstack/salt | salt/states/kubernetes.py | pod_present | def pod_present(
name,
namespace='default',
metadata=None,
spec=None,
source='',
template='',
**kwargs):
'''
Ensures that the named pod is present inside of the specified
namespace with the given metadata and spec.
If the pod exists it will be replaced.
name
The name of the pod.
namespace
The namespace holding the pod. The 'default' one is going to be
used unless a different one is specified.
metadata
The metadata of the pod object.
spec
The spec of the pod object.
source
A file containing the definition of the pod (metadata and
spec) in the official kubernetes format.
template
Template engine to be used to render the source file.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if (metadata or spec) and source:
return _error(
ret,
'\'source\' cannot be used in combination with \'metadata\' or '
'\'spec\''
)
if metadata is None:
metadata = {}
if spec is None:
spec = {}
pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs)
if pod is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The pod is going to be created'
return ret
res = __salt__['kubernetes.create_pod'](name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes']['{0}.{1}'.format(namespace, name)] = {
'old': {},
'new': res}
else:
if __opts__['test']:
ret['result'] = None
return ret
# TODO: fix replace_namespaced_pod validation issues
ret['comment'] = 'salt is currently unable to replace a pod without ' \
'deleting it. Please perform the removal of the pod requiring ' \
'the \'pod_absent\' state if this is the desired behaviour.'
ret['result'] = False
return ret
ret['changes'] = {
'metadata': metadata,
'spec': spec
}
ret['result'] = True
return ret | python | def pod_present(
name,
namespace='default',
metadata=None,
spec=None,
source='',
template='',
**kwargs):
'''
Ensures that the named pod is present inside of the specified
namespace with the given metadata and spec.
If the pod exists it will be replaced.
name
The name of the pod.
namespace
The namespace holding the pod. The 'default' one is going to be
used unless a different one is specified.
metadata
The metadata of the pod object.
spec
The spec of the pod object.
source
A file containing the definition of the pod (metadata and
spec) in the official kubernetes format.
template
Template engine to be used to render the source file.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if (metadata or spec) and source:
return _error(
ret,
'\'source\' cannot be used in combination with \'metadata\' or '
'\'spec\''
)
if metadata is None:
metadata = {}
if spec is None:
spec = {}
pod = __salt__['kubernetes.show_pod'](name, namespace, **kwargs)
if pod is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The pod is going to be created'
return ret
res = __salt__['kubernetes.create_pod'](name=name,
namespace=namespace,
metadata=metadata,
spec=spec,
source=source,
template=template,
saltenv=__env__,
**kwargs)
ret['changes']['{0}.{1}'.format(namespace, name)] = {
'old': {},
'new': res}
else:
if __opts__['test']:
ret['result'] = None
return ret
# TODO: fix replace_namespaced_pod validation issues
ret['comment'] = 'salt is currently unable to replace a pod without ' \
'deleting it. Please perform the removal of the pod requiring ' \
'the \'pod_absent\' state if this is the desired behaviour.'
ret['result'] = False
return ret
ret['changes'] = {
'metadata': metadata,
'spec': spec
}
ret['result'] = True
return ret | [
"def",
"pod_present",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"metadata",
"=",
"None",
",",
"spec",
"=",
"None",
",",
"source",
"=",
"''",
",",
"template",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
... | Ensures that the named pod is present inside of the specified
namespace with the given metadata and spec.
If the pod exists it will be replaced.
name
The name of the pod.
namespace
The namespace holding the pod. The 'default' one is going to be
used unless a different one is specified.
metadata
The metadata of the pod object.
spec
The spec of the pod object.
source
A file containing the definition of the pod (metadata and
spec) in the official kubernetes format.
template
Template engine to be used to render the source file. | [
"Ensures",
"that",
"the",
"named",
"pod",
"is",
"present",
"inside",
"of",
"the",
"specified",
"namespace",
"with",
"the",
"given",
"metadata",
"and",
"spec",
".",
"If",
"the",
"pod",
"exists",
"it",
"will",
"be",
"replaced",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L764-L850 | train |
saltstack/salt | salt/states/kubernetes.py | node_label_absent | def node_label_absent(name, node, **kwargs):
'''
Ensures that the named label is absent from the node.
name
The name of the label
node
The name of the node
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
labels = __salt__['kubernetes.node_labels'](node, **kwargs)
if name not in labels:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The label does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The label is going to be deleted'
ret['result'] = None
return ret
__salt__['kubernetes.node_remove_label'](
node_name=node,
label_name=name,
**kwargs)
ret['result'] = True
ret['changes'] = {
'kubernetes.node_label': {
'new': 'absent', 'old': 'present'}}
ret['comment'] = 'Label removed from node'
return ret | python | def node_label_absent(name, node, **kwargs):
'''
Ensures that the named label is absent from the node.
name
The name of the label
node
The name of the node
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
labels = __salt__['kubernetes.node_labels'](node, **kwargs)
if name not in labels:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The label does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The label is going to be deleted'
ret['result'] = None
return ret
__salt__['kubernetes.node_remove_label'](
node_name=node,
label_name=name,
**kwargs)
ret['result'] = True
ret['changes'] = {
'kubernetes.node_label': {
'new': 'absent', 'old': 'present'}}
ret['comment'] = 'Label removed from node'
return ret | [
"def",
"node_label_absent",
"(",
"name",
",",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"labels",
"=",
"__sal... | Ensures that the named label is absent from the node.
name
The name of the label
node
The name of the node | [
"Ensures",
"that",
"the",
"named",
"label",
"is",
"absent",
"from",
"the",
"node",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L853-L892 | train |
saltstack/salt | salt/states/kubernetes.py | node_label_folder_absent | def node_label_folder_absent(name, node, **kwargs):
'''
Ensures the label folder doesn't exist on the specified node.
name
The name of label folder
node
The name of the node
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
labels = __salt__['kubernetes.node_labels'](node, **kwargs)
folder = name.strip("/") + "/"
labels_to_drop = []
new_labels = []
for label in labels:
if label.startswith(folder):
labels_to_drop.append(label)
else:
new_labels.append(label)
if not labels_to_drop:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The label folder does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The label folder is going to be deleted'
ret['result'] = None
return ret
for label in labels_to_drop:
__salt__['kubernetes.node_remove_label'](
node_name=node,
label_name=label,
**kwargs)
ret['result'] = True
ret['changes'] = {
'kubernetes.node_label_folder_absent': {
'old': list(labels),
'new': new_labels,
}
}
ret['comment'] = 'Label folder removed from node'
return ret | python | def node_label_folder_absent(name, node, **kwargs):
'''
Ensures the label folder doesn't exist on the specified node.
name
The name of label folder
node
The name of the node
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
labels = __salt__['kubernetes.node_labels'](node, **kwargs)
folder = name.strip("/") + "/"
labels_to_drop = []
new_labels = []
for label in labels:
if label.startswith(folder):
labels_to_drop.append(label)
else:
new_labels.append(label)
if not labels_to_drop:
ret['result'] = True if not __opts__['test'] else None
ret['comment'] = 'The label folder does not exist'
return ret
if __opts__['test']:
ret['comment'] = 'The label folder is going to be deleted'
ret['result'] = None
return ret
for label in labels_to_drop:
__salt__['kubernetes.node_remove_label'](
node_name=node,
label_name=label,
**kwargs)
ret['result'] = True
ret['changes'] = {
'kubernetes.node_label_folder_absent': {
'old': list(labels),
'new': new_labels,
}
}
ret['comment'] = 'Label folder removed from node'
return ret | [
"def",
"node_label_folder_absent",
"(",
"name",
",",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"labels",
"=",
... | Ensures the label folder doesn't exist on the specified node.
name
The name of label folder
node
The name of the node | [
"Ensures",
"the",
"label",
"folder",
"doesn",
"t",
"exist",
"on",
"the",
"specified",
"node",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L895-L946 | train |
saltstack/salt | salt/states/kubernetes.py | node_label_present | def node_label_present(
name,
node,
value,
**kwargs):
'''
Ensures that the named label is set on the named node
with the given value.
If the label exists it will be replaced.
name
The name of the label.
value
Value of the label.
node
Node to change.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
labels = __salt__['kubernetes.node_labels'](node, **kwargs)
if name not in labels:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The label is going to be set'
return ret
__salt__['kubernetes.node_add_label'](label_name=name,
label_value=value,
node_name=node,
**kwargs)
elif labels[name] == value:
ret['result'] = True
ret['comment'] = 'The label is already set and has the specified value'
return ret
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The label is going to be updated'
return ret
ret['comment'] = 'The label is already set, changing the value'
__salt__['kubernetes.node_add_label'](
node_name=node,
label_name=name,
label_value=value,
**kwargs)
old_labels = copy.copy(labels)
labels[name] = value
ret['changes']['{0}.{1}'.format(node, name)] = {
'old': old_labels,
'new': labels}
ret['result'] = True
return ret | python | def node_label_present(
name,
node,
value,
**kwargs):
'''
Ensures that the named label is set on the named node
with the given value.
If the label exists it will be replaced.
name
The name of the label.
value
Value of the label.
node
Node to change.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
labels = __salt__['kubernetes.node_labels'](node, **kwargs)
if name not in labels:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The label is going to be set'
return ret
__salt__['kubernetes.node_add_label'](label_name=name,
label_value=value,
node_name=node,
**kwargs)
elif labels[name] == value:
ret['result'] = True
ret['comment'] = 'The label is already set and has the specified value'
return ret
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'The label is going to be updated'
return ret
ret['comment'] = 'The label is already set, changing the value'
__salt__['kubernetes.node_add_label'](
node_name=node,
label_name=name,
label_value=value,
**kwargs)
old_labels = copy.copy(labels)
labels[name] = value
ret['changes']['{0}.{1}'.format(node, name)] = {
'old': old_labels,
'new': labels}
ret['result'] = True
return ret | [
"def",
"node_label_present",
"(",
"name",
",",
"node",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"label... | Ensures that the named label is set on the named node
with the given value.
If the label exists it will be replaced.
name
The name of the label.
value
Value of the label.
node
Node to change. | [
"Ensures",
"that",
"the",
"named",
"label",
"is",
"set",
"on",
"the",
"named",
"node",
"with",
"the",
"given",
"value",
".",
"If",
"the",
"label",
"exists",
"it",
"will",
"be",
"replaced",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kubernetes.py#L949-L1009 | train |
saltstack/salt | salt/proxy/esxvm.py | init | def init(opts):
'''
This function gets called when the proxy starts up. For
login the protocol and port are cached.
'''
log.debug('Initting esxvm proxy module in process %s', os.getpid())
log.debug('Validating esxvm proxy input')
proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {}))
log.trace('proxy_conf = %s', proxy_conf)
# TODO json schema validation
# Save mandatory fields in cache
for key in ('vcenter', 'datacenter', 'mechanism'):
DETAILS[key] = proxy_conf[key]
# Additional validation
if DETAILS['mechanism'] == 'userpass':
if 'username' not in proxy_conf:
raise excs.InvalidProxyInputError(
'Mechanism is set to \'userpass\' , but no '
'\'username\' key found in pillar for this proxy.')
if 'passwords' not in proxy_conf:
raise excs.InvalidProxyInputError(
'Mechanism is set to \'userpass\' , but no '
'\'passwords\' key found in pillar for this proxy.')
for key in ('username', 'passwords'):
DETAILS[key] = proxy_conf[key]
else:
if 'domain' not in proxy_conf:
raise excs.InvalidProxyInputError(
'Mechanism is set to \'sspi\' , but no '
'\'domain\' key found in pillar for this proxy.')
if 'principal' not in proxy_conf:
raise excs.InvalidProxyInputError(
'Mechanism is set to \'sspi\' , but no '
'\'principal\' key found in pillar for this proxy.')
for key in ('domain', 'principal'):
DETAILS[key] = proxy_conf[key]
# Save optional
DETAILS['protocol'] = proxy_conf.get('protocol')
DETAILS['port'] = proxy_conf.get('port')
# Test connection
if DETAILS['mechanism'] == 'userpass':
# Get the correct login details
log.debug('Retrieving credentials and testing vCenter connection for '
'mehchanism \'userpass\'')
try:
username, password = find_credentials()
DETAILS['password'] = password
except excs.SaltSystemExit as err:
log.critical('Error: %s', err)
return False
return True | python | def init(opts):
'''
This function gets called when the proxy starts up. For
login the protocol and port are cached.
'''
log.debug('Initting esxvm proxy module in process %s', os.getpid())
log.debug('Validating esxvm proxy input')
proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {}))
log.trace('proxy_conf = %s', proxy_conf)
# TODO json schema validation
# Save mandatory fields in cache
for key in ('vcenter', 'datacenter', 'mechanism'):
DETAILS[key] = proxy_conf[key]
# Additional validation
if DETAILS['mechanism'] == 'userpass':
if 'username' not in proxy_conf:
raise excs.InvalidProxyInputError(
'Mechanism is set to \'userpass\' , but no '
'\'username\' key found in pillar for this proxy.')
if 'passwords' not in proxy_conf:
raise excs.InvalidProxyInputError(
'Mechanism is set to \'userpass\' , but no '
'\'passwords\' key found in pillar for this proxy.')
for key in ('username', 'passwords'):
DETAILS[key] = proxy_conf[key]
else:
if 'domain' not in proxy_conf:
raise excs.InvalidProxyInputError(
'Mechanism is set to \'sspi\' , but no '
'\'domain\' key found in pillar for this proxy.')
if 'principal' not in proxy_conf:
raise excs.InvalidProxyInputError(
'Mechanism is set to \'sspi\' , but no '
'\'principal\' key found in pillar for this proxy.')
for key in ('domain', 'principal'):
DETAILS[key] = proxy_conf[key]
# Save optional
DETAILS['protocol'] = proxy_conf.get('protocol')
DETAILS['port'] = proxy_conf.get('port')
# Test connection
if DETAILS['mechanism'] == 'userpass':
# Get the correct login details
log.debug('Retrieving credentials and testing vCenter connection for '
'mehchanism \'userpass\'')
try:
username, password = find_credentials()
DETAILS['password'] = password
except excs.SaltSystemExit as err:
log.critical('Error: %s', err)
return False
return True | [
"def",
"init",
"(",
"opts",
")",
":",
"log",
".",
"debug",
"(",
"'Initting esxvm proxy module in process %s'",
",",
"os",
".",
"getpid",
"(",
")",
")",
"log",
".",
"debug",
"(",
"'Validating esxvm proxy input'",
")",
"proxy_conf",
"=",
"merge",
"(",
"opts",
... | This function gets called when the proxy starts up. For
login the protocol and port are cached. | [
"This",
"function",
"gets",
"called",
"when",
"the",
"proxy",
"starts",
"up",
".",
"For",
"login",
"the",
"protocol",
"and",
"port",
"are",
"cached",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxvm.py#L180-L234 | train |
saltstack/salt | salt/proxy/esxvm.py | find_credentials | def find_credentials():
'''
Cycle through all the possible credentials and return the first one that
works.
'''
# if the username and password were already found don't go through the
# connection process again
if 'username' in DETAILS and 'password' in DETAILS:
return DETAILS['username'], DETAILS['password']
passwords = __pillar__['proxy']['passwords']
for password in passwords:
DETAILS['password'] = password
if not __salt__['vsphere.test_vcenter_connection']():
# We are unable to authenticate
continue
# If we have data returned from above, we've successfully authenticated.
return DETAILS['username'], password
# We've reached the end of the list without successfully authenticating.
raise excs.VMwareConnectionError('Cannot complete login due to '
'incorrect credentials.') | python | def find_credentials():
'''
Cycle through all the possible credentials and return the first one that
works.
'''
# if the username and password were already found don't go through the
# connection process again
if 'username' in DETAILS and 'password' in DETAILS:
return DETAILS['username'], DETAILS['password']
passwords = __pillar__['proxy']['passwords']
for password in passwords:
DETAILS['password'] = password
if not __salt__['vsphere.test_vcenter_connection']():
# We are unable to authenticate
continue
# If we have data returned from above, we've successfully authenticated.
return DETAILS['username'], password
# We've reached the end of the list without successfully authenticating.
raise excs.VMwareConnectionError('Cannot complete login due to '
'incorrect credentials.') | [
"def",
"find_credentials",
"(",
")",
":",
"# if the username and password were already found don't go through the",
"# connection process again",
"if",
"'username'",
"in",
"DETAILS",
"and",
"'password'",
"in",
"DETAILS",
":",
"return",
"DETAILS",
"[",
"'username'",
"]",
","... | Cycle through all the possible credentials and return the first one that
works. | [
"Cycle",
"through",
"all",
"the",
"possible",
"credentials",
"and",
"return",
"the",
"first",
"one",
"that",
"works",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxvm.py#L258-L279 | train |
saltstack/salt | salt/modules/devmap.py | multipath_flush | def multipath_flush(device):
'''
Device-Mapper Multipath flush
CLI Example:
.. code-block:: bash
salt '*' devmap.multipath_flush mpath1
'''
if not os.path.exists(device):
return '{0} does not exist'.format(device)
cmd = 'multipath -f {0}'.format(device)
return __salt__['cmd.run'](cmd).splitlines() | python | def multipath_flush(device):
'''
Device-Mapper Multipath flush
CLI Example:
.. code-block:: bash
salt '*' devmap.multipath_flush mpath1
'''
if not os.path.exists(device):
return '{0} does not exist'.format(device)
cmd = 'multipath -f {0}'.format(device)
return __salt__['cmd.run'](cmd).splitlines() | [
"def",
"multipath_flush",
"(",
"device",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"device",
")",
":",
"return",
"'{0} does not exist'",
".",
"format",
"(",
"device",
")",
"cmd",
"=",
"'multipath -f {0}'",
".",
"format",
"(",
"device",
... | Device-Mapper Multipath flush
CLI Example:
.. code-block:: bash
salt '*' devmap.multipath_flush mpath1 | [
"Device",
"-",
"Mapper",
"Multipath",
"flush"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/devmap.py#L23-L37 | train |
saltstack/salt | salt/states/debconfmod.py | set_file | def set_file(name, source, template=None, context=None, defaults=None, **kwargs):
'''
Set debconf selections from a file or a template
.. code-block:: yaml
<state_id>:
debconf.set_file:
- source: salt://pathto/pkg.selections
<state_id>:
debconf.set_file:
- source: salt://pathto/pkg.selections?saltenv=myenvironment
<state_id>:
debconf.set_file:
- source: salt://pathto/pkg.selections.jinja2
- template: jinja
- context:
some_value: "false"
source:
The location of the file containing the package selections
template
If this setting is applied then the named templating engine will be
used to render the package selections file, currently jinja, mako, and
wempy are supported
context
Overrides default context variables passed to the template.
defaults
Default context passed to the template.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if context is None:
context = {}
elif not isinstance(context, dict):
ret['result'] = False
ret['comment'] = 'Context must be formed as a dict'
return ret
if defaults is None:
defaults = {}
elif not isinstance(defaults, dict):
ret['result'] = False
ret['comment'] = 'Defaults must be formed as a dict'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Debconf selections would have been set.'
return ret
if template:
result = __salt__['debconf.set_template'](source, template, context, defaults, **kwargs)
else:
result = __salt__['debconf.set_file'](source, **kwargs)
if result:
ret['comment'] = 'Debconf selections were set.'
else:
ret['result'] = False
ret['comment'] = 'Unable to set debconf selections from file.'
return ret | python | def set_file(name, source, template=None, context=None, defaults=None, **kwargs):
'''
Set debconf selections from a file or a template
.. code-block:: yaml
<state_id>:
debconf.set_file:
- source: salt://pathto/pkg.selections
<state_id>:
debconf.set_file:
- source: salt://pathto/pkg.selections?saltenv=myenvironment
<state_id>:
debconf.set_file:
- source: salt://pathto/pkg.selections.jinja2
- template: jinja
- context:
some_value: "false"
source:
The location of the file containing the package selections
template
If this setting is applied then the named templating engine will be
used to render the package selections file, currently jinja, mako, and
wempy are supported
context
Overrides default context variables passed to the template.
defaults
Default context passed to the template.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if context is None:
context = {}
elif not isinstance(context, dict):
ret['result'] = False
ret['comment'] = 'Context must be formed as a dict'
return ret
if defaults is None:
defaults = {}
elif not isinstance(defaults, dict):
ret['result'] = False
ret['comment'] = 'Defaults must be formed as a dict'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Debconf selections would have been set.'
return ret
if template:
result = __salt__['debconf.set_template'](source, template, context, defaults, **kwargs)
else:
result = __salt__['debconf.set_file'](source, **kwargs)
if result:
ret['comment'] = 'Debconf selections were set.'
else:
ret['result'] = False
ret['comment'] = 'Unable to set debconf selections from file.'
return ret | [
"def",
"set_file",
"(",
"name",
",",
"source",
",",
"template",
"=",
"None",
",",
"context",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",... | Set debconf selections from a file or a template
.. code-block:: yaml
<state_id>:
debconf.set_file:
- source: salt://pathto/pkg.selections
<state_id>:
debconf.set_file:
- source: salt://pathto/pkg.selections?saltenv=myenvironment
<state_id>:
debconf.set_file:
- source: salt://pathto/pkg.selections.jinja2
- template: jinja
- context:
some_value: "false"
source:
The location of the file containing the package selections
template
If this setting is applied then the named templating engine will be
used to render the package selections file, currently jinja, mako, and
wempy are supported
context
Overrides default context variables passed to the template.
defaults
Default context passed to the template. | [
"Set",
"debconf",
"selections",
"from",
"a",
"file",
"or",
"a",
"template"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/debconfmod.py#L85-L155 | train |
saltstack/salt | salt/states/debconfmod.py | set | def set(name, data, **kwargs):
'''
Set debconf selections
.. code-block:: yaml
<state_id>:
debconf.set:
- name: <name>
- data:
<question>: {'type': <type>, 'value': <value>}
<question>: {'type': <type>, 'value': <value>}
<state_id>:
debconf.set:
- name: <name>
- data:
<question>: {'type': <type>, 'value': <value>}
<question>: {'type': <type>, 'value': <value>}
name:
The package name to set answers for.
data:
A set of questions/answers for debconf. Note that everything under
this must be indented twice.
question:
The question the is being pre-answered
type:
The type of question that is being asked (string, boolean, select, etc.)
value:
The answer to the question
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
current = __salt__['debconf.show'](name)
for (key, args) in six.iteritems(data):
# For debconf data, valid booleans are 'true' and 'false';
# But str()'ing the args['value'] will result in 'True' and 'False'
# which will be ignored and overridden by a dpkg-reconfigure.
# So we should manually set these values to lowercase ones,
# before any str() call is performed.
if args['type'] == 'boolean':
args['value'] = 'true' if args['value'] else 'false'
if current is not None and [key, args['type'], six.text_type(args['value'])] in current:
if ret['comment'] is '':
ret['comment'] = 'Unchanged answers: '
ret['comment'] += ('{0} ').format(key)
else:
if __opts__['test']:
ret['result'] = None
ret['changes'][key] = ('New value: {0}').format(args['value'])
else:
if __salt__['debconf.set'](name, key, args['type'], args['value']):
if args['type'] == 'password':
ret['changes'][key] = '(password hidden)'
else:
ret['changes'][key] = ('{0}').format(args['value'])
else:
ret['result'] = False
ret['comment'] = 'Some settings failed to be applied.'
ret['changes'][key] = 'Failed to set!'
if not ret['changes']:
ret['comment'] = 'All specified answers are already set'
return ret | python | def set(name, data, **kwargs):
'''
Set debconf selections
.. code-block:: yaml
<state_id>:
debconf.set:
- name: <name>
- data:
<question>: {'type': <type>, 'value': <value>}
<question>: {'type': <type>, 'value': <value>}
<state_id>:
debconf.set:
- name: <name>
- data:
<question>: {'type': <type>, 'value': <value>}
<question>: {'type': <type>, 'value': <value>}
name:
The package name to set answers for.
data:
A set of questions/answers for debconf. Note that everything under
this must be indented twice.
question:
The question the is being pre-answered
type:
The type of question that is being asked (string, boolean, select, etc.)
value:
The answer to the question
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
current = __salt__['debconf.show'](name)
for (key, args) in six.iteritems(data):
# For debconf data, valid booleans are 'true' and 'false';
# But str()'ing the args['value'] will result in 'True' and 'False'
# which will be ignored and overridden by a dpkg-reconfigure.
# So we should manually set these values to lowercase ones,
# before any str() call is performed.
if args['type'] == 'boolean':
args['value'] = 'true' if args['value'] else 'false'
if current is not None and [key, args['type'], six.text_type(args['value'])] in current:
if ret['comment'] is '':
ret['comment'] = 'Unchanged answers: '
ret['comment'] += ('{0} ').format(key)
else:
if __opts__['test']:
ret['result'] = None
ret['changes'][key] = ('New value: {0}').format(args['value'])
else:
if __salt__['debconf.set'](name, key, args['type'], args['value']):
if args['type'] == 'password':
ret['changes'][key] = '(password hidden)'
else:
ret['changes'][key] = ('{0}').format(args['value'])
else:
ret['result'] = False
ret['comment'] = 'Some settings failed to be applied.'
ret['changes'][key] = 'Failed to set!'
if not ret['changes']:
ret['comment'] = 'All specified answers are already set'
return ret | [
"def",
"set",
"(",
"name",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"current",
"=",
"__salt__",
"[",
... | Set debconf selections
.. code-block:: yaml
<state_id>:
debconf.set:
- name: <name>
- data:
<question>: {'type': <type>, 'value': <value>}
<question>: {'type': <type>, 'value': <value>}
<state_id>:
debconf.set:
- name: <name>
- data:
<question>: {'type': <type>, 'value': <value>}
<question>: {'type': <type>, 'value': <value>}
name:
The package name to set answers for.
data:
A set of questions/answers for debconf. Note that everything under
this must be indented twice.
question:
The question the is being pre-answered
type:
The type of question that is being asked (string, boolean, select, etc.)
value:
The answer to the question | [
"Set",
"debconf",
"selections"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/debconfmod.py#L158-L234 | train |
saltstack/salt | salt/engines/docker_events.py | start | def start(docker_url='unix://var/run/docker.sock',
timeout=CLIENT_TIMEOUT,
tag='salt/engines/docker_events',
filters=None):
'''
Scan for Docker events and fire events
Example Config
.. code-block:: yaml
engines:
- docker_events:
docker_url: unix://var/run/docker.sock
filters:
event:
- start
- stop
- die
- oom
The config above sets up engines to listen
for events from the Docker daemon and publish
them to the Salt event bus.
For filter reference, see https://docs.docker.com/engine/reference/commandline/events/
'''
if __opts__.get('__role') == 'master':
fire_master = salt.utils.event.get_master_event(
__opts__,
__opts__['sock_dir']).fire_event
else:
fire_master = None
def fire(tag, msg):
'''
How to fire the event
'''
if fire_master:
fire_master(msg, tag)
else:
__salt__['event.send'](tag, msg)
try:
# docker-py 2.0 renamed this client attribute
client = docker.APIClient(base_url=docker_url, timeout=timeout)
except AttributeError:
client = docker.Client(base_url=docker_url, timeout=timeout)
try:
events = client.events(filters=filters)
for event in events:
data = salt.utils.json.loads(event.decode(__salt_system_encoding__, errors='replace'))
# https://github.com/docker/cli/blob/master/cli/command/system/events.go#L109
# https://github.com/docker/engine-api/blob/master/types/events/events.go
# Each output includes the event type, actor id, name and action.
# status field can be ommited
if data['Action']:
fire('{0}/{1}'.format(tag, data['Action']), data)
else:
fire('{0}/{1}'.format(tag, data['status']), data)
except Exception:
traceback.print_exc() | python | def start(docker_url='unix://var/run/docker.sock',
timeout=CLIENT_TIMEOUT,
tag='salt/engines/docker_events',
filters=None):
'''
Scan for Docker events and fire events
Example Config
.. code-block:: yaml
engines:
- docker_events:
docker_url: unix://var/run/docker.sock
filters:
event:
- start
- stop
- die
- oom
The config above sets up engines to listen
for events from the Docker daemon and publish
them to the Salt event bus.
For filter reference, see https://docs.docker.com/engine/reference/commandline/events/
'''
if __opts__.get('__role') == 'master':
fire_master = salt.utils.event.get_master_event(
__opts__,
__opts__['sock_dir']).fire_event
else:
fire_master = None
def fire(tag, msg):
'''
How to fire the event
'''
if fire_master:
fire_master(msg, tag)
else:
__salt__['event.send'](tag, msg)
try:
# docker-py 2.0 renamed this client attribute
client = docker.APIClient(base_url=docker_url, timeout=timeout)
except AttributeError:
client = docker.Client(base_url=docker_url, timeout=timeout)
try:
events = client.events(filters=filters)
for event in events:
data = salt.utils.json.loads(event.decode(__salt_system_encoding__, errors='replace'))
# https://github.com/docker/cli/blob/master/cli/command/system/events.go#L109
# https://github.com/docker/engine-api/blob/master/types/events/events.go
# Each output includes the event type, actor id, name and action.
# status field can be ommited
if data['Action']:
fire('{0}/{1}'.format(tag, data['Action']), data)
else:
fire('{0}/{1}'.format(tag, data['status']), data)
except Exception:
traceback.print_exc() | [
"def",
"start",
"(",
"docker_url",
"=",
"'unix://var/run/docker.sock'",
",",
"timeout",
"=",
"CLIENT_TIMEOUT",
",",
"tag",
"=",
"'salt/engines/docker_events'",
",",
"filters",
"=",
"None",
")",
":",
"if",
"__opts__",
".",
"get",
"(",
"'__role'",
")",
"==",
"'m... | Scan for Docker events and fire events
Example Config
.. code-block:: yaml
engines:
- docker_events:
docker_url: unix://var/run/docker.sock
filters:
event:
- start
- stop
- die
- oom
The config above sets up engines to listen
for events from the Docker daemon and publish
them to the Salt event bus.
For filter reference, see https://docs.docker.com/engine/reference/commandline/events/ | [
"Scan",
"for",
"Docker",
"events",
"and",
"fire",
"events"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/docker_events.py#L42-L105 | train |
saltstack/salt | salt/modules/infoblox.py | _get_config | def _get_config(**api_opts):
'''
Return configuration
user passed api_opts override salt config.get vars
'''
config = {
'api_sslverify': True,
'api_url': 'https://INFOBLOX/wapi/v1.2.1',
'api_user': '',
'api_key': '',
}
if '__salt__' in globals():
config_key = '{0}.config'.format(__virtualname__)
config.update(__salt__['config.get'](config_key, {}))
# pylint: disable=C0201
for k in set(config.keys()) & set(api_opts.keys()):
config[k] = api_opts[k]
return config | python | def _get_config(**api_opts):
'''
Return configuration
user passed api_opts override salt config.get vars
'''
config = {
'api_sslverify': True,
'api_url': 'https://INFOBLOX/wapi/v1.2.1',
'api_user': '',
'api_key': '',
}
if '__salt__' in globals():
config_key = '{0}.config'.format(__virtualname__)
config.update(__salt__['config.get'](config_key, {}))
# pylint: disable=C0201
for k in set(config.keys()) & set(api_opts.keys()):
config[k] = api_opts[k]
return config | [
"def",
"_get_config",
"(",
"*",
"*",
"api_opts",
")",
":",
"config",
"=",
"{",
"'api_sslverify'",
":",
"True",
",",
"'api_url'",
":",
"'https://INFOBLOX/wapi/v1.2.1'",
",",
"'api_user'",
":",
"''",
",",
"'api_key'",
":",
"''",
",",
"}",
"if",
"'__salt__'",
... | Return configuration
user passed api_opts override salt config.get vars | [
"Return",
"configuration",
"user",
"passed",
"api_opts",
"override",
"salt",
"config",
".",
"get",
"vars"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L58-L75 | train |
saltstack/salt | salt/modules/infoblox.py | update_host | def update_host(name, data, **api_opts):
'''
Update host record. This is a helper call to update_object.
Find a hosts ``_ref`` then call update_object with the record data.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_host name=fqdn data={}
'''
o = get_host(name=name, **api_opts)
return update_object(objref=o['_ref'], data=data, **api_opts) | python | def update_host(name, data, **api_opts):
'''
Update host record. This is a helper call to update_object.
Find a hosts ``_ref`` then call update_object with the record data.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_host name=fqdn data={}
'''
o = get_host(name=name, **api_opts)
return update_object(objref=o['_ref'], data=data, **api_opts) | [
"def",
"update_host",
"(",
"name",
",",
"data",
",",
"*",
"*",
"api_opts",
")",
":",
"o",
"=",
"get_host",
"(",
"name",
"=",
"name",
",",
"*",
"*",
"api_opts",
")",
"return",
"update_object",
"(",
"objref",
"=",
"o",
"[",
"'_ref'",
"]",
",",
"data"... | Update host record. This is a helper call to update_object.
Find a hosts ``_ref`` then call update_object with the record data.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_host name=fqdn data={} | [
"Update",
"host",
"record",
".",
"This",
"is",
"a",
"helper",
"call",
"to",
"update_object",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L120-L133 | train |
saltstack/salt | salt/modules/infoblox.py | update_object | def update_object(objref, data, **api_opts):
'''
Update raw infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_object objref=[ref_of_object] data={}
'''
if '__opts__' in globals() and __opts__['test']:
return {'Test': 'Would attempt to update object: {0}'.format(objref)}
infoblox = _get_infoblox(**api_opts)
return infoblox.update_object(objref, data) | python | def update_object(objref, data, **api_opts):
'''
Update raw infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_object objref=[ref_of_object] data={}
'''
if '__opts__' in globals() and __opts__['test']:
return {'Test': 'Would attempt to update object: {0}'.format(objref)}
infoblox = _get_infoblox(**api_opts)
return infoblox.update_object(objref, data) | [
"def",
"update_object",
"(",
"objref",
",",
"data",
",",
"*",
"*",
"api_opts",
")",
":",
"if",
"'__opts__'",
"in",
"globals",
"(",
")",
"and",
"__opts__",
"[",
"'test'",
"]",
":",
"return",
"{",
"'Test'",
":",
"'Would attempt to update object: {0}'",
".",
... | Update raw infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_object objref=[ref_of_object] data={} | [
"Update",
"raw",
"infoblox",
"object",
".",
"This",
"is",
"a",
"low",
"level",
"api",
"call",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L136-L149 | train |
saltstack/salt | salt/modules/infoblox.py | delete_object | def delete_object(objref, **api_opts):
'''
Delete infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.delete_object objref=[ref_of_object]
'''
if '__opts__' in globals() and __opts__['test']:
return {'Test': 'Would attempt to delete object: {0}'.format(objref)}
infoblox = _get_infoblox(**api_opts)
return infoblox.delete_object(objref) | python | def delete_object(objref, **api_opts):
'''
Delete infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.delete_object objref=[ref_of_object]
'''
if '__opts__' in globals() and __opts__['test']:
return {'Test': 'Would attempt to delete object: {0}'.format(objref)}
infoblox = _get_infoblox(**api_opts)
return infoblox.delete_object(objref) | [
"def",
"delete_object",
"(",
"objref",
",",
"*",
"*",
"api_opts",
")",
":",
"if",
"'__opts__'",
"in",
"globals",
"(",
")",
"and",
"__opts__",
"[",
"'test'",
"]",
":",
"return",
"{",
"'Test'",
":",
"'Would attempt to delete object: {0}'",
".",
"format",
"(",
... | Delete infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.delete_object objref=[ref_of_object] | [
"Delete",
"infoblox",
"object",
".",
"This",
"is",
"a",
"low",
"level",
"api",
"call",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L152-L165 | train |
saltstack/salt | salt/modules/infoblox.py | create_object | def create_object(object_type, data, **api_opts):
'''
Create raw infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_object object_type=record:host data={}
'''
if '__opts__' in globals() and __opts__['test']:
return {'Test': 'Would attempt to create object: {0}'.format(object_type)}
infoblox = _get_infoblox(**api_opts)
return infoblox.create_object(object_type, data) | python | def create_object(object_type, data, **api_opts):
'''
Create raw infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_object object_type=record:host data={}
'''
if '__opts__' in globals() and __opts__['test']:
return {'Test': 'Would attempt to create object: {0}'.format(object_type)}
infoblox = _get_infoblox(**api_opts)
return infoblox.create_object(object_type, data) | [
"def",
"create_object",
"(",
"object_type",
",",
"data",
",",
"*",
"*",
"api_opts",
")",
":",
"if",
"'__opts__'",
"in",
"globals",
"(",
")",
"and",
"__opts__",
"[",
"'test'",
"]",
":",
"return",
"{",
"'Test'",
":",
"'Would attempt to create object: {0}'",
".... | Create raw infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_object object_type=record:host data={} | [
"Create",
"raw",
"infoblox",
"object",
".",
"This",
"is",
"a",
"low",
"level",
"api",
"call",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L168-L181 | train |
saltstack/salt | salt/modules/infoblox.py | get_object | def get_object(objref, data=None, return_fields=None, max_results=None,
ensure_none_or_one_result=False, **api_opts):
'''
Get raw infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.get_object objref=[_ref of object]
'''
if not data:
data = {}
infoblox = _get_infoblox(**api_opts)
return infoblox.get_object(objref, data, return_fields,
max_results, ensure_none_or_one_result) | python | def get_object(objref, data=None, return_fields=None, max_results=None,
ensure_none_or_one_result=False, **api_opts):
'''
Get raw infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.get_object objref=[_ref of object]
'''
if not data:
data = {}
infoblox = _get_infoblox(**api_opts)
return infoblox.get_object(objref, data, return_fields,
max_results, ensure_none_or_one_result) | [
"def",
"get_object",
"(",
"objref",
",",
"data",
"=",
"None",
",",
"return_fields",
"=",
"None",
",",
"max_results",
"=",
"None",
",",
"ensure_none_or_one_result",
"=",
"False",
",",
"*",
"*",
"api_opts",
")",
":",
"if",
"not",
"data",
":",
"data",
"=",
... | Get raw infoblox object. This is a low level api call.
CLI Example:
.. code-block:: bash
salt-call infoblox.get_object objref=[_ref of object] | [
"Get",
"raw",
"infoblox",
"object",
".",
"This",
"is",
"a",
"low",
"level",
"api",
"call",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L184-L199 | train |
saltstack/salt | salt/modules/infoblox.py | create_cname | def create_cname(data, **api_opts):
'''
Create a cname record.
CLI Example:
.. code-block:: bash
salt-call infoblox.create_cname data={ \
"comment": "cname to example server", \
"name": "example.example.com", \
"zone": "example.com", \
"view": "Internal", \
"canonical": "example-ha-0.example.com" \
}
'''
infoblox = _get_infoblox(**api_opts)
host = infoblox.create_cname(data=data)
return host | python | def create_cname(data, **api_opts):
'''
Create a cname record.
CLI Example:
.. code-block:: bash
salt-call infoblox.create_cname data={ \
"comment": "cname to example server", \
"name": "example.example.com", \
"zone": "example.com", \
"view": "Internal", \
"canonical": "example-ha-0.example.com" \
}
'''
infoblox = _get_infoblox(**api_opts)
host = infoblox.create_cname(data=data)
return host | [
"def",
"create_cname",
"(",
"data",
",",
"*",
"*",
"api_opts",
")",
":",
"infoblox",
"=",
"_get_infoblox",
"(",
"*",
"*",
"api_opts",
")",
"host",
"=",
"infoblox",
".",
"create_cname",
"(",
"data",
"=",
"data",
")",
"return",
"host"
] | Create a cname record.
CLI Example:
.. code-block:: bash
salt-call infoblox.create_cname data={ \
"comment": "cname to example server", \
"name": "example.example.com", \
"zone": "example.com", \
"view": "Internal", \
"canonical": "example-ha-0.example.com" \
} | [
"Create",
"a",
"cname",
"record",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L202-L220 | train |
saltstack/salt | salt/modules/infoblox.py | get_cname | def get_cname(name=None, canonical=None, return_fields=None, **api_opts):
'''
Get CNAME information.
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_cname name=example.example.com
salt-call infoblox.get_cname canonical=example-ha-0.example.com
'''
infoblox = _get_infoblox(**api_opts)
o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields)
return o | python | def get_cname(name=None, canonical=None, return_fields=None, **api_opts):
'''
Get CNAME information.
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_cname name=example.example.com
salt-call infoblox.get_cname canonical=example-ha-0.example.com
'''
infoblox = _get_infoblox(**api_opts)
o = infoblox.get_cname(name=name, canonical=canonical, return_fields=return_fields)
return o | [
"def",
"get_cname",
"(",
"name",
"=",
"None",
",",
"canonical",
"=",
"None",
",",
"return_fields",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"infoblox",
"=",
"_get_infoblox",
"(",
"*",
"*",
"api_opts",
")",
"o",
"=",
"infoblox",
".",
"get_cname... | Get CNAME information.
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_cname name=example.example.com
salt-call infoblox.get_cname canonical=example-ha-0.example.com | [
"Get",
"CNAME",
"information",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L223-L236 | train |
saltstack/salt | salt/modules/infoblox.py | update_cname | def update_cname(name, data, **api_opts):
'''
Update CNAME. This is a helper call to update_object.
Find a CNAME ``_ref`` then call update_object with the record data.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_cname name=example.example.com data="{
'canonical':'example-ha-0.example.com',
'use_ttl':true,
'ttl':200,
'comment':'Salt managed CNAME'}"
'''
o = get_cname(name=name, **api_opts)
if not o:
raise Exception('CNAME record not found')
return update_object(objref=o['_ref'], data=data, **api_opts) | python | def update_cname(name, data, **api_opts):
'''
Update CNAME. This is a helper call to update_object.
Find a CNAME ``_ref`` then call update_object with the record data.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_cname name=example.example.com data="{
'canonical':'example-ha-0.example.com',
'use_ttl':true,
'ttl':200,
'comment':'Salt managed CNAME'}"
'''
o = get_cname(name=name, **api_opts)
if not o:
raise Exception('CNAME record not found')
return update_object(objref=o['_ref'], data=data, **api_opts) | [
"def",
"update_cname",
"(",
"name",
",",
"data",
",",
"*",
"*",
"api_opts",
")",
":",
"o",
"=",
"get_cname",
"(",
"name",
"=",
"name",
",",
"*",
"*",
"api_opts",
")",
"if",
"not",
"o",
":",
"raise",
"Exception",
"(",
"'CNAME record not found'",
")",
... | Update CNAME. This is a helper call to update_object.
Find a CNAME ``_ref`` then call update_object with the record data.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_cname name=example.example.com data="{
'canonical':'example-ha-0.example.com',
'use_ttl':true,
'ttl':200,
'comment':'Salt managed CNAME'}" | [
"Update",
"CNAME",
".",
"This",
"is",
"a",
"helper",
"call",
"to",
"update_object",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L239-L258 | train |
saltstack/salt | salt/modules/infoblox.py | delete_cname | def delete_cname(name=None, canonical=None, **api_opts):
'''
Delete CNAME. This is a helper call to delete_object.
If record is not found, return True
CLI Examples:
.. code-block:: bash
salt-call infoblox.delete_cname name=example.example.com
salt-call infoblox.delete_cname canonical=example-ha-0.example.com
'''
cname = get_cname(name=name, canonical=canonical, **api_opts)
if cname:
return delete_object(cname['_ref'], **api_opts)
return True | python | def delete_cname(name=None, canonical=None, **api_opts):
'''
Delete CNAME. This is a helper call to delete_object.
If record is not found, return True
CLI Examples:
.. code-block:: bash
salt-call infoblox.delete_cname name=example.example.com
salt-call infoblox.delete_cname canonical=example-ha-0.example.com
'''
cname = get_cname(name=name, canonical=canonical, **api_opts)
if cname:
return delete_object(cname['_ref'], **api_opts)
return True | [
"def",
"delete_cname",
"(",
"name",
"=",
"None",
",",
"canonical",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"cname",
"=",
"get_cname",
"(",
"name",
"=",
"name",
",",
"canonical",
"=",
"canonical",
",",
"*",
"*",
"api_opts",
")",
"if",
"cname... | Delete CNAME. This is a helper call to delete_object.
If record is not found, return True
CLI Examples:
.. code-block:: bash
salt-call infoblox.delete_cname name=example.example.com
salt-call infoblox.delete_cname canonical=example-ha-0.example.com | [
"Delete",
"CNAME",
".",
"This",
"is",
"a",
"helper",
"call",
"to",
"delete_object",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L261-L277 | train |
saltstack/salt | salt/modules/infoblox.py | get_host | def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts):
'''
Get host information
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_host hostname.domain.ca
salt-call infoblox.get_host ipv4addr=123.123.122.12
salt-call infoblox.get_host mac=00:50:56:84:6e:ae
'''
infoblox = _get_infoblox(**api_opts)
host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields)
return host | python | def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts):
'''
Get host information
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_host hostname.domain.ca
salt-call infoblox.get_host ipv4addr=123.123.122.12
salt-call infoblox.get_host mac=00:50:56:84:6e:ae
'''
infoblox = _get_infoblox(**api_opts)
host = infoblox.get_host(name=name, mac=mac, ipv4addr=ipv4addr, return_fields=return_fields)
return host | [
"def",
"get_host",
"(",
"name",
"=",
"None",
",",
"ipv4addr",
"=",
"None",
",",
"mac",
"=",
"None",
",",
"return_fields",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"infoblox",
"=",
"_get_infoblox",
"(",
"*",
"*",
"api_opts",
")",
"host",
"=",... | Get host information
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_host hostname.domain.ca
salt-call infoblox.get_host ipv4addr=123.123.122.12
salt-call infoblox.get_host mac=00:50:56:84:6e:ae | [
"Get",
"host",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L280-L294 | train |
saltstack/salt | salt/modules/infoblox.py | get_host_advanced | def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts):
'''
Get all host information
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_advanced hostname.domain.ca
'''
infoblox = _get_infoblox(**api_opts)
host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr)
return host | python | def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts):
'''
Get all host information
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_advanced hostname.domain.ca
'''
infoblox = _get_infoblox(**api_opts)
host = infoblox.get_host_advanced(name=name, mac=mac, ipv4addr=ipv4addr)
return host | [
"def",
"get_host_advanced",
"(",
"name",
"=",
"None",
",",
"ipv4addr",
"=",
"None",
",",
"mac",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"infoblox",
"=",
"_get_infoblox",
"(",
"*",
"*",
"api_opts",
")",
"host",
"=",
"infoblox",
".",
"get_host_... | Get all host information
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_advanced hostname.domain.ca | [
"Get",
"all",
"host",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L297-L309 | train |
saltstack/salt | salt/modules/infoblox.py | get_host_domainname | def get_host_domainname(name, domains=None, **api_opts):
'''
Get host domain name
If no domains are passed, the hostname is checked for a zone in infoblox,
if no zone split on first dot.
If domains are provided, the best match out of the list is returned.
If none are found the return is None
dots at end of names are ignored.
CLI Example:
.. code-block:: bash
salt-call uwl.get_host_domainname name=localhost.t.domain.com \
domains=['domain.com', 't.domain.com.']
# returns: t.domain.com
'''
name = name.lower().rstrip('.')
if not domains:
data = get_host(name=name, **api_opts)
if data and 'zone' in data:
return data['zone'].lower()
else:
if name.count('.') > 1:
return name[name.find('.')+1:]
return name
match = ''
for d in domains:
d = d.lower().rstrip('.')
if name.endswith(d) and len(d) > len(match):
match = d
return match if match else None | python | def get_host_domainname(name, domains=None, **api_opts):
'''
Get host domain name
If no domains are passed, the hostname is checked for a zone in infoblox,
if no zone split on first dot.
If domains are provided, the best match out of the list is returned.
If none are found the return is None
dots at end of names are ignored.
CLI Example:
.. code-block:: bash
salt-call uwl.get_host_domainname name=localhost.t.domain.com \
domains=['domain.com', 't.domain.com.']
# returns: t.domain.com
'''
name = name.lower().rstrip('.')
if not domains:
data = get_host(name=name, **api_opts)
if data and 'zone' in data:
return data['zone'].lower()
else:
if name.count('.') > 1:
return name[name.find('.')+1:]
return name
match = ''
for d in domains:
d = d.lower().rstrip('.')
if name.endswith(d) and len(d) > len(match):
match = d
return match if match else None | [
"def",
"get_host_domainname",
"(",
"name",
",",
"domains",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
".",
"rstrip",
"(",
"'.'",
")",
"if",
"not",
"domains",
":",
"data",
"=",
"get_host",
"(",
"na... | Get host domain name
If no domains are passed, the hostname is checked for a zone in infoblox,
if no zone split on first dot.
If domains are provided, the best match out of the list is returned.
If none are found the return is None
dots at end of names are ignored.
CLI Example:
.. code-block:: bash
salt-call uwl.get_host_domainname name=localhost.t.domain.com \
domains=['domain.com', 't.domain.com.']
# returns: t.domain.com | [
"Get",
"host",
"domain",
"name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L312-L348 | train |
saltstack/salt | salt/modules/infoblox.py | get_host_hostname | def get_host_hostname(name, domains=None, **api_opts):
'''
Get hostname
If no domains are passed, the hostname is checked for a zone in infoblox,
if no zone split on first dot.
If domains are provided, the best match out of the list is truncated from
the fqdn leaving the hostname.
If no matching domains are found the fqdn is returned.
dots at end of names are ignored.
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \
domains="['domain.com', 't.domain.com']"
#returns: localhost.xxx
salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com
#returns: localhost
'''
name = name.lower().rstrip('.')
if not domains:
return name.split('.')[0]
domain = get_host_domainname(name, domains, **api_opts)
if domain and domain in name:
return name.rsplit('.' + domain)[0]
return name | python | def get_host_hostname(name, domains=None, **api_opts):
'''
Get hostname
If no domains are passed, the hostname is checked for a zone in infoblox,
if no zone split on first dot.
If domains are provided, the best match out of the list is truncated from
the fqdn leaving the hostname.
If no matching domains are found the fqdn is returned.
dots at end of names are ignored.
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \
domains="['domain.com', 't.domain.com']"
#returns: localhost.xxx
salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com
#returns: localhost
'''
name = name.lower().rstrip('.')
if not domains:
return name.split('.')[0]
domain = get_host_domainname(name, domains, **api_opts)
if domain and domain in name:
return name.rsplit('.' + domain)[0]
return name | [
"def",
"get_host_hostname",
"(",
"name",
",",
"domains",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
".",
"rstrip",
"(",
"'.'",
")",
"if",
"not",
"domains",
":",
"return",
"name",
".",
"split",
"("... | Get hostname
If no domains are passed, the hostname is checked for a zone in infoblox,
if no zone split on first dot.
If domains are provided, the best match out of the list is truncated from
the fqdn leaving the hostname.
If no matching domains are found the fqdn is returned.
dots at end of names are ignored.
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com \
domains="['domain.com', 't.domain.com']"
#returns: localhost.xxx
salt-call infoblox.get_host_hostname fqdn=localhost.xxx.t.domain.com
#returns: localhost | [
"Get",
"hostname"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L351-L382 | train |
saltstack/salt | salt/modules/infoblox.py | get_host_mac | def get_host_mac(name=None, allow_array=False, **api_opts):
'''
Get mac address from host record.
Use `allow_array` to return possible multiple values.
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_mac host=localhost.domain.com
'''
data = get_host(name=name, **api_opts)
if data and 'ipv4addrs' in data:
l = []
for a in data['ipv4addrs']:
if 'mac' in a:
l.append(a['mac'])
if allow_array:
return l
if l:
return l[0]
return None | python | def get_host_mac(name=None, allow_array=False, **api_opts):
'''
Get mac address from host record.
Use `allow_array` to return possible multiple values.
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_mac host=localhost.domain.com
'''
data = get_host(name=name, **api_opts)
if data and 'ipv4addrs' in data:
l = []
for a in data['ipv4addrs']:
if 'mac' in a:
l.append(a['mac'])
if allow_array:
return l
if l:
return l[0]
return None | [
"def",
"get_host_mac",
"(",
"name",
"=",
"None",
",",
"allow_array",
"=",
"False",
",",
"*",
"*",
"api_opts",
")",
":",
"data",
"=",
"get_host",
"(",
"name",
"=",
"name",
",",
"*",
"*",
"api_opts",
")",
"if",
"data",
"and",
"'ipv4addrs'",
"in",
"data... | Get mac address from host record.
Use `allow_array` to return possible multiple values.
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_mac host=localhost.domain.com | [
"Get",
"mac",
"address",
"from",
"host",
"record",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L385-L407 | train |
saltstack/salt | salt/modules/infoblox.py | get_host_ipv4 | def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts):
'''
Get ipv4 address from host record.
Use `allow_array` to return possible multiple values.
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_host_ipv4 host=localhost.domain.com
salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae
'''
data = get_host(name=name, mac=mac, **api_opts)
if data and 'ipv4addrs' in data:
l = []
for a in data['ipv4addrs']:
if 'ipv4addr' in a:
l.append(a['ipv4addr'])
if allow_array:
return l
if l:
return l[0]
return None | python | def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts):
'''
Get ipv4 address from host record.
Use `allow_array` to return possible multiple values.
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_host_ipv4 host=localhost.domain.com
salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae
'''
data = get_host(name=name, mac=mac, **api_opts)
if data and 'ipv4addrs' in data:
l = []
for a in data['ipv4addrs']:
if 'ipv4addr' in a:
l.append(a['ipv4addr'])
if allow_array:
return l
if l:
return l[0]
return None | [
"def",
"get_host_ipv4",
"(",
"name",
"=",
"None",
",",
"mac",
"=",
"None",
",",
"allow_array",
"=",
"False",
",",
"*",
"*",
"api_opts",
")",
":",
"data",
"=",
"get_host",
"(",
"name",
"=",
"name",
",",
"mac",
"=",
"mac",
",",
"*",
"*",
"api_opts",
... | Get ipv4 address from host record.
Use `allow_array` to return possible multiple values.
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_host_ipv4 host=localhost.domain.com
salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae | [
"Get",
"ipv4",
"address",
"from",
"host",
"record",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L410-L433 | train |
saltstack/salt | salt/modules/infoblox.py | get_host_ipv4addr_info | def get_host_ipv4addr_info(ipv4addr=None, mac=None,
discovered_data=None,
return_fields=None, **api_opts):
'''
Get host ipv4addr information
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12
salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae
salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr'
'''
infoblox = _get_infoblox(**api_opts)
return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) | python | def get_host_ipv4addr_info(ipv4addr=None, mac=None,
discovered_data=None,
return_fields=None, **api_opts):
'''
Get host ipv4addr information
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12
salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae
salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr'
'''
infoblox = _get_infoblox(**api_opts)
return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields) | [
"def",
"get_host_ipv4addr_info",
"(",
"ipv4addr",
"=",
"None",
",",
"mac",
"=",
"None",
",",
"discovered_data",
"=",
"None",
",",
"return_fields",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"infoblox",
"=",
"_get_infoblox",
"(",
"*",
"*",
"api_opts"... | Get host ipv4addr information
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12
salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae
salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' | [
"Get",
"host",
"ipv4addr",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L436-L451 | train |
saltstack/salt | salt/modules/infoblox.py | get_host_ipv6addr_info | def get_host_ipv6addr_info(ipv6addr=None, mac=None,
discovered_data=None,
return_fields=None, **api_opts):
'''
Get host ipv6addr information
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348
'''
infoblox = _get_infoblox(**api_opts)
return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) | python | def get_host_ipv6addr_info(ipv6addr=None, mac=None,
discovered_data=None,
return_fields=None, **api_opts):
'''
Get host ipv6addr information
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348
'''
infoblox = _get_infoblox(**api_opts)
return infoblox.get_host_ipv6addr_object(ipv6addr, mac, discovered_data, return_fields) | [
"def",
"get_host_ipv6addr_info",
"(",
"ipv6addr",
"=",
"None",
",",
"mac",
"=",
"None",
",",
"discovered_data",
"=",
"None",
",",
"return_fields",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"infoblox",
"=",
"_get_infoblox",
"(",
"*",
"*",
"api_opts"... | Get host ipv6addr information
CLI Example:
.. code-block:: bash
salt-call infoblox.get_host_ipv6addr_info ipv6addr=2001:db8:85a3:8d3:1349:8a2e:370:7348 | [
"Get",
"host",
"ipv6addr",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L454-L467 | train |
saltstack/salt | salt/modules/infoblox.py | get_network | def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts):
'''
Get list of all networks. This is helpful when looking up subnets to use
with func:nextavailableip
This call is offen slow and not cached!
some return_fields
comment,network,network_view,ddns_domainname,disable,enable_ddns
CLI Example:
.. code-block:: bash
salt-call infoblox.get_network
'''
infoblox = _get_infoblox(**api_opts)
return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) | python | def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts):
'''
Get list of all networks. This is helpful when looking up subnets to use
with func:nextavailableip
This call is offen slow and not cached!
some return_fields
comment,network,network_view,ddns_domainname,disable,enable_ddns
CLI Example:
.. code-block:: bash
salt-call infoblox.get_network
'''
infoblox = _get_infoblox(**api_opts)
return infoblox.get_network(ipv4addr=ipv4addr, network=network, return_fields=return_fields) | [
"def",
"get_network",
"(",
"ipv4addr",
"=",
"None",
",",
"network",
"=",
"None",
",",
"return_fields",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"infoblox",
"=",
"_get_infoblox",
"(",
"*",
"*",
"api_opts",
")",
"return",
"infoblox",
".",
"get_net... | Get list of all networks. This is helpful when looking up subnets to use
with func:nextavailableip
This call is offen slow and not cached!
some return_fields
comment,network,network_view,ddns_domainname,disable,enable_ddns
CLI Example:
.. code-block:: bash
salt-call infoblox.get_network | [
"Get",
"list",
"of",
"all",
"networks",
".",
"This",
"is",
"helpful",
"when",
"looking",
"up",
"subnets",
"to",
"use",
"with",
"func",
":",
"nextavailableip"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L470-L487 | train |
saltstack/salt | salt/modules/infoblox.py | delete_host | def delete_host(name=None, mac=None, ipv4addr=None, **api_opts):
'''
Delete host
CLI Example:
.. code-block:: bash
salt-call infoblox.delete_host name=example.domain.com
salt-call infoblox.delete_host ipv4addr=123.123.122.12
salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae
'''
if '__opts__' in globals() and __opts__['test']:
return {'Test': 'Would attempt to delete host'}
infoblox = _get_infoblox(**api_opts)
return infoblox.delete_host(name, mac, ipv4addr) | python | def delete_host(name=None, mac=None, ipv4addr=None, **api_opts):
'''
Delete host
CLI Example:
.. code-block:: bash
salt-call infoblox.delete_host name=example.domain.com
salt-call infoblox.delete_host ipv4addr=123.123.122.12
salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae
'''
if '__opts__' in globals() and __opts__['test']:
return {'Test': 'Would attempt to delete host'}
infoblox = _get_infoblox(**api_opts)
return infoblox.delete_host(name, mac, ipv4addr) | [
"def",
"delete_host",
"(",
"name",
"=",
"None",
",",
"mac",
"=",
"None",
",",
"ipv4addr",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"if",
"'__opts__'",
"in",
"globals",
"(",
")",
"and",
"__opts__",
"[",
"'test'",
"]",
":",
"return",
"{",
"'... | Delete host
CLI Example:
.. code-block:: bash
salt-call infoblox.delete_host name=example.domain.com
salt-call infoblox.delete_host ipv4addr=123.123.122.12
salt-call infoblox.delete_host ipv4addr=123.123.122.12 mac=00:50:56:84:6e:ae | [
"Delete",
"host"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L490-L505 | train |
saltstack/salt | salt/modules/infoblox.py | get_ipv4_range | def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts):
'''
Get ip range
CLI Example:
.. code-block:: bash
salt-call infoblox.get_ipv4_range start_addr=123.123.122.12
'''
infoblox = _get_infoblox(**api_opts)
return infoblox.get_range(start_addr, end_addr, return_fields) | python | def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts):
'''
Get ip range
CLI Example:
.. code-block:: bash
salt-call infoblox.get_ipv4_range start_addr=123.123.122.12
'''
infoblox = _get_infoblox(**api_opts)
return infoblox.get_range(start_addr, end_addr, return_fields) | [
"def",
"get_ipv4_range",
"(",
"start_addr",
"=",
"None",
",",
"end_addr",
"=",
"None",
",",
"return_fields",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"infoblox",
"=",
"_get_infoblox",
"(",
"*",
"*",
"api_opts",
")",
"return",
"infoblox",
".",
"g... | Get ip range
CLI Example:
.. code-block:: bash
salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 | [
"Get",
"ip",
"range"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L541-L552 | train |
saltstack/salt | salt/modules/infoblox.py | delete_ipv4_range | def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts):
'''
Delete ip range.
CLI Example:
.. code-block:: bash
salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12
'''
r = get_ipv4_range(start_addr, end_addr, **api_opts)
if r:
return delete_object(r['_ref'], **api_opts)
else:
return True | python | def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts):
'''
Delete ip range.
CLI Example:
.. code-block:: bash
salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12
'''
r = get_ipv4_range(start_addr, end_addr, **api_opts)
if r:
return delete_object(r['_ref'], **api_opts)
else:
return True | [
"def",
"delete_ipv4_range",
"(",
"start_addr",
"=",
"None",
",",
"end_addr",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"r",
"=",
"get_ipv4_range",
"(",
"start_addr",
",",
"end_addr",
",",
"*",
"*",
"api_opts",
")",
"if",
"r",
":",
"return",
"de... | Delete ip range.
CLI Example:
.. code-block:: bash
salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 | [
"Delete",
"ip",
"range",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L555-L569 | train |
saltstack/salt | salt/modules/infoblox.py | get_a | def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts):
'''
Get A record
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_a name=abc.example.com
salt-call infoblox.get_a ipv4addr=192.168.3.5
'''
data = {}
if name:
data['name'] = name
if ipv4addr:
data['ipv4addr'] = ipv4addr
r = get_object('record:a', data=data, **api_opts)
if r and len(r) > 1 and not allow_array:
raise Exception('More than one result, use allow_array to return the data')
return r | python | def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts):
'''
Get A record
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_a name=abc.example.com
salt-call infoblox.get_a ipv4addr=192.168.3.5
'''
data = {}
if name:
data['name'] = name
if ipv4addr:
data['ipv4addr'] = ipv4addr
r = get_object('record:a', data=data, **api_opts)
if r and len(r) > 1 and not allow_array:
raise Exception('More than one result, use allow_array to return the data')
return r | [
"def",
"get_a",
"(",
"name",
"=",
"None",
",",
"ipv4addr",
"=",
"None",
",",
"allow_array",
"=",
"True",
",",
"*",
"*",
"api_opts",
")",
":",
"data",
"=",
"{",
"}",
"if",
"name",
":",
"data",
"[",
"'name'",
"]",
"=",
"name",
"if",
"ipv4addr",
":"... | Get A record
CLI Examples:
.. code-block:: bash
salt-call infoblox.get_a name=abc.example.com
salt-call infoblox.get_a ipv4addr=192.168.3.5 | [
"Get",
"A",
"record"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L610-L629 | train |
saltstack/salt | salt/modules/infoblox.py | delete_a | def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts):
'''
Delete A record
If the A record is used as a round robin you can set ``allow_array=True`` to
delete all records for the hostname.
CLI Examples:
.. code-block:: bash
salt-call infoblox.delete_a name=abc.example.com
salt-call infoblox.delete_a ipv4addr=192.168.3.5
salt-call infoblox.delete_a name=acname.example.com allow_array=True
'''
r = get_a(name, ipv4addr, allow_array=False, **api_opts)
if not r:
return True
if len(r) > 1 and not allow_array:
raise Exception('More than one result, use allow_array to override')
ret = []
for ri in r:
ret.append(delete_object(ri['_ref'], **api_opts))
return ret | python | def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts):
'''
Delete A record
If the A record is used as a round robin you can set ``allow_array=True`` to
delete all records for the hostname.
CLI Examples:
.. code-block:: bash
salt-call infoblox.delete_a name=abc.example.com
salt-call infoblox.delete_a ipv4addr=192.168.3.5
salt-call infoblox.delete_a name=acname.example.com allow_array=True
'''
r = get_a(name, ipv4addr, allow_array=False, **api_opts)
if not r:
return True
if len(r) > 1 and not allow_array:
raise Exception('More than one result, use allow_array to override')
ret = []
for ri in r:
ret.append(delete_object(ri['_ref'], **api_opts))
return ret | [
"def",
"delete_a",
"(",
"name",
"=",
"None",
",",
"ipv4addr",
"=",
"None",
",",
"allow_array",
"=",
"False",
",",
"*",
"*",
"api_opts",
")",
":",
"r",
"=",
"get_a",
"(",
"name",
",",
"ipv4addr",
",",
"allow_array",
"=",
"False",
",",
"*",
"*",
"api... | Delete A record
If the A record is used as a round robin you can set ``allow_array=True`` to
delete all records for the hostname.
CLI Examples:
.. code-block:: bash
salt-call infoblox.delete_a name=abc.example.com
salt-call infoblox.delete_a ipv4addr=192.168.3.5
salt-call infoblox.delete_a name=acname.example.com allow_array=True | [
"Delete",
"A",
"record"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L632-L655 | train |
saltstack/salt | salt/states/infoblox_a.py | present | def present(name=None, ipv4addr=None, data=None, ensure_data=True, **api_opts):
'''
Ensure infoblox A record.
When you wish to update a hostname ensure `name` is set to the hostname
of the current record. You can give a new name in the `data.name`.
State example:
.. code-block:: yaml
infoblox_a.present:
- name: example-ha-0.domain.com
- data:
name: example-ha-0.domain.com
ipv4addr: 123.0.31.2
view: Internal
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if not data:
data = {}
if 'name' not in data:
data.update({'name': name})
if 'ipv4addr' not in data:
data.update({'ipv4addr': ipv4addr})
obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts)
if obj is None:
# perhaps the user updated the name
obj = __salt__['infoblox.get_a'](name=data['name'], ipv4addr=data['ipv4addr'], allow_array=False, **api_opts)
if obj:
# warn user that the data was updated and does not match
ret['result'] = False
ret['comment'] = '** please update the name: {0} to equal the updated data name {1}'.format(name, data['name'])
return ret
if obj:
obj = obj[0]
if not ensure_data:
ret['result'] = True
ret['comment'] = 'infoblox record already created (supplied fields not ensured to match)'
return ret
diff = __salt__['infoblox.diff_objects'](data, obj)
if not diff:
ret['result'] = True
ret['comment'] = 'supplied fields already updated (note: removing fields might not update)'
return ret
if diff:
ret['changes'] = {'diff': diff}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'would attempt to update infoblox record'
return ret
## TODO: perhaps need to review the output of new_obj
new_obj = __salt__['infoblox.update_object'](obj['_ref'], data=data, **api_opts)
ret['result'] = True
ret['comment'] = 'infoblox record fields updated (note: removing fields might not update)'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'would attempt to create infoblox record {0}'.format(data['name'])
return ret
new_obj_ref = __salt__['infoblox.create_a'](data=data, **api_opts)
new_obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts)
ret['result'] = True
ret['comment'] = 'infoblox record created'
ret['changes'] = {'old': 'None', 'new': {'_ref': new_obj_ref, 'data': new_obj}}
return ret | python | def present(name=None, ipv4addr=None, data=None, ensure_data=True, **api_opts):
'''
Ensure infoblox A record.
When you wish to update a hostname ensure `name` is set to the hostname
of the current record. You can give a new name in the `data.name`.
State example:
.. code-block:: yaml
infoblox_a.present:
- name: example-ha-0.domain.com
- data:
name: example-ha-0.domain.com
ipv4addr: 123.0.31.2
view: Internal
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if not data:
data = {}
if 'name' not in data:
data.update({'name': name})
if 'ipv4addr' not in data:
data.update({'ipv4addr': ipv4addr})
obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts)
if obj is None:
# perhaps the user updated the name
obj = __salt__['infoblox.get_a'](name=data['name'], ipv4addr=data['ipv4addr'], allow_array=False, **api_opts)
if obj:
# warn user that the data was updated and does not match
ret['result'] = False
ret['comment'] = '** please update the name: {0} to equal the updated data name {1}'.format(name, data['name'])
return ret
if obj:
obj = obj[0]
if not ensure_data:
ret['result'] = True
ret['comment'] = 'infoblox record already created (supplied fields not ensured to match)'
return ret
diff = __salt__['infoblox.diff_objects'](data, obj)
if not diff:
ret['result'] = True
ret['comment'] = 'supplied fields already updated (note: removing fields might not update)'
return ret
if diff:
ret['changes'] = {'diff': diff}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'would attempt to update infoblox record'
return ret
## TODO: perhaps need to review the output of new_obj
new_obj = __salt__['infoblox.update_object'](obj['_ref'], data=data, **api_opts)
ret['result'] = True
ret['comment'] = 'infoblox record fields updated (note: removing fields might not update)'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'would attempt to create infoblox record {0}'.format(data['name'])
return ret
new_obj_ref = __salt__['infoblox.create_a'](data=data, **api_opts)
new_obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts)
ret['result'] = True
ret['comment'] = 'infoblox record created'
ret['changes'] = {'old': 'None', 'new': {'_ref': new_obj_ref, 'data': new_obj}}
return ret | [
"def",
"present",
"(",
"name",
"=",
"None",
",",
"ipv4addr",
"=",
"None",
",",
"data",
"=",
"None",
",",
"ensure_data",
"=",
"True",
",",
"*",
"*",
"api_opts",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
... | Ensure infoblox A record.
When you wish to update a hostname ensure `name` is set to the hostname
of the current record. You can give a new name in the `data.name`.
State example:
.. code-block:: yaml
infoblox_a.present:
- name: example-ha-0.domain.com
- data:
name: example-ha-0.domain.com
ipv4addr: 123.0.31.2
view: Internal | [
"Ensure",
"infoblox",
"A",
"record",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/infoblox_a.py#L17-L90 | train |
saltstack/salt | salt/states/infoblox_a.py | absent | def absent(name=None, ipv4addr=None, **api_opts):
'''
Ensure infoblox A record is removed.
State example:
.. code-block:: yaml
infoblox_a.absent:
- name: example-ha-0.domain.com
infoblox_a.absent:
- name:
- ipv4addr: 127.0.23.23
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts)
if not obj:
ret['result'] = True
ret['comment'] = 'infoblox already removed'
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = {'old': obj, 'new': 'absent'}
return ret
if __salt__['infoblox.delete_a'](name=name, ipv4addr=ipv4addr, **api_opts):
ret['result'] = True
ret['changes'] = {'old': obj, 'new': 'absent'}
return ret | python | def absent(name=None, ipv4addr=None, **api_opts):
'''
Ensure infoblox A record is removed.
State example:
.. code-block:: yaml
infoblox_a.absent:
- name: example-ha-0.domain.com
infoblox_a.absent:
- name:
- ipv4addr: 127.0.23.23
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
obj = __salt__['infoblox.get_a'](name=name, ipv4addr=ipv4addr, allow_array=False, **api_opts)
if not obj:
ret['result'] = True
ret['comment'] = 'infoblox already removed'
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = {'old': obj, 'new': 'absent'}
return ret
if __salt__['infoblox.delete_a'](name=name, ipv4addr=ipv4addr, **api_opts):
ret['result'] = True
ret['changes'] = {'old': obj, 'new': 'absent'}
return ret | [
"def",
"absent",
"(",
"name",
"=",
"None",
",",
"ipv4addr",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}"... | Ensure infoblox A record is removed.
State example:
.. code-block:: yaml
infoblox_a.absent:
- name: example-ha-0.domain.com
infoblox_a.absent:
- name:
- ipv4addr: 127.0.23.23 | [
"Ensure",
"infoblox",
"A",
"record",
"is",
"removed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/infoblox_a.py#L93-L124 | train |
saltstack/salt | salt/modules/kapacitor.py | _get_url | def _get_url():
'''
Get the kapacitor URL.
'''
protocol = __salt__['config.option']('kapacitor.protocol', 'http')
host = __salt__['config.option']('kapacitor.host', 'localhost')
port = __salt__['config.option']('kapacitor.port', 9092)
return '{0}://{1}:{2}'.format(protocol, host, port) | python | def _get_url():
'''
Get the kapacitor URL.
'''
protocol = __salt__['config.option']('kapacitor.protocol', 'http')
host = __salt__['config.option']('kapacitor.host', 'localhost')
port = __salt__['config.option']('kapacitor.port', 9092)
return '{0}://{1}:{2}'.format(protocol, host, port) | [
"def",
"_get_url",
"(",
")",
":",
"protocol",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'kapacitor.protocol'",
",",
"'http'",
")",
"host",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'kapacitor.host'",
",",
"'localhost'",
")",
"port",
"=",
... | Get the kapacitor URL. | [
"Get",
"the",
"kapacitor",
"URL",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kapacitor.py#L55-L63 | train |
saltstack/salt | salt/modules/kapacitor.py | get_task | def get_task(name):
'''
Get a dict of data on a task.
name
Name of the task to get information about.
CLI Example:
.. code-block:: bash
salt '*' kapacitor.get_task cpu
'''
url = _get_url()
if version() < '0.13':
task_url = '{0}/task?name={1}'.format(url, name)
else:
task_url = '{0}/kapacitor/v1/tasks/{1}?skip-format=true'.format(url, name)
response = salt.utils.http.query(task_url, status=True)
if response['status'] == 404:
return None
data = salt.utils.json.loads(response['body'])
if version() < '0.13':
return {
'script': data['TICKscript'],
'type': data['Type'],
'dbrps': data['DBRPs'],
'enabled': data['Enabled'],
}
return {
'script': data['script'],
'type': data['type'],
'dbrps': data['dbrps'],
'enabled': data['status'] == 'enabled',
} | python | def get_task(name):
'''
Get a dict of data on a task.
name
Name of the task to get information about.
CLI Example:
.. code-block:: bash
salt '*' kapacitor.get_task cpu
'''
url = _get_url()
if version() < '0.13':
task_url = '{0}/task?name={1}'.format(url, name)
else:
task_url = '{0}/kapacitor/v1/tasks/{1}?skip-format=true'.format(url, name)
response = salt.utils.http.query(task_url, status=True)
if response['status'] == 404:
return None
data = salt.utils.json.loads(response['body'])
if version() < '0.13':
return {
'script': data['TICKscript'],
'type': data['Type'],
'dbrps': data['DBRPs'],
'enabled': data['Enabled'],
}
return {
'script': data['script'],
'type': data['type'],
'dbrps': data['dbrps'],
'enabled': data['status'] == 'enabled',
} | [
"def",
"get_task",
"(",
"name",
")",
":",
"url",
"=",
"_get_url",
"(",
")",
"if",
"version",
"(",
")",
"<",
"'0.13'",
":",
"task_url",
"=",
"'{0}/task?name={1}'",
".",
"format",
"(",
"url",
",",
"name",
")",
"else",
":",
"task_url",
"=",
"'{0}/kapacito... | Get a dict of data on a task.
name
Name of the task to get information about.
CLI Example:
.. code-block:: bash
salt '*' kapacitor.get_task cpu | [
"Get",
"a",
"dict",
"of",
"data",
"on",
"a",
"task",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kapacitor.py#L66-L106 | train |
saltstack/salt | salt/modules/kapacitor.py | _run_cmd | def _run_cmd(cmd):
'''
Run a Kapacitor task and return a dictionary of info.
'''
ret = {}
env_vars = {
'KAPACITOR_URL': _get_url(),
'KAPACITOR_UNSAFE_SSL': __salt__['config.option']('kapacitor.unsafe_ssl', 'false'),
}
result = __salt__['cmd.run_all'](cmd, env=env_vars)
if result.get('stdout'):
ret['stdout'] = result['stdout']
if result.get('stderr'):
ret['stderr'] = result['stderr']
ret['success'] = result['retcode'] == 0
return ret | python | def _run_cmd(cmd):
'''
Run a Kapacitor task and return a dictionary of info.
'''
ret = {}
env_vars = {
'KAPACITOR_URL': _get_url(),
'KAPACITOR_UNSAFE_SSL': __salt__['config.option']('kapacitor.unsafe_ssl', 'false'),
}
result = __salt__['cmd.run_all'](cmd, env=env_vars)
if result.get('stdout'):
ret['stdout'] = result['stdout']
if result.get('stderr'):
ret['stderr'] = result['stderr']
ret['success'] = result['retcode'] == 0
return ret | [
"def",
"_run_cmd",
"(",
"cmd",
")",
":",
"ret",
"=",
"{",
"}",
"env_vars",
"=",
"{",
"'KAPACITOR_URL'",
":",
"_get_url",
"(",
")",
",",
"'KAPACITOR_UNSAFE_SSL'",
":",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'kapacitor.unsafe_ssl'",
",",
"'false'",
")"... | Run a Kapacitor task and return a dictionary of info. | [
"Run",
"a",
"Kapacitor",
"task",
"and",
"return",
"a",
"dictionary",
"of",
"info",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kapacitor.py#L109-L126 | train |
saltstack/salt | salt/modules/kapacitor.py | define_task | def define_task(name,
tick_script,
task_type='stream',
database=None,
retention_policy='default',
dbrps=None):
'''
Define a task. Serves as both create/update.
name
Name of the task.
tick_script
Path to the TICK script for the task. Can be a salt:// source.
task_type
Task type. Defaults to 'stream'
dbrps
A list of databases and retention policies in "dbname"."rpname" format
to fetch data from. For backward compatibility, the value of
'database' and 'retention_policy' will be merged as part of dbrps.
.. versionadded:: 2019.2.0
database
Which database to fetch data from.
retention_policy
Which retention policy to fetch data from. Defaults to 'default'.
CLI Example:
.. code-block:: bash
salt '*' kapacitor.define_task cpu salt://kapacitor/cpu.tick database=telegraf
'''
if not database and not dbrps:
log.error("Providing database name or dbrps is mandatory.")
return False
if version() < '0.13':
cmd = 'kapacitor define -name {0}'.format(name)
else:
cmd = 'kapacitor define {0}'.format(name)
if tick_script.startswith('salt://'):
tick_script = __salt__['cp.cache_file'](tick_script, __env__)
cmd += ' -tick {0}'.format(tick_script)
if task_type:
cmd += ' -type {0}'.format(task_type)
if not dbrps:
dbrps = []
if database and retention_policy:
dbrp = '{0}.{1}'.format(database, retention_policy)
dbrps.append(dbrp)
if dbrps:
for dbrp in dbrps:
cmd += ' -dbrp {0}'.format(dbrp)
return _run_cmd(cmd) | python | def define_task(name,
tick_script,
task_type='stream',
database=None,
retention_policy='default',
dbrps=None):
'''
Define a task. Serves as both create/update.
name
Name of the task.
tick_script
Path to the TICK script for the task. Can be a salt:// source.
task_type
Task type. Defaults to 'stream'
dbrps
A list of databases and retention policies in "dbname"."rpname" format
to fetch data from. For backward compatibility, the value of
'database' and 'retention_policy' will be merged as part of dbrps.
.. versionadded:: 2019.2.0
database
Which database to fetch data from.
retention_policy
Which retention policy to fetch data from. Defaults to 'default'.
CLI Example:
.. code-block:: bash
salt '*' kapacitor.define_task cpu salt://kapacitor/cpu.tick database=telegraf
'''
if not database and not dbrps:
log.error("Providing database name or dbrps is mandatory.")
return False
if version() < '0.13':
cmd = 'kapacitor define -name {0}'.format(name)
else:
cmd = 'kapacitor define {0}'.format(name)
if tick_script.startswith('salt://'):
tick_script = __salt__['cp.cache_file'](tick_script, __env__)
cmd += ' -tick {0}'.format(tick_script)
if task_type:
cmd += ' -type {0}'.format(task_type)
if not dbrps:
dbrps = []
if database and retention_policy:
dbrp = '{0}.{1}'.format(database, retention_policy)
dbrps.append(dbrp)
if dbrps:
for dbrp in dbrps:
cmd += ' -dbrp {0}'.format(dbrp)
return _run_cmd(cmd) | [
"def",
"define_task",
"(",
"name",
",",
"tick_script",
",",
"task_type",
"=",
"'stream'",
",",
"database",
"=",
"None",
",",
"retention_policy",
"=",
"'default'",
",",
"dbrps",
"=",
"None",
")",
":",
"if",
"not",
"database",
"and",
"not",
"dbrps",
":",
"... | Define a task. Serves as both create/update.
name
Name of the task.
tick_script
Path to the TICK script for the task. Can be a salt:// source.
task_type
Task type. Defaults to 'stream'
dbrps
A list of databases and retention policies in "dbname"."rpname" format
to fetch data from. For backward compatibility, the value of
'database' and 'retention_policy' will be merged as part of dbrps.
.. versionadded:: 2019.2.0
database
Which database to fetch data from.
retention_policy
Which retention policy to fetch data from. Defaults to 'default'.
CLI Example:
.. code-block:: bash
salt '*' kapacitor.define_task cpu salt://kapacitor/cpu.tick database=telegraf | [
"Define",
"a",
"task",
".",
"Serves",
"as",
"both",
"create",
"/",
"update",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kapacitor.py#L129-L194 | train |
saltstack/salt | salt/modules/linux_ip.py | _ip_ifaces | def _ip_ifaces():
'''
Parse output from 'ip a'
'''
tmp = {}
ret = {}
if_ = None
at_ = None
out = __salt__['cmd.run']('ip a')
for line in out.splitlines():
if not line.startswith(' '):
comps = line.split(':')
if_ = comps[1].strip()
opts_comps = comps[2].strip().split()
flags = opts_comps.pop(0).lstrip('<').rstrip('>').split(',')
opts_iter = iter(opts_comps)
ret[if_] = {
'flags': flags,
'options': dict(list(zip(opts_iter, opts_iter)))
}
else:
if line.strip().startswith('link'):
comps = iter(line.strip().split())
ret[if_]['link_layer'] = dict(list(zip(comps, comps)))
elif line.strip().startswith('inet'):
comps = line.strip().split()
at_ = comps[0]
if len(comps) % 2 != 0:
last = comps.pop()
comps[-1] += ' {0}'.format(last)
ifi = iter(comps)
ret[if_][at_] = dict(list(zip(ifi, ifi)))
else:
comps = line.strip().split()
ifi = iter(comps)
ret[if_][at_].update(dict(list(zip(ifi, ifi))))
return ret | python | def _ip_ifaces():
'''
Parse output from 'ip a'
'''
tmp = {}
ret = {}
if_ = None
at_ = None
out = __salt__['cmd.run']('ip a')
for line in out.splitlines():
if not line.startswith(' '):
comps = line.split(':')
if_ = comps[1].strip()
opts_comps = comps[2].strip().split()
flags = opts_comps.pop(0).lstrip('<').rstrip('>').split(',')
opts_iter = iter(opts_comps)
ret[if_] = {
'flags': flags,
'options': dict(list(zip(opts_iter, opts_iter)))
}
else:
if line.strip().startswith('link'):
comps = iter(line.strip().split())
ret[if_]['link_layer'] = dict(list(zip(comps, comps)))
elif line.strip().startswith('inet'):
comps = line.strip().split()
at_ = comps[0]
if len(comps) % 2 != 0:
last = comps.pop()
comps[-1] += ' {0}'.format(last)
ifi = iter(comps)
ret[if_][at_] = dict(list(zip(ifi, ifi)))
else:
comps = line.strip().split()
ifi = iter(comps)
ret[if_][at_].update(dict(list(zip(ifi, ifi))))
return ret | [
"def",
"_ip_ifaces",
"(",
")",
":",
"tmp",
"=",
"{",
"}",
"ret",
"=",
"{",
"}",
"if_",
"=",
"None",
"at_",
"=",
"None",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'ip a'",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",
... | Parse output from 'ip a' | [
"Parse",
"output",
"from",
"ip",
"a"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_ip.py#L67-L103 | train |
saltstack/salt | salt/modules/linux_ip.py | _parse_routes | def _parse_routes():
'''
Parse the contents of ``/proc/net/route``
'''
with salt.utils.files.fopen('/proc/net/route', 'r') as fp_:
out = salt.utils.stringutils.to_unicode(fp_.read())
ret = {}
for line in out.splitlines():
tmp = {}
if not line.strip():
continue
if line.startswith('Iface'):
continue
comps = line.split()
tmp['iface'] = comps[0]
tmp['destination'] = _hex_to_octets(comps[1])
tmp['gateway'] = _hex_to_octets(comps[2])
tmp['flags'] = _route_flags(int(comps[3]))
tmp['refcnt'] = comps[4]
tmp['use'] = comps[5]
tmp['metric'] = comps[6]
tmp['mask'] = _hex_to_octets(comps[7])
tmp['mtu'] = comps[8]
tmp['window'] = comps[9]
tmp['irtt'] = comps[10]
if comps[0] not in ret:
ret[comps[0]] = []
ret[comps[0]].append(tmp)
return ret | python | def _parse_routes():
'''
Parse the contents of ``/proc/net/route``
'''
with salt.utils.files.fopen('/proc/net/route', 'r') as fp_:
out = salt.utils.stringutils.to_unicode(fp_.read())
ret = {}
for line in out.splitlines():
tmp = {}
if not line.strip():
continue
if line.startswith('Iface'):
continue
comps = line.split()
tmp['iface'] = comps[0]
tmp['destination'] = _hex_to_octets(comps[1])
tmp['gateway'] = _hex_to_octets(comps[2])
tmp['flags'] = _route_flags(int(comps[3]))
tmp['refcnt'] = comps[4]
tmp['use'] = comps[5]
tmp['metric'] = comps[6]
tmp['mask'] = _hex_to_octets(comps[7])
tmp['mtu'] = comps[8]
tmp['window'] = comps[9]
tmp['irtt'] = comps[10]
if comps[0] not in ret:
ret[comps[0]] = []
ret[comps[0]].append(tmp)
return ret | [
"def",
"_parse_routes",
"(",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/proc/net/route'",
",",
"'r'",
")",
"as",
"fp_",
":",
"out",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"fp_",
".",
"r... | Parse the contents of ``/proc/net/route`` | [
"Parse",
"the",
"contents",
"of",
"/",
"proc",
"/",
"net",
"/",
"route"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_ip.py#L139-L168 | train |
saltstack/salt | salt/modules/linux_ip.py | _hex_to_octets | def _hex_to_octets(addr):
'''
Convert hex fields from /proc/net/route to octects
'''
return '{0}:{1}:{2}:{3}'.format(
int(addr[6:8], 16),
int(addr[4:6], 16),
int(addr[2:4], 16),
int(addr[0:2], 16),
) | python | def _hex_to_octets(addr):
'''
Convert hex fields from /proc/net/route to octects
'''
return '{0}:{1}:{2}:{3}'.format(
int(addr[6:8], 16),
int(addr[4:6], 16),
int(addr[2:4], 16),
int(addr[0:2], 16),
) | [
"def",
"_hex_to_octets",
"(",
"addr",
")",
":",
"return",
"'{0}:{1}:{2}:{3}'",
".",
"format",
"(",
"int",
"(",
"addr",
"[",
"6",
":",
"8",
"]",
",",
"16",
")",
",",
"int",
"(",
"addr",
"[",
"4",
":",
"6",
"]",
",",
"16",
")",
",",
"int",
"(",
... | Convert hex fields from /proc/net/route to octects | [
"Convert",
"hex",
"fields",
"from",
"/",
"proc",
"/",
"net",
"/",
"route",
"to",
"octects"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_ip.py#L171-L180 | train |
saltstack/salt | salt/modules/linux_ip.py | _route_flags | def _route_flags(rflags):
'''
https://github.com/torvalds/linux/blob/master/include/uapi/linux/route.h
https://github.com/torvalds/linux/blob/master/include/uapi/linux/ipv6_route.h
'''
flags = ''
fmap = {
0x0001: 'U', # RTF_UP, route is up
0x0002: 'G', # RTF_GATEWAY, use gateway
0x0004: 'H', # RTF_HOST, target is a host
0x0008: 'R', # RET_REINSTATE, reinstate route for dynamic routing
0x0010: 'D', # RTF_DYNAMIC, dynamically installed by daemon or redirect
0x0020: 'M', # RTF_MODIFIED, modified from routing daemon or redirect
0x00040000: 'A', # RTF_ADDRCONF, installed by addrconf
0x01000000: 'C', # RTF_CACHE, cache entry
0x0200: '!', # RTF_REJECT, reject route
}
for item in fmap:
if rflags & item:
flags += fmap[item]
return flags | python | def _route_flags(rflags):
'''
https://github.com/torvalds/linux/blob/master/include/uapi/linux/route.h
https://github.com/torvalds/linux/blob/master/include/uapi/linux/ipv6_route.h
'''
flags = ''
fmap = {
0x0001: 'U', # RTF_UP, route is up
0x0002: 'G', # RTF_GATEWAY, use gateway
0x0004: 'H', # RTF_HOST, target is a host
0x0008: 'R', # RET_REINSTATE, reinstate route for dynamic routing
0x0010: 'D', # RTF_DYNAMIC, dynamically installed by daemon or redirect
0x0020: 'M', # RTF_MODIFIED, modified from routing daemon or redirect
0x00040000: 'A', # RTF_ADDRCONF, installed by addrconf
0x01000000: 'C', # RTF_CACHE, cache entry
0x0200: '!', # RTF_REJECT, reject route
}
for item in fmap:
if rflags & item:
flags += fmap[item]
return flags | [
"def",
"_route_flags",
"(",
"rflags",
")",
":",
"flags",
"=",
"''",
"fmap",
"=",
"{",
"0x0001",
":",
"'U'",
",",
"# RTF_UP, route is up",
"0x0002",
":",
"'G'",
",",
"# RTF_GATEWAY, use gateway",
"0x0004",
":",
"'H'",
",",
"# RTF_HOST, target is a host",
"0x0008"... | https://github.com/torvalds/linux/blob/master/include/uapi/linux/route.h
https://github.com/torvalds/linux/blob/master/include/uapi/linux/ipv6_route.h | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"torvalds",
"/",
"linux",
"/",
"blob",
"/",
"master",
"/",
"include",
"/",
"uapi",
"/",
"linux",
"/",
"route",
".",
"h",
"https",
":",
"//",
"github",
".",
"com",
"/",
"torvalds",
"/",
"linux",
"/",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_ip.py#L183-L203 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_state | def _get_state():
'''
Returns the state of connman
'''
try:
return pyconnman.ConnManager().get_property('State')
except KeyError:
return 'offline'
except dbus.DBusException as exc:
raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) | python | def _get_state():
'''
Returns the state of connman
'''
try:
return pyconnman.ConnManager().get_property('State')
except KeyError:
return 'offline'
except dbus.DBusException as exc:
raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc)) | [
"def",
"_get_state",
"(",
")",
":",
"try",
":",
"return",
"pyconnman",
".",
"ConnManager",
"(",
")",
".",
"get_property",
"(",
"'State'",
")",
"except",
"KeyError",
":",
"return",
"'offline'",
"except",
"dbus",
".",
"DBusException",
"as",
"exc",
":",
"rais... | Returns the state of connman | [
"Returns",
"the",
"state",
"of",
"connman"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L85-L94 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_technologies | def _get_technologies():
'''
Returns the technologies of connman
'''
tech = ''
technologies = pyconnman.ConnManager().get_technologies()
for path, params in technologies:
tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format(
path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1)
return tech | python | def _get_technologies():
'''
Returns the technologies of connman
'''
tech = ''
technologies = pyconnman.ConnManager().get_technologies()
for path, params in technologies:
tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format(
path, params['Name'], params['Type'], params['Powered'] == 1, params['Connected'] == 1)
return tech | [
"def",
"_get_technologies",
"(",
")",
":",
"tech",
"=",
"''",
"technologies",
"=",
"pyconnman",
".",
"ConnManager",
"(",
")",
".",
"get_technologies",
"(",
")",
"for",
"path",
",",
"params",
"in",
"technologies",
":",
"tech",
"+=",
"'{0}\\n\\tName = {1}\\n\\tT... | Returns the technologies of connman | [
"Returns",
"the",
"technologies",
"of",
"connman"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L97-L106 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_services | def _get_services():
'''
Returns a list with all connman services
'''
serv = []
services = pyconnman.ConnManager().get_services()
for path, _ in services:
serv.append(six.text_type(path[len(SERVICE_PATH):]))
return serv | python | def _get_services():
'''
Returns a list with all connman services
'''
serv = []
services = pyconnman.ConnManager().get_services()
for path, _ in services:
serv.append(six.text_type(path[len(SERVICE_PATH):]))
return serv | [
"def",
"_get_services",
"(",
")",
":",
"serv",
"=",
"[",
"]",
"services",
"=",
"pyconnman",
".",
"ConnManager",
"(",
")",
".",
"get_services",
"(",
")",
"for",
"path",
",",
"_",
"in",
"services",
":",
"serv",
".",
"append",
"(",
"six",
".",
"text_typ... | Returns a list with all connman services | [
"Returns",
"a",
"list",
"with",
"all",
"connman",
"services"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L109-L117 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _connected | def _connected(service):
'''
Verify if a connman service is connected
'''
state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State')
return state == 'online' or state == 'ready' | python | def _connected(service):
'''
Verify if a connman service is connected
'''
state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State')
return state == 'online' or state == 'ready' | [
"def",
"_connected",
"(",
"service",
")",
":",
"state",
"=",
"pyconnman",
".",
"ConnService",
"(",
"os",
".",
"path",
".",
"join",
"(",
"SERVICE_PATH",
",",
"service",
")",
")",
".",
"get_property",
"(",
"'State'",
")",
"return",
"state",
"==",
"'online'... | Verify if a connman service is connected | [
"Verify",
"if",
"a",
"connman",
"service",
"is",
"connected"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L120-L125 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _space_delimited_list | def _space_delimited_list(value):
'''
validate that a value contains one or more space-delimited values
'''
if isinstance(value, six.string_types):
items = value.split(' ')
valid = items and all(items)
else:
valid = hasattr(value, '__iter__') and (value != [])
if valid:
return True, 'space-delimited string'
return False, '{0} is not a valid list.\n'.format(value) | python | def _space_delimited_list(value):
'''
validate that a value contains one or more space-delimited values
'''
if isinstance(value, six.string_types):
items = value.split(' ')
valid = items and all(items)
else:
valid = hasattr(value, '__iter__') and (value != [])
if valid:
return True, 'space-delimited string'
return False, '{0} is not a valid list.\n'.format(value) | [
"def",
"_space_delimited_list",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"items",
"=",
"value",
".",
"split",
"(",
"' '",
")",
"valid",
"=",
"items",
"and",
"all",
"(",
"items",
")",
"else",
... | validate that a value contains one or more space-delimited values | [
"validate",
"that",
"a",
"value",
"contains",
"one",
"or",
"more",
"space",
"-",
"delimited",
"values"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L128-L140 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _validate_ipv4 | def _validate_ipv4(value):
'''
validate ipv4 values
'''
if len(value) == 3:
if not salt.utils.validate.net.ipv4_addr(value[0].strip()):
return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0])
if not salt.utils.validate.net.netmask(value[1].strip()):
return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1])
if not salt.utils.validate.net.ipv4_addr(value[2].strip()):
return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2])
else:
return False, 'Invalid value: {0} for ipv4 option'.format(value)
return True, '' | python | def _validate_ipv4(value):
'''
validate ipv4 values
'''
if len(value) == 3:
if not salt.utils.validate.net.ipv4_addr(value[0].strip()):
return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0])
if not salt.utils.validate.net.netmask(value[1].strip()):
return False, 'Invalid netmask: {0} for ipv4 option'.format(value[1])
if not salt.utils.validate.net.ipv4_addr(value[2].strip()):
return False, 'Invalid gateway: {0} for ipv4 option'.format(value[2])
else:
return False, 'Invalid value: {0} for ipv4 option'.format(value)
return True, '' | [
"def",
"_validate_ipv4",
"(",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"==",
"3",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"validate",
".",
"net",
".",
"ipv4_addr",
"(",
"value",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
":",
"r... | validate ipv4 values | [
"validate",
"ipv4",
"values"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L143-L156 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _interface_to_service | def _interface_to_service(iface):
'''
returns the coresponding service to given interface if exists, otherwise return None
'''
for _service in _get_services():
service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service))
if service_info.get_property('Ethernet')['Interface'] == iface:
return _service
return None | python | def _interface_to_service(iface):
'''
returns the coresponding service to given interface if exists, otherwise return None
'''
for _service in _get_services():
service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service))
if service_info.get_property('Ethernet')['Interface'] == iface:
return _service
return None | [
"def",
"_interface_to_service",
"(",
"iface",
")",
":",
"for",
"_service",
"in",
"_get_services",
"(",
")",
":",
"service_info",
"=",
"pyconnman",
".",
"ConnService",
"(",
"os",
".",
"path",
".",
"join",
"(",
"SERVICE_PATH",
",",
"_service",
")",
")",
"if"... | returns the coresponding service to given interface if exists, otherwise return None | [
"returns",
"the",
"coresponding",
"service",
"to",
"given",
"interface",
"if",
"exists",
"otherwise",
"return",
"None"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L159-L167 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_service_info | def _get_service_info(service):
'''
return details about given connman service
'''
service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
data = {
'label': service,
'wireless': service_info.get_property('Type') == 'wifi',
'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']),
'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address'])
}
state = service_info.get_property('State')
if state == 'ready' or state == 'online':
data['up'] = True
data['ipv4'] = {
'gateway': '0.0.0.0'
}
ipv4 = 'IPv4'
if service_info.get_property('IPv4')['Method'] == 'manual':
ipv4 += '.Configuration'
ipv4_info = service_info.get_property(ipv4)
for info in ['Method', 'Address', 'Netmask', 'Gateway']:
value = ipv4_info.get(info)
if value is None:
log.warning('Unable to get IPv4 %s for service %s\n', info, service)
continue
if info == 'Method':
info = 'requestmode'
if value == 'dhcp':
value = 'dhcp_linklocal'
elif value in ('manual', 'fixed'):
value = 'static'
data['ipv4'][info.lower()] = six.text_type(value)
ipv6_info = service_info.get_property('IPv6')
for info in ['Address', 'Prefix', 'Gateway']:
value = ipv6_info.get(info)
if value is None:
log.warning('Unable to get IPv6 %s for service %s\n', info, service)
continue
if 'ipv6' not in data:
data['ipv6'] = {}
data['ipv6'][info.lower()] = [six.text_type(value)]
nameservers = []
for nameserver_prop in service_info.get_property('Nameservers'):
nameservers.append(six.text_type(nameserver_prop))
data['ipv4']['dns'] = nameservers
else:
data['up'] = False
data['ipv4'] = {
'requestmode': 'disabled'
}
data['ipv4']['supportedrequestmodes'] = [
'static',
'dhcp_linklocal',
'disabled'
]
return data | python | def _get_service_info(service):
'''
return details about given connman service
'''
service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
data = {
'label': service,
'wireless': service_info.get_property('Type') == 'wifi',
'connectionid': six.text_type(service_info.get_property('Ethernet')['Interface']),
'hwaddr': six.text_type(service_info.get_property('Ethernet')['Address'])
}
state = service_info.get_property('State')
if state == 'ready' or state == 'online':
data['up'] = True
data['ipv4'] = {
'gateway': '0.0.0.0'
}
ipv4 = 'IPv4'
if service_info.get_property('IPv4')['Method'] == 'manual':
ipv4 += '.Configuration'
ipv4_info = service_info.get_property(ipv4)
for info in ['Method', 'Address', 'Netmask', 'Gateway']:
value = ipv4_info.get(info)
if value is None:
log.warning('Unable to get IPv4 %s for service %s\n', info, service)
continue
if info == 'Method':
info = 'requestmode'
if value == 'dhcp':
value = 'dhcp_linklocal'
elif value in ('manual', 'fixed'):
value = 'static'
data['ipv4'][info.lower()] = six.text_type(value)
ipv6_info = service_info.get_property('IPv6')
for info in ['Address', 'Prefix', 'Gateway']:
value = ipv6_info.get(info)
if value is None:
log.warning('Unable to get IPv6 %s for service %s\n', info, service)
continue
if 'ipv6' not in data:
data['ipv6'] = {}
data['ipv6'][info.lower()] = [six.text_type(value)]
nameservers = []
for nameserver_prop in service_info.get_property('Nameservers'):
nameservers.append(six.text_type(nameserver_prop))
data['ipv4']['dns'] = nameservers
else:
data['up'] = False
data['ipv4'] = {
'requestmode': 'disabled'
}
data['ipv4']['supportedrequestmodes'] = [
'static',
'dhcp_linklocal',
'disabled'
]
return data | [
"def",
"_get_service_info",
"(",
"service",
")",
":",
"service_info",
"=",
"pyconnman",
".",
"ConnService",
"(",
"os",
".",
"path",
".",
"join",
"(",
"SERVICE_PATH",
",",
"service",
")",
")",
"data",
"=",
"{",
"'label'",
":",
"service",
",",
"'wireless'",
... | return details about given connman service | [
"return",
"details",
"about",
"given",
"connman",
"service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L170-L230 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_dns_info | def _get_dns_info():
'''
return dns list
'''
dns_list = []
try:
with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info:
lines = dns_info.readlines()
for line in lines:
if 'nameserver' in line:
dns = line.split()[1].strip()
if dns not in dns_list:
dns_list.append(dns)
except IOError:
log.warning('Could not get domain\n')
return dns_list | python | def _get_dns_info():
'''
return dns list
'''
dns_list = []
try:
with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info:
lines = dns_info.readlines()
for line in lines:
if 'nameserver' in line:
dns = line.split()[1].strip()
if dns not in dns_list:
dns_list.append(dns)
except IOError:
log.warning('Could not get domain\n')
return dns_list | [
"def",
"_get_dns_info",
"(",
")",
":",
"dns_list",
"=",
"[",
"]",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/etc/resolv.conf'",
",",
"'r+'",
")",
"as",
"dns_info",
":",
"lines",
"=",
"dns_info",
".",
"readlines",
"(",... | return dns list | [
"return",
"dns",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L233-L248 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _load_config | def _load_config(section, options, default_value='', filename=INI_FILE):
'''
Get values for some options and a given section from a config file.
:param section: Section Name
:param options: List of options
:param default_value: Default value if an option doesn't have a value. Default is empty string.
:param filename: config file. Default is INI_FILE.
:return:
'''
results = {}
if not options:
return results
with salt.utils.files.fopen(filename, 'r') as config_file:
config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict)
config_parser.readfp(config_file)
for option in options:
results[option] = _remove_quotes(config_parser.get(section, option)) \
if config_parser.has_option(section, option) else default_value
return results | python | def _load_config(section, options, default_value='', filename=INI_FILE):
'''
Get values for some options and a given section from a config file.
:param section: Section Name
:param options: List of options
:param default_value: Default value if an option doesn't have a value. Default is empty string.
:param filename: config file. Default is INI_FILE.
:return:
'''
results = {}
if not options:
return results
with salt.utils.files.fopen(filename, 'r') as config_file:
config_parser = configparser.RawConfigParser(dict_type=CaseInsensitiveDict)
config_parser.readfp(config_file)
for option in options:
results[option] = _remove_quotes(config_parser.get(section, option)) \
if config_parser.has_option(section, option) else default_value
return results | [
"def",
"_load_config",
"(",
"section",
",",
"options",
",",
"default_value",
"=",
"''",
",",
"filename",
"=",
"INI_FILE",
")",
":",
"results",
"=",
"{",
"}",
"if",
"not",
"options",
":",
"return",
"results",
"with",
"salt",
".",
"utils",
".",
"files",
... | Get values for some options and a given section from a config file.
:param section: Section Name
:param options: List of options
:param default_value: Default value if an option doesn't have a value. Default is empty string.
:param filename: config file. Default is INI_FILE.
:return: | [
"Get",
"values",
"for",
"some",
"options",
"and",
"a",
"given",
"section",
"from",
"a",
"config",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L261-L281 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_request_mode_info | def _get_request_mode_info(interface):
'''
return requestmode for given interface
'''
settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1)
link_local_enabled = int(settings['linklocalenabled'])
dhcp_enabled = int(settings['dhcpenabled'])
if dhcp_enabled == 1:
return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only'
else:
if link_local_enabled == 1:
return 'linklocal_only'
if link_local_enabled == 0:
return 'static'
# some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables
# when selecting "DHCP or Link Local" from MAX, so return it by default to avoid
# having the requestmode "None" because none of the conditions above matched.
return 'dhcp_linklocal' | python | def _get_request_mode_info(interface):
'''
return requestmode for given interface
'''
settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1)
link_local_enabled = int(settings['linklocalenabled'])
dhcp_enabled = int(settings['dhcpenabled'])
if dhcp_enabled == 1:
return 'dhcp_linklocal' if link_local_enabled == 1 else 'dhcp_only'
else:
if link_local_enabled == 1:
return 'linklocal_only'
if link_local_enabled == 0:
return 'static'
# some versions of nirtcfg don't set the dhcpenabled/linklocalenabled variables
# when selecting "DHCP or Link Local" from MAX, so return it by default to avoid
# having the requestmode "None" because none of the conditions above matched.
return 'dhcp_linklocal' | [
"def",
"_get_request_mode_info",
"(",
"interface",
")",
":",
"settings",
"=",
"_load_config",
"(",
"interface",
",",
"[",
"'linklocalenabled'",
",",
"'dhcpenabled'",
"]",
",",
"-",
"1",
")",
"link_local_enabled",
"=",
"int",
"(",
"settings",
"[",
"'linklocalenab... | return requestmode for given interface | [
"return",
"requestmode",
"for",
"given",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L284-L303 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_possible_adapter_modes | def _get_possible_adapter_modes(interface, blacklist):
'''
Return possible adapter modes for a given interface using a blacklist.
:param interface: interface name
:param blacklist: given blacklist
:return: list of possible adapter modes
'''
adapter_modes = []
protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower()
sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface))
with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file:
uevent_lines = uevent_file.readlines()
uevent_devtype = ""
for line in uevent_lines:
if line.startswith("DEVTYPE="):
uevent_devtype = line.split('=')[1].strip()
break
for adapter_mode in blacklist:
if adapter_mode == '_':
continue
value = blacklist.get(adapter_mode, {})
if value.get('additional_protocol') and adapter_mode not in protocols:
continue
if interface not in value['name'] \
and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or
(blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype)
for iface_type in value['type']):
adapter_modes += [adapter_mode]
return adapter_modes | python | def _get_possible_adapter_modes(interface, blacklist):
'''
Return possible adapter modes for a given interface using a blacklist.
:param interface: interface name
:param blacklist: given blacklist
:return: list of possible adapter modes
'''
adapter_modes = []
protocols = _load_config('lvrt', ['AdditionalNetworkProtocols'])['AdditionalNetworkProtocols'].lower()
sys_interface_path = os.readlink('/sys/class/net/{0}'.format(interface))
with salt.utils.files.fopen('/sys/class/net/{0}/uevent'.format(interface)) as uevent_file:
uevent_lines = uevent_file.readlines()
uevent_devtype = ""
for line in uevent_lines:
if line.startswith("DEVTYPE="):
uevent_devtype = line.split('=')[1].strip()
break
for adapter_mode in blacklist:
if adapter_mode == '_':
continue
value = blacklist.get(adapter_mode, {})
if value.get('additional_protocol') and adapter_mode not in protocols:
continue
if interface not in value['name'] \
and not any((blacklist['_'][iface_type] == 'sys' and iface_type in sys_interface_path) or
(blacklist['_'][iface_type] == 'uevent' and iface_type == uevent_devtype)
for iface_type in value['type']):
adapter_modes += [adapter_mode]
return adapter_modes | [
"def",
"_get_possible_adapter_modes",
"(",
"interface",
",",
"blacklist",
")",
":",
"adapter_modes",
"=",
"[",
"]",
"protocols",
"=",
"_load_config",
"(",
"'lvrt'",
",",
"[",
"'AdditionalNetworkProtocols'",
"]",
")",
"[",
"'AdditionalNetworkProtocols'",
"]",
".",
... | Return possible adapter modes for a given interface using a blacklist.
:param interface: interface name
:param blacklist: given blacklist
:return: list of possible adapter modes | [
"Return",
"possible",
"adapter",
"modes",
"for",
"a",
"given",
"interface",
"using",
"a",
"blacklist",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L314-L345 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_static_info | def _get_static_info(interface):
'''
Return information about an interface from config file.
:param interface: interface label
'''
data = {
'connectionid': interface.name,
'label': interface.name,
'hwaddr': interface.hwaddr[:-1],
'up': False,
'ipv4': {
'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'],
'requestmode': 'static'
},
'wireless': False
}
hwaddr_section_number = ''.join(data['hwaddr'].split(':'))
if os.path.exists(INTERFACES_CONFIG):
information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG)
if information['IPv4'] != '':
ipv4_information = information['IPv4'].split('/')
data['ipv4']['address'] = ipv4_information[0]
data['ipv4']['dns'] = information['Nameservers'].split(',')
data['ipv4']['netmask'] = ipv4_information[1]
data['ipv4']['gateway'] = ipv4_information[2]
return data | python | def _get_static_info(interface):
'''
Return information about an interface from config file.
:param interface: interface label
'''
data = {
'connectionid': interface.name,
'label': interface.name,
'hwaddr': interface.hwaddr[:-1],
'up': False,
'ipv4': {
'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'],
'requestmode': 'static'
},
'wireless': False
}
hwaddr_section_number = ''.join(data['hwaddr'].split(':'))
if os.path.exists(INTERFACES_CONFIG):
information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG)
if information['IPv4'] != '':
ipv4_information = information['IPv4'].split('/')
data['ipv4']['address'] = ipv4_information[0]
data['ipv4']['dns'] = information['Nameservers'].split(',')
data['ipv4']['netmask'] = ipv4_information[1]
data['ipv4']['gateway'] = ipv4_information[2]
return data | [
"def",
"_get_static_info",
"(",
"interface",
")",
":",
"data",
"=",
"{",
"'connectionid'",
":",
"interface",
".",
"name",
",",
"'label'",
":",
"interface",
".",
"name",
",",
"'hwaddr'",
":",
"interface",
".",
"hwaddr",
"[",
":",
"-",
"1",
"]",
",",
"'u... | Return information about an interface from config file.
:param interface: interface label | [
"Return",
"information",
"about",
"an",
"interface",
"from",
"config",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L348-L374 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_base_interface_info | def _get_base_interface_info(interface):
'''
return base details about given interface
'''
blacklist = {
'tcpip': {
'name': [],
'type': [],
'additional_protocol': False
},
'disabled': {
'name': ['eth0'],
'type': ['gadget'],
'additional_protocol': False
},
'ethercat': {
'name': ['eth0'],
'type': ['gadget', 'usb', 'wlan'],
'additional_protocol': True
},
'_': {
'usb': 'sys',
'gadget': 'uevent',
'wlan': 'uevent'
}
}
return {
'label': interface.name,
'connectionid': interface.name,
'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist),
'adapter_mode': _get_adapter_mode_info(interface.name),
'up': interface.flags & IFF_RUNNING != 0,
'ipv4': {
'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'],
'requestmode': _get_request_mode_info(interface.name)
},
'hwaddr': interface.hwaddr[:-1]
} | python | def _get_base_interface_info(interface):
'''
return base details about given interface
'''
blacklist = {
'tcpip': {
'name': [],
'type': [],
'additional_protocol': False
},
'disabled': {
'name': ['eth0'],
'type': ['gadget'],
'additional_protocol': False
},
'ethercat': {
'name': ['eth0'],
'type': ['gadget', 'usb', 'wlan'],
'additional_protocol': True
},
'_': {
'usb': 'sys',
'gadget': 'uevent',
'wlan': 'uevent'
}
}
return {
'label': interface.name,
'connectionid': interface.name,
'supported_adapter_modes': _get_possible_adapter_modes(interface.name, blacklist),
'adapter_mode': _get_adapter_mode_info(interface.name),
'up': interface.flags & IFF_RUNNING != 0,
'ipv4': {
'supportedrequestmodes': ['dhcp_linklocal', 'dhcp_only', 'linklocal_only', 'static'],
'requestmode': _get_request_mode_info(interface.name)
},
'hwaddr': interface.hwaddr[:-1]
} | [
"def",
"_get_base_interface_info",
"(",
"interface",
")",
":",
"blacklist",
"=",
"{",
"'tcpip'",
":",
"{",
"'name'",
":",
"[",
"]",
",",
"'type'",
":",
"[",
"]",
",",
"'additional_protocol'",
":",
"False",
"}",
",",
"'disabled'",
":",
"{",
"'name'",
":",... | return base details about given interface | [
"return",
"base",
"details",
"about",
"given",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L377-L414 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_ethercat_interface_info | def _get_ethercat_interface_info(interface):
'''
return details about given ethercat interface
'''
base_information = _get_base_interface_info(interface)
base_information['ethercat'] = {
'masterid': _load_config(interface.name, ['MasterID'])['MasterID']
}
return base_information | python | def _get_ethercat_interface_info(interface):
'''
return details about given ethercat interface
'''
base_information = _get_base_interface_info(interface)
base_information['ethercat'] = {
'masterid': _load_config(interface.name, ['MasterID'])['MasterID']
}
return base_information | [
"def",
"_get_ethercat_interface_info",
"(",
"interface",
")",
":",
"base_information",
"=",
"_get_base_interface_info",
"(",
"interface",
")",
"base_information",
"[",
"'ethercat'",
"]",
"=",
"{",
"'masterid'",
":",
"_load_config",
"(",
"interface",
".",
"name",
","... | return details about given ethercat interface | [
"return",
"details",
"about",
"given",
"ethercat",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L417-L425 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_tcpip_interface_info | def _get_tcpip_interface_info(interface):
'''
return details about given tcpip interface
'''
base_information = _get_base_interface_info(interface)
if base_information['ipv4']['requestmode'] == 'static':
settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address'])
base_information['ipv4']['address'] = settings['IP_Address']
base_information['ipv4']['netmask'] = settings['Subnet_Mask']
base_information['ipv4']['gateway'] = settings['Gateway']
base_information['ipv4']['dns'] = [settings['DNS_Address']]
elif base_information['up']:
base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr)
base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask)
base_information['ipv4']['gateway'] = '0.0.0.0'
base_information['ipv4']['dns'] = _get_dns_info()
with salt.utils.files.fopen('/proc/net/route', 'r') as route_file:
pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name),
re.MULTILINE)
match = pattern.search(route_file.read())
iface_gateway_hex = None if not match else match.group(1)
if iface_gateway_hex is not None and len(iface_gateway_hex) == 8:
base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16))
for i in range(6, -1, -2)])
return base_information | python | def _get_tcpip_interface_info(interface):
'''
return details about given tcpip interface
'''
base_information = _get_base_interface_info(interface)
if base_information['ipv4']['requestmode'] == 'static':
settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address'])
base_information['ipv4']['address'] = settings['IP_Address']
base_information['ipv4']['netmask'] = settings['Subnet_Mask']
base_information['ipv4']['gateway'] = settings['Gateway']
base_information['ipv4']['dns'] = [settings['DNS_Address']]
elif base_information['up']:
base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr)
base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask)
base_information['ipv4']['gateway'] = '0.0.0.0'
base_information['ipv4']['dns'] = _get_dns_info()
with salt.utils.files.fopen('/proc/net/route', 'r') as route_file:
pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name),
re.MULTILINE)
match = pattern.search(route_file.read())
iface_gateway_hex = None if not match else match.group(1)
if iface_gateway_hex is not None and len(iface_gateway_hex) == 8:
base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16))
for i in range(6, -1, -2)])
return base_information | [
"def",
"_get_tcpip_interface_info",
"(",
"interface",
")",
":",
"base_information",
"=",
"_get_base_interface_info",
"(",
"interface",
")",
"if",
"base_information",
"[",
"'ipv4'",
"]",
"[",
"'requestmode'",
"]",
"==",
"'static'",
":",
"settings",
"=",
"_load_config... | return details about given tcpip interface | [
"return",
"details",
"about",
"given",
"tcpip",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L428-L452 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _get_interface_info | def _get_interface_info(interface):
'''
return details about given interface
'''
adapter_mode = _get_adapter_mode_info(interface.name)
if adapter_mode == 'disabled':
return _get_base_interface_info(interface)
elif adapter_mode == 'ethercat':
return _get_ethercat_interface_info(interface)
return _get_tcpip_interface_info(interface) | python | def _get_interface_info(interface):
'''
return details about given interface
'''
adapter_mode = _get_adapter_mode_info(interface.name)
if adapter_mode == 'disabled':
return _get_base_interface_info(interface)
elif adapter_mode == 'ethercat':
return _get_ethercat_interface_info(interface)
return _get_tcpip_interface_info(interface) | [
"def",
"_get_interface_info",
"(",
"interface",
")",
":",
"adapter_mode",
"=",
"_get_adapter_mode_info",
"(",
"interface",
".",
"name",
")",
"if",
"adapter_mode",
"==",
"'disabled'",
":",
"return",
"_get_base_interface_info",
"(",
"interface",
")",
"elif",
"adapter_... | return details about given interface | [
"return",
"details",
"about",
"given",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L455-L464 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _dict_to_string | def _dict_to_string(dictionary):
'''
converts a dictionary object into a list of strings
'''
ret = ''
for key, val in sorted(dictionary.items()):
if isinstance(val, dict):
for line in _dict_to_string(val):
ret += six.text_type(key) + '-' + line + '\n'
elif isinstance(val, list):
text = ' '.join([six.text_type(item) for item in val])
ret += six.text_type(key) + ': ' + text + '\n'
else:
ret += six.text_type(key) + ': ' + six.text_type(val) + '\n'
return ret.splitlines() | python | def _dict_to_string(dictionary):
'''
converts a dictionary object into a list of strings
'''
ret = ''
for key, val in sorted(dictionary.items()):
if isinstance(val, dict):
for line in _dict_to_string(val):
ret += six.text_type(key) + '-' + line + '\n'
elif isinstance(val, list):
text = ' '.join([six.text_type(item) for item in val])
ret += six.text_type(key) + ': ' + text + '\n'
else:
ret += six.text_type(key) + ': ' + six.text_type(val) + '\n'
return ret.splitlines() | [
"def",
"_dict_to_string",
"(",
"dictionary",
")",
":",
"ret",
"=",
"''",
"for",
"key",
",",
"val",
"in",
"sorted",
"(",
"dictionary",
".",
"items",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"for",
"line",
"in",
"_di... | converts a dictionary object into a list of strings | [
"converts",
"a",
"dictionary",
"object",
"into",
"a",
"list",
"of",
"strings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L467-L481 | train |
saltstack/salt | salt/modules/nilrt_ip.py | get_interfaces_details | def get_interfaces_details():
'''
Get details about all the interfaces on the minion
:return: information about all interfaces omitting loopback
:rtype: dictionary
CLI Example:
.. code-block:: bash
salt '*' ip.get_interfaces_details
'''
_interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0]
if __grains__['lsb_distrib_id'] == 'nilrt':
return {'interfaces': list(map(_get_interface_info, _interfaces))}
# filter just the services
_interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None]
return {'interfaces': list(map(_get_info, _interfaces))} | python | def get_interfaces_details():
'''
Get details about all the interfaces on the minion
:return: information about all interfaces omitting loopback
:rtype: dictionary
CLI Example:
.. code-block:: bash
salt '*' ip.get_interfaces_details
'''
_interfaces = [interface for interface in pyiface.getIfaces() if interface.flags & IFF_LOOPBACK == 0]
if __grains__['lsb_distrib_id'] == 'nilrt':
return {'interfaces': list(map(_get_interface_info, _interfaces))}
# filter just the services
_interfaces = [interface for interface in _interfaces if _interface_to_service(interface.name) is not None]
return {'interfaces': list(map(_get_info, _interfaces))} | [
"def",
"get_interfaces_details",
"(",
")",
":",
"_interfaces",
"=",
"[",
"interface",
"for",
"interface",
"in",
"pyiface",
".",
"getIfaces",
"(",
")",
"if",
"interface",
".",
"flags",
"&",
"IFF_LOOPBACK",
"==",
"0",
"]",
"if",
"__grains__",
"[",
"'lsb_distri... | Get details about all the interfaces on the minion
:return: information about all interfaces omitting loopback
:rtype: dictionary
CLI Example:
.. code-block:: bash
salt '*' ip.get_interfaces_details | [
"Get",
"details",
"about",
"all",
"the",
"interfaces",
"on",
"the",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L494-L512 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _change_state_legacy | def _change_state_legacy(interface, new_state):
'''
Enable or disable an interface on a legacy distro
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param interface: interface label
:param new_state: up or down
:return: True if the service was enabled, otherwise an exception will be thrown.
:rtype: bool
'''
initial_mode = _get_adapter_mode_info(interface)
_save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled')
if initial_mode == 'ethercat':
__salt__['system.set_reboot_required_witnessed']()
else:
out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state))
if out['retcode'] != 0:
msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable',
interface, out['stderr'])
raise salt.exceptions.CommandExecutionError(msg)
return True | python | def _change_state_legacy(interface, new_state):
'''
Enable or disable an interface on a legacy distro
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param interface: interface label
:param new_state: up or down
:return: True if the service was enabled, otherwise an exception will be thrown.
:rtype: bool
'''
initial_mode = _get_adapter_mode_info(interface)
_save_config(interface, 'Mode', 'TCPIP' if new_state == 'up' else 'Disabled')
if initial_mode == 'ethercat':
__salt__['system.set_reboot_required_witnessed']()
else:
out = __salt__['cmd.run_all']('ip link set {0} {1}'.format(interface, new_state))
if out['retcode'] != 0:
msg = 'Couldn\'t {0} interface {1}. Error: {2}'.format('enable' if new_state == 'up' else 'disable',
interface, out['stderr'])
raise salt.exceptions.CommandExecutionError(msg)
return True | [
"def",
"_change_state_legacy",
"(",
"interface",
",",
"new_state",
")",
":",
"initial_mode",
"=",
"_get_adapter_mode_info",
"(",
"interface",
")",
"_save_config",
"(",
"interface",
",",
"'Mode'",
",",
"'TCPIP'",
"if",
"new_state",
"==",
"'up'",
"else",
"'Disabled'... | Enable or disable an interface on a legacy distro
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param interface: interface label
:param new_state: up or down
:return: True if the service was enabled, otherwise an exception will be thrown.
:rtype: bool | [
"Enable",
"or",
"disable",
"an",
"interface",
"on",
"a",
"legacy",
"distro"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L515-L536 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _change_state | def _change_state(interface, new_state):
'''
Enable or disable an interface
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param interface: interface label
:param new_state: up or down
:return: True if the service was enabled, otherwise an exception will be thrown.
:rtype: bool
'''
if __grains__['lsb_distrib_id'] == 'nilrt':
return _change_state_legacy(interface, new_state)
service = _interface_to_service(interface)
if not service:
raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface))
connected = _connected(service)
if (not connected and new_state == 'up') or (connected and new_state == 'down'):
service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
try:
state = service.connect() if new_state == 'up' else service.disconnect()
return state is None
except Exception:
raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n'
.format('enable' if new_state == 'up' else 'disable', service))
return True | python | def _change_state(interface, new_state):
'''
Enable or disable an interface
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param interface: interface label
:param new_state: up or down
:return: True if the service was enabled, otherwise an exception will be thrown.
:rtype: bool
'''
if __grains__['lsb_distrib_id'] == 'nilrt':
return _change_state_legacy(interface, new_state)
service = _interface_to_service(interface)
if not service:
raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface))
connected = _connected(service)
if (not connected and new_state == 'up') or (connected and new_state == 'down'):
service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
try:
state = service.connect() if new_state == 'up' else service.disconnect()
return state is None
except Exception:
raise salt.exceptions.CommandExecutionError('Couldn\'t {0} service: {1}\n'
.format('enable' if new_state == 'up' else 'disable', service))
return True | [
"def",
"_change_state",
"(",
"interface",
",",
"new_state",
")",
":",
"if",
"__grains__",
"[",
"'lsb_distrib_id'",
"]",
"==",
"'nilrt'",
":",
"return",
"_change_state_legacy",
"(",
"interface",
",",
"new_state",
")",
"service",
"=",
"_interface_to_service",
"(",
... | Enable or disable an interface
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param interface: interface label
:param new_state: up or down
:return: True if the service was enabled, otherwise an exception will be thrown.
:rtype: bool | [
"Enable",
"or",
"disable",
"an",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L539-L564 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _save_config | def _save_config(section, token, value):
'''
Helper function to persist a configuration in the ini file
'''
cmd = NIRTCFG_PATH
cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value)
if __salt__['cmd.run_all'](cmd)['retcode'] != 0:
exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section)
raise salt.exceptions.CommandExecutionError(exc_msg) | python | def _save_config(section, token, value):
'''
Helper function to persist a configuration in the ini file
'''
cmd = NIRTCFG_PATH
cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value)
if __salt__['cmd.run_all'](cmd)['retcode'] != 0:
exc_msg = 'Error: could not set {} to {} for {}\n'.format(token, value, section)
raise salt.exceptions.CommandExecutionError(exc_msg) | [
"def",
"_save_config",
"(",
"section",
",",
"token",
",",
"value",
")",
":",
"cmd",
"=",
"NIRTCFG_PATH",
"cmd",
"+=",
"' --set section={0},token=\\'{1}\\',value=\\'{2}\\''",
".",
"format",
"(",
"section",
",",
"token",
",",
"value",
")",
"if",
"__salt__",
"[",
... | Helper function to persist a configuration in the ini file | [
"Helper",
"function",
"to",
"persist",
"a",
"configuration",
"in",
"the",
"ini",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L643-L651 | train |
saltstack/salt | salt/modules/nilrt_ip.py | set_ethercat | def set_ethercat(interface, master_id):
'''
Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't
already use EtherCAT adapter mode, otherwise will return true.
:param interface: interface label
:param master_id: EtherCAT Master ID
:return: True if the settings were applied, otherwise an exception will be thrown.
CLI Example:
.. code-block:: bash
salt '*' ip.set_ethercat interface-label master-id
'''
if __grains__['lsb_distrib_id'] == 'nilrt':
initial_mode = _get_adapter_mode_info(interface)
_save_config(interface, 'Mode', NIRTCFG_ETHERCAT)
_save_config(interface, 'MasterID', master_id)
if initial_mode != 'ethercat':
__salt__['system.set_reboot_required_witnessed']()
return True
raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') | python | def set_ethercat(interface, master_id):
'''
Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't
already use EtherCAT adapter mode, otherwise will return true.
:param interface: interface label
:param master_id: EtherCAT Master ID
:return: True if the settings were applied, otherwise an exception will be thrown.
CLI Example:
.. code-block:: bash
salt '*' ip.set_ethercat interface-label master-id
'''
if __grains__['lsb_distrib_id'] == 'nilrt':
initial_mode = _get_adapter_mode_info(interface)
_save_config(interface, 'Mode', NIRTCFG_ETHERCAT)
_save_config(interface, 'MasterID', master_id)
if initial_mode != 'ethercat':
__salt__['system.set_reboot_required_witnessed']()
return True
raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') | [
"def",
"set_ethercat",
"(",
"interface",
",",
"master_id",
")",
":",
"if",
"__grains__",
"[",
"'lsb_distrib_id'",
"]",
"==",
"'nilrt'",
":",
"initial_mode",
"=",
"_get_adapter_mode_info",
"(",
"interface",
")",
"_save_config",
"(",
"interface",
",",
"'Mode'",
",... | Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't
already use EtherCAT adapter mode, otherwise will return true.
:param interface: interface label
:param master_id: EtherCAT Master ID
:return: True if the settings were applied, otherwise an exception will be thrown.
CLI Example:
.. code-block:: bash
salt '*' ip.set_ethercat interface-label master-id | [
"Configure",
"specified",
"adapter",
"to",
"use",
"EtherCAT",
"adapter",
"mode",
".",
"If",
"successful",
"the",
"target",
"will",
"need",
"reboot",
"if",
"it",
"doesn",
"t",
"already",
"use",
"EtherCAT",
"adapter",
"mode",
"otherwise",
"will",
"return",
"true... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L654-L676 | train |
saltstack/salt | salt/modules/nilrt_ip.py | set_dhcp_linklocal_all | def set_dhcp_linklocal_all(interface):
'''
Configure specified adapter to use DHCP with linklocal fallback
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param str interface: interface label
:return: True if the settings were applied, otherwise an exception will be thrown.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' ip.set_dhcp_linklocal_all interface-label
'''
if __grains__['lsb_distrib_id'] == 'nilrt':
initial_mode = _get_adapter_mode_info(interface)
_save_config(interface, 'Mode', 'TCPIP')
_save_config(interface, 'dhcpenabled', '1')
_save_config(interface, 'linklocalenabled', '1')
if initial_mode == 'ethercat':
__salt__['system.set_reboot_required_witnessed']()
else:
_restart(interface)
return True
service = _interface_to_service(interface)
if not service:
raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface))
service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
ipv4 = service.get_property('IPv4.Configuration')
ipv4['Method'] = dbus.String('dhcp', variant_level=1)
ipv4['Address'] = dbus.String('', variant_level=1)
ipv4['Netmask'] = dbus.String('', variant_level=1)
ipv4['Gateway'] = dbus.String('', variant_level=1)
try:
service.set_property('IPv4.Configuration', ipv4)
service.set_property('Nameservers.Configuration', ['']) # reset nameservers list
except Exception as exc:
exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc)
raise salt.exceptions.CommandExecutionError(exc_msg)
return True | python | def set_dhcp_linklocal_all(interface):
'''
Configure specified adapter to use DHCP with linklocal fallback
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param str interface: interface label
:return: True if the settings were applied, otherwise an exception will be thrown.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' ip.set_dhcp_linklocal_all interface-label
'''
if __grains__['lsb_distrib_id'] == 'nilrt':
initial_mode = _get_adapter_mode_info(interface)
_save_config(interface, 'Mode', 'TCPIP')
_save_config(interface, 'dhcpenabled', '1')
_save_config(interface, 'linklocalenabled', '1')
if initial_mode == 'ethercat':
__salt__['system.set_reboot_required_witnessed']()
else:
_restart(interface)
return True
service = _interface_to_service(interface)
if not service:
raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface))
service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
ipv4 = service.get_property('IPv4.Configuration')
ipv4['Method'] = dbus.String('dhcp', variant_level=1)
ipv4['Address'] = dbus.String('', variant_level=1)
ipv4['Netmask'] = dbus.String('', variant_level=1)
ipv4['Gateway'] = dbus.String('', variant_level=1)
try:
service.set_property('IPv4.Configuration', ipv4)
service.set_property('Nameservers.Configuration', ['']) # reset nameservers list
except Exception as exc:
exc_msg = 'Couldn\'t set dhcp linklocal for service: {0}\nError: {1}\n'.format(service, exc)
raise salt.exceptions.CommandExecutionError(exc_msg)
return True | [
"def",
"set_dhcp_linklocal_all",
"(",
"interface",
")",
":",
"if",
"__grains__",
"[",
"'lsb_distrib_id'",
"]",
"==",
"'nilrt'",
":",
"initial_mode",
"=",
"_get_adapter_mode_info",
"(",
"interface",
")",
"_save_config",
"(",
"interface",
",",
"'Mode'",
",",
"'TCPIP... | Configure specified adapter to use DHCP with linklocal fallback
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param str interface: interface label
:return: True if the settings were applied, otherwise an exception will be thrown.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' ip.set_dhcp_linklocal_all interface-label | [
"Configure",
"specified",
"adapter",
"to",
"use",
"DHCP",
"with",
"linklocal",
"fallback"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L687-L728 | train |
saltstack/salt | salt/modules/nilrt_ip.py | set_dhcp_only_all | def set_dhcp_only_all(interface):
'''
Configure specified adapter to use DHCP only
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param str interface: interface label
:return: True if the settings were applied, otherwise an exception will be thrown.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' ip.dhcp_only_all interface-label
'''
if not __grains__['lsb_distrib_id'] == 'nilrt':
raise salt.exceptions.CommandExecutionError('Not supported in this version')
initial_mode = _get_adapter_mode_info(interface)
_save_config(interface, 'Mode', 'TCPIP')
_save_config(interface, 'dhcpenabled', '1')
_save_config(interface, 'linklocalenabled', '0')
if initial_mode == 'ethercat':
__salt__['system.set_reboot_required_witnessed']()
else:
_restart(interface)
return True | python | def set_dhcp_only_all(interface):
'''
Configure specified adapter to use DHCP only
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param str interface: interface label
:return: True if the settings were applied, otherwise an exception will be thrown.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' ip.dhcp_only_all interface-label
'''
if not __grains__['lsb_distrib_id'] == 'nilrt':
raise salt.exceptions.CommandExecutionError('Not supported in this version')
initial_mode = _get_adapter_mode_info(interface)
_save_config(interface, 'Mode', 'TCPIP')
_save_config(interface, 'dhcpenabled', '1')
_save_config(interface, 'linklocalenabled', '0')
if initial_mode == 'ethercat':
__salt__['system.set_reboot_required_witnessed']()
else:
_restart(interface)
return True | [
"def",
"set_dhcp_only_all",
"(",
"interface",
")",
":",
"if",
"not",
"__grains__",
"[",
"'lsb_distrib_id'",
"]",
"==",
"'nilrt'",
":",
"raise",
"salt",
".",
"exceptions",
".",
"CommandExecutionError",
"(",
"'Not supported in this version'",
")",
"initial_mode",
"=",... | Configure specified adapter to use DHCP only
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param str interface: interface label
:return: True if the settings were applied, otherwise an exception will be thrown.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' ip.dhcp_only_all interface-label | [
"Configure",
"specified",
"adapter",
"to",
"use",
"DHCP",
"only"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L731-L757 | train |
saltstack/salt | salt/modules/nilrt_ip.py | _configure_static_interface | def _configure_static_interface(interface, **settings):
'''
Configure an interface that is not detected as a service by Connman (i.e. link is down)
:param interface: interface label
:param settings:
- ip
- netmask
- gateway
- dns
- name
:return: True if settings were applied successfully.
:rtype: bool
'''
interface = pyiface.Interface(name=interface)
parser = configparser.ConfigParser()
if os.path.exists(INTERFACES_CONFIG):
try:
with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file:
parser.readfp(config_file)
except configparser.MissingSectionHeaderError:
pass
hwaddr = interface.hwaddr[:-1]
hwaddr_section_number = ''.join(hwaddr.split(':'))
if not parser.has_section('interface_{0}'.format(hwaddr_section_number)):
parser.add_section('interface_{0}'.format(hwaddr_section_number))
ip_address = settings.get('ip', '0.0.0.0')
netmask = settings.get('netmask', '0.0.0.0')
gateway = settings.get('gateway', '0.0.0.0')
dns_servers = settings.get('dns', '')
name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number))
parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'.
format(ip_address, netmask, gateway))
parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers)
parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name)
parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr)
parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet')
with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file:
parser.write(config_file)
return True | python | def _configure_static_interface(interface, **settings):
'''
Configure an interface that is not detected as a service by Connman (i.e. link is down)
:param interface: interface label
:param settings:
- ip
- netmask
- gateway
- dns
- name
:return: True if settings were applied successfully.
:rtype: bool
'''
interface = pyiface.Interface(name=interface)
parser = configparser.ConfigParser()
if os.path.exists(INTERFACES_CONFIG):
try:
with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file:
parser.readfp(config_file)
except configparser.MissingSectionHeaderError:
pass
hwaddr = interface.hwaddr[:-1]
hwaddr_section_number = ''.join(hwaddr.split(':'))
if not parser.has_section('interface_{0}'.format(hwaddr_section_number)):
parser.add_section('interface_{0}'.format(hwaddr_section_number))
ip_address = settings.get('ip', '0.0.0.0')
netmask = settings.get('netmask', '0.0.0.0')
gateway = settings.get('gateway', '0.0.0.0')
dns_servers = settings.get('dns', '')
name = settings.get('name', 'ethernet_cable_{0}'.format(hwaddr_section_number))
parser.set('interface_{0}'.format(hwaddr_section_number), 'IPv4', '{0}/{1}/{2}'.
format(ip_address, netmask, gateway))
parser.set('interface_{0}'.format(hwaddr_section_number), 'Nameservers', dns_servers)
parser.set('interface_{0}'.format(hwaddr_section_number), 'Name', name)
parser.set('interface_{0}'.format(hwaddr_section_number), 'MAC', hwaddr)
parser.set('interface_{0}'.format(hwaddr_section_number), 'Type', 'ethernet')
with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file:
parser.write(config_file)
return True | [
"def",
"_configure_static_interface",
"(",
"interface",
",",
"*",
"*",
"settings",
")",
":",
"interface",
"=",
"pyiface",
".",
"Interface",
"(",
"name",
"=",
"interface",
")",
"parser",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"if",
"os",
".",
"... | Configure an interface that is not detected as a service by Connman (i.e. link is down)
:param interface: interface label
:param settings:
- ip
- netmask
- gateway
- dns
- name
:return: True if settings were applied successfully.
:rtype: bool | [
"Configure",
"an",
"interface",
"that",
"is",
"not",
"detected",
"as",
"a",
"service",
"by",
"Connman",
"(",
"i",
".",
"e",
".",
"link",
"is",
"down",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L789-L828 | train |
saltstack/salt | salt/modules/nilrt_ip.py | set_static_all | def set_static_all(interface, address, netmask, gateway, nameservers=None):
'''
Configure specified adapter to use ipv4 manual settings
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param str interface: interface label
:param str address: ipv4 address
:param str netmask: ipv4 netmask
:param str gateway: ipv4 gateway
:param str nameservers: list of nameservers servers separated by spaces (Optional)
:return: True if the settings were applied, otherwise an exception will be thrown.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' ip.set_static_all interface-label address netmask gateway nameservers
'''
validate, msg = _validate_ipv4([address, netmask, gateway])
if not validate:
raise salt.exceptions.CommandExecutionError(msg)
if nameservers:
validate, msg = _space_delimited_list(nameservers)
if not validate:
raise salt.exceptions.CommandExecutionError(msg)
if not isinstance(nameservers, list):
nameservers = nameservers.split(' ')
if __grains__['lsb_distrib_id'] == 'nilrt':
initial_mode = _get_adapter_mode_info(interface)
_save_config(interface, 'Mode', 'TCPIP')
_save_config(interface, 'dhcpenabled', '0')
_save_config(interface, 'linklocalenabled', '0')
_save_config(interface, 'IP_Address', address)
_save_config(interface, 'Subnet_Mask', netmask)
_save_config(interface, 'Gateway', gateway)
if nameservers:
_save_config(interface, 'DNS_Address', nameservers[0])
if initial_mode == 'ethercat':
__salt__['system.set_reboot_required_witnessed']()
else:
_restart(interface)
return True
service = _interface_to_service(interface)
if not service:
if interface in pyiface.getIfaces():
return _configure_static_interface(interface, **{'ip': address,
'dns': ','.join(nameservers) if nameservers else '',
'netmask': netmask, 'gateway': gateway})
raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface))
service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
ipv4 = service.get_property('IPv4.Configuration')
ipv4['Method'] = dbus.String('manual', variant_level=1)
ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1)
ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1)
ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1)
try:
service.set_property('IPv4.Configuration', ipv4)
if nameservers:
service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers])
except Exception as exc:
exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc)
raise salt.exceptions.CommandExecutionError(exc_msg)
return True | python | def set_static_all(interface, address, netmask, gateway, nameservers=None):
'''
Configure specified adapter to use ipv4 manual settings
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param str interface: interface label
:param str address: ipv4 address
:param str netmask: ipv4 netmask
:param str gateway: ipv4 gateway
:param str nameservers: list of nameservers servers separated by spaces (Optional)
:return: True if the settings were applied, otherwise an exception will be thrown.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' ip.set_static_all interface-label address netmask gateway nameservers
'''
validate, msg = _validate_ipv4([address, netmask, gateway])
if not validate:
raise salt.exceptions.CommandExecutionError(msg)
if nameservers:
validate, msg = _space_delimited_list(nameservers)
if not validate:
raise salt.exceptions.CommandExecutionError(msg)
if not isinstance(nameservers, list):
nameservers = nameservers.split(' ')
if __grains__['lsb_distrib_id'] == 'nilrt':
initial_mode = _get_adapter_mode_info(interface)
_save_config(interface, 'Mode', 'TCPIP')
_save_config(interface, 'dhcpenabled', '0')
_save_config(interface, 'linklocalenabled', '0')
_save_config(interface, 'IP_Address', address)
_save_config(interface, 'Subnet_Mask', netmask)
_save_config(interface, 'Gateway', gateway)
if nameservers:
_save_config(interface, 'DNS_Address', nameservers[0])
if initial_mode == 'ethercat':
__salt__['system.set_reboot_required_witnessed']()
else:
_restart(interface)
return True
service = _interface_to_service(interface)
if not service:
if interface in pyiface.getIfaces():
return _configure_static_interface(interface, **{'ip': address,
'dns': ','.join(nameservers) if nameservers else '',
'netmask': netmask, 'gateway': gateway})
raise salt.exceptions.CommandExecutionError('Invalid interface name: {0}'.format(interface))
service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service))
ipv4 = service.get_property('IPv4.Configuration')
ipv4['Method'] = dbus.String('manual', variant_level=1)
ipv4['Address'] = dbus.String('{0}'.format(address), variant_level=1)
ipv4['Netmask'] = dbus.String('{0}'.format(netmask), variant_level=1)
ipv4['Gateway'] = dbus.String('{0}'.format(gateway), variant_level=1)
try:
service.set_property('IPv4.Configuration', ipv4)
if nameservers:
service.set_property('Nameservers.Configuration', [dbus.String('{0}'.format(d)) for d in nameservers])
except Exception as exc:
exc_msg = 'Couldn\'t set manual settings for service: {0}\nError: {1}\n'.format(service, exc)
raise salt.exceptions.CommandExecutionError(exc_msg)
return True | [
"def",
"set_static_all",
"(",
"interface",
",",
"address",
",",
"netmask",
",",
"gateway",
",",
"nameservers",
"=",
"None",
")",
":",
"validate",
",",
"msg",
"=",
"_validate_ipv4",
"(",
"[",
"address",
",",
"netmask",
",",
"gateway",
"]",
")",
"if",
"not... | Configure specified adapter to use ipv4 manual settings
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param str interface: interface label
:param str address: ipv4 address
:param str netmask: ipv4 netmask
:param str gateway: ipv4 gateway
:param str nameservers: list of nameservers servers separated by spaces (Optional)
:return: True if the settings were applied, otherwise an exception will be thrown.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' ip.set_static_all interface-label address netmask gateway nameservers | [
"Configure",
"specified",
"adapter",
"to",
"use",
"ipv4",
"manual",
"settings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L831-L895 | train |
saltstack/salt | salt/modules/nilrt_ip.py | get_interface | def get_interface(iface):
'''
Returns details about given interface.
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
_interfaces = get_interfaces_details()
for _interface in _interfaces['interfaces']:
if _interface['connectionid'] == iface:
return _dict_to_string(_interface)
return None | python | def get_interface(iface):
'''
Returns details about given interface.
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0
'''
_interfaces = get_interfaces_details()
for _interface in _interfaces['interfaces']:
if _interface['connectionid'] == iface:
return _dict_to_string(_interface)
return None | [
"def",
"get_interface",
"(",
"iface",
")",
":",
"_interfaces",
"=",
"get_interfaces_details",
"(",
")",
"for",
"_interface",
"in",
"_interfaces",
"[",
"'interfaces'",
"]",
":",
"if",
"_interface",
"[",
"'connectionid'",
"]",
"==",
"iface",
":",
"return",
"_dic... | Returns details about given interface.
CLI Example:
.. code-block:: bash
salt '*' ip.get_interface eth0 | [
"Returns",
"details",
"about",
"given",
"interface",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L898-L912 | train |
saltstack/salt | salt/modules/nilrt_ip.py | build_interface | def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
if __grains__['lsb_distrib_id'] == 'nilrt':
raise salt.exceptions.CommandExecutionError('Not supported in this version.')
if iface_type != 'eth':
raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type))
if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp
set_dhcp_linklocal_all(iface)
elif settings['proto'] != 'static':
exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto'])
raise salt.exceptions.CommandExecutionError(exc_msg)
else:
address = settings['ipaddr']
netmask = settings['netmask']
gateway = settings['gateway']
dns = []
for key, val in six.iteritems(settings):
if 'dns' in key or 'domain' in key:
dns += val
set_static_all(iface, address, netmask, gateway, dns)
if enabled:
up(iface)
return get_interface(iface) | python | def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings>
'''
if __grains__['lsb_distrib_id'] == 'nilrt':
raise salt.exceptions.CommandExecutionError('Not supported in this version.')
if iface_type != 'eth':
raise salt.exceptions.CommandExecutionError('Interface type not supported: {0}:'.format(iface_type))
if 'proto' not in settings or settings['proto'] == 'dhcp': # default protocol type used is dhcp
set_dhcp_linklocal_all(iface)
elif settings['proto'] != 'static':
exc_msg = 'Protocol type: {0} is not supported'.format(settings['proto'])
raise salt.exceptions.CommandExecutionError(exc_msg)
else:
address = settings['ipaddr']
netmask = settings['netmask']
gateway = settings['gateway']
dns = []
for key, val in six.iteritems(settings):
if 'dns' in key or 'domain' in key:
dns += val
set_static_all(iface, address, netmask, gateway, dns)
if enabled:
up(iface)
return get_interface(iface) | [
"def",
"build_interface",
"(",
"iface",
",",
"iface_type",
",",
"enabled",
",",
"*",
"*",
"settings",
")",
":",
"if",
"__grains__",
"[",
"'lsb_distrib_id'",
"]",
"==",
"'nilrt'",
":",
"raise",
"salt",
".",
"exceptions",
".",
"CommandExecutionError",
"(",
"'N... | Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth <settings> | [
"Build",
"an",
"interface",
"script",
"for",
"a",
"network",
"interface",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nilrt_ip.py#L915-L948 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.