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/azurearm_network.py | route_delete | def route_delete(name, route_table, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a route from a route table.
:param name: The route to delete.
:param route_table: The route table containing the route.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_delete test-rt test-rt-table testgroup
'''
result = False
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
route = netconn.routes.delete(
resource_group_name=resource_group,
route_table_name=route_table,
route_name=name
)
route.wait()
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
return result | python | def route_delete(name, route_table, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a route from a route table.
:param name: The route to delete.
:param route_table: The route table containing the route.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_delete test-rt test-rt-table testgroup
'''
result = False
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
route = netconn.routes.delete(
resource_group_name=resource_group,
route_table_name=route_table,
route_name=name
)
route.wait()
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
return result | [
"def",
"route_delete",
"(",
"name",
",",
"route_table",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",... | .. versionadded:: 2019.2.0
Delete a route from a route table.
:param name: The route to delete.
:param route_table: The route table containing the route.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_delete test-rt test-rt-table testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L2392-L2425 | train |
saltstack/salt | salt/modules/azurearm_network.py | route_get | def route_get(name, route_table, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific route.
:param name: The route to query.
:param route_table: The route table containing the route.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_get test-rt test-rt-table testgroup
'''
result = {}
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
route = netconn.routes.get(
resource_group_name=resource_group,
route_table_name=route_table,
route_name=name
)
result = route.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def route_get(name, route_table, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific route.
:param name: The route to query.
:param route_table: The route table containing the route.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_get test-rt test-rt-table testgroup
'''
result = {}
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
route = netconn.routes.get(
resource_group_name=resource_group,
route_table_name=route_table,
route_name=name
)
result = route.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"route_get",
"(",
"name",
",",
"route_table",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",... | .. versionadded:: 2019.2.0
Get details about a specific route.
:param name: The route to query.
:param route_table: The route table containing the route.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_get test-rt test-rt-table testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L2428-L2462 | train |
saltstack/salt | salt/modules/azurearm_network.py | route_create_or_update | def route_create_or_update(name, address_prefix, next_hop_type, route_table, resource_group,
next_hop_ip_address=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Create or update a route within a specified route table.
:param name: The name of the route to create.
:param address_prefix: The destination CIDR to which the route applies.
:param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are:
'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'.
:param next_hop_ip_address: Optional IP address to which packets should be forwarded. Next hop
values are only allowed in routes where the next_hop_type is 'VirtualAppliance'.
:param route_table: The name of the route table containing the route.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_create_or_update test-rt '10.0.0.0/8' test-rt-table testgroup
'''
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
rt_model = __utils__['azurearm.create_object_model'](
'network',
'Route',
address_prefix=address_prefix,
next_hop_type=next_hop_type,
next_hop_ip_address=next_hop_ip_address,
**kwargs
)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
route = netconn.routes.create_or_update(
resource_group_name=resource_group,
route_table_name=route_table,
route_name=name,
route_parameters=rt_model
)
route.wait()
rt_result = route.result()
result = rt_result.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
return result | python | def route_create_or_update(name, address_prefix, next_hop_type, route_table, resource_group,
next_hop_ip_address=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Create or update a route within a specified route table.
:param name: The name of the route to create.
:param address_prefix: The destination CIDR to which the route applies.
:param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are:
'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'.
:param next_hop_ip_address: Optional IP address to which packets should be forwarded. Next hop
values are only allowed in routes where the next_hop_type is 'VirtualAppliance'.
:param route_table: The name of the route table containing the route.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_create_or_update test-rt '10.0.0.0/8' test-rt-table testgroup
'''
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
rt_model = __utils__['azurearm.create_object_model'](
'network',
'Route',
address_prefix=address_prefix,
next_hop_type=next_hop_type,
next_hop_ip_address=next_hop_ip_address,
**kwargs
)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
route = netconn.routes.create_or_update(
resource_group_name=resource_group,
route_table_name=route_table,
route_name=name,
route_parameters=rt_model
)
route.wait()
rt_result = route.result()
result = rt_result.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
return result | [
"def",
"route_create_or_update",
"(",
"name",
",",
"address_prefix",
",",
"next_hop_type",
",",
"route_table",
",",
"resource_group",
",",
"next_hop_ip_address",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_clien... | .. versionadded:: 2019.2.0
Create or update a route within a specified route table.
:param name: The name of the route to create.
:param address_prefix: The destination CIDR to which the route applies.
:param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are:
'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'.
:param next_hop_ip_address: Optional IP address to which packets should be forwarded. Next hop
values are only allowed in routes where the next_hop_type is 'VirtualAppliance'.
:param route_table: The name of the route table containing the route.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_create_or_update test-rt '10.0.0.0/8' test-rt-table testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L2465-L2525 | train |
saltstack/salt | salt/modules/azurearm_network.py | routes_list | def routes_list(route_table, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all routes within a route table.
:param route_table: The route table to query.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.routes_list test-rt-table testgroup
'''
result = {}
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
routes = __utils__['azurearm.paged_object_to_list'](
netconn.routes.list(
resource_group_name=resource_group,
route_table_name=route_table
)
)
for route in routes:
result[route['name']] = route
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def routes_list(route_table, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all routes within a route table.
:param route_table: The route table to query.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.routes_list test-rt-table testgroup
'''
result = {}
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
routes = __utils__['azurearm.paged_object_to_list'](
netconn.routes.list(
resource_group_name=resource_group,
route_table_name=route_table
)
)
for route in routes:
result[route['name']] = route
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"routes_list",
"(",
"route_table",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"rout... | .. versionadded:: 2019.2.0
List all routes within a route table.
:param route_table: The route table to query.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.routes_list test-rt-table testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L2528-L2562 | train |
saltstack/salt | salt/modules/azurearm_network.py | route_table_delete | def route_table_delete(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a route table.
:param name: The name of the route table to delete.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_table_delete test-rt-table testgroup
'''
result = False
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
table = netconn.route_tables.delete(
route_table_name=name,
resource_group_name=resource_group
)
table.wait()
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
return result | python | def route_table_delete(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a route table.
:param name: The name of the route table to delete.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_table_delete test-rt-table testgroup
'''
result = False
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
table = netconn.route_tables.delete(
route_table_name=name,
resource_group_name=resource_group
)
table.wait()
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
return result | [
"def",
"route_table_delete",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"table",... | .. versionadded:: 2019.2.0
Delete a route table.
:param name: The name of the route table to delete.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_table_delete test-rt-table testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L2565-L2595 | train |
saltstack/salt | salt/modules/azurearm_network.py | route_table_get | def route_table_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific route table.
:param name: The name of the route table to query.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_table_get test-rt-table testgroup
'''
expand = kwargs.get('expand')
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
table = netconn.route_tables.get(
route_table_name=name,
resource_group_name=resource_group,
expand=expand
)
result = table.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def route_table_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific route table.
:param name: The name of the route table to query.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_table_get test-rt-table testgroup
'''
expand = kwargs.get('expand')
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
table = netconn.route_tables.get(
route_table_name=name,
resource_group_name=resource_group,
expand=expand
)
result = table.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"route_table_get",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"expand",
"=",
"kwargs",
".",
"get",
"(",
"'expand'",
")",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"... | .. versionadded:: 2019.2.0
Get details about a specific route table.
:param name: The name of the route table to query.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_table_get test-rt-table testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L2598-L2631 | train |
saltstack/salt | salt/modules/azurearm_network.py | route_table_create_or_update | def route_table_create_or_update(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Create or update a route table within a specified resource group.
:param name: The name of the route table to create.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_table_create_or_update test-rt-table testgroup
'''
if 'location' not in kwargs:
rg_props = __salt__['azurearm_resource.resource_group_get'](
resource_group, **kwargs
)
if 'error' in rg_props:
log.error(
'Unable to determine location from resource group specified.'
)
return False
kwargs['location'] = rg_props['location']
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
rt_tbl_model = __utils__['azurearm.create_object_model']('network', 'RouteTable', **kwargs)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
table = netconn.route_tables.create_or_update(
resource_group_name=resource_group,
route_table_name=name,
parameters=rt_tbl_model
)
table.wait()
tbl_result = table.result()
result = tbl_result.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
return result | python | def route_table_create_or_update(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Create or update a route table within a specified resource group.
:param name: The name of the route table to create.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_table_create_or_update test-rt-table testgroup
'''
if 'location' not in kwargs:
rg_props = __salt__['azurearm_resource.resource_group_get'](
resource_group, **kwargs
)
if 'error' in rg_props:
log.error(
'Unable to determine location from resource group specified.'
)
return False
kwargs['location'] = rg_props['location']
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
rt_tbl_model = __utils__['azurearm.create_object_model']('network', 'RouteTable', **kwargs)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
table = netconn.route_tables.create_or_update(
resource_group_name=resource_group,
route_table_name=name,
parameters=rt_tbl_model
)
table.wait()
tbl_result = table.result()
result = tbl_result.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
return result | [
"def",
"route_table_create_or_update",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'location'",
"not",
"in",
"kwargs",
":",
"rg_props",
"=",
"__salt__",
"[",
"'azurearm_resource.resource_group_get'",
"]",
"(",
"resource_group",
",... | .. versionadded:: 2019.2.0
Create or update a route table within a specified resource group.
:param name: The name of the route table to create.
:param resource_group: The resource group name assigned to the
route table.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_table_create_or_update test-rt-table testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L2634-L2687 | train |
saltstack/salt | salt/modules/azurearm_network.py | route_tables_list | def route_tables_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all route tables within a resource group.
:param resource_group: The resource group name to list route
tables within.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_tables_list testgroup
'''
result = {}
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
tables = __utils__['azurearm.paged_object_to_list'](
netconn.route_tables.list(
resource_group_name=resource_group
)
)
for table in tables:
result[table['name']] = table
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def route_tables_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all route tables within a resource group.
:param resource_group: The resource group name to list route
tables within.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_tables_list testgroup
'''
result = {}
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
tables = __utils__['azurearm.paged_object_to_list'](
netconn.route_tables.list(
resource_group_name=resource_group
)
)
for table in tables:
result[table['name']] = table
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"route_tables_list",
"(",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"tables",
"=",
"__u... | .. versionadded:: 2019.2.0
List all route tables within a resource group.
:param resource_group: The resource group name to list route
tables within.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_tables_list testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L2690-L2721 | train |
saltstack/salt | salt/modules/azurearm_network.py | route_tables_list_all | def route_tables_list_all(**kwargs):
'''
.. versionadded:: 2019.2.0
List all route tables within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_tables_list_all
'''
result = {}
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
tables = __utils__['azurearm.paged_object_to_list'](netconn.route_tables.list_all())
for table in tables:
result[table['name']] = table
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def route_tables_list_all(**kwargs):
'''
.. versionadded:: 2019.2.0
List all route tables within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_tables_list_all
'''
result = {}
netconn = __utils__['azurearm.get_client']('network', **kwargs)
try:
tables = __utils__['azurearm.paged_object_to_list'](netconn.route_tables.list_all())
for table in tables:
result[table['name']] = table
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"route_tables_list_all",
"(",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"tables",
"=",
"__utils__",
"[",
"'azu... | .. versionadded:: 2019.2.0
List all route tables within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_tables_list_all | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_network.py#L2724-L2748 | train |
saltstack/salt | salt/modules/capirca_acl.py | _import_platform_generator | def _import_platform_generator(platform):
'''
Given a specific platform (under the Capirca conventions),
return the generator class.
The generator class is identified looking under the <platform> module
for a class inheriting the `ACLGenerator` class.
'''
log.debug('Using platform: %s', platform)
for mod_name, mod_obj in inspect.getmembers(capirca.aclgen):
if mod_name == platform and inspect.ismodule(mod_obj):
for plat_obj_name, plat_obj in inspect.getmembers(mod_obj): # pylint: disable=unused-variable
if inspect.isclass(plat_obj) and issubclass(plat_obj, capirca.lib.aclgenerator.ACLGenerator):
log.debug('Identified Capirca class %s for %s', plat_obj, platform)
return plat_obj
log.error('Unable to identify any Capirca plaform class for %s', platform) | python | def _import_platform_generator(platform):
'''
Given a specific platform (under the Capirca conventions),
return the generator class.
The generator class is identified looking under the <platform> module
for a class inheriting the `ACLGenerator` class.
'''
log.debug('Using platform: %s', platform)
for mod_name, mod_obj in inspect.getmembers(capirca.aclgen):
if mod_name == platform and inspect.ismodule(mod_obj):
for plat_obj_name, plat_obj in inspect.getmembers(mod_obj): # pylint: disable=unused-variable
if inspect.isclass(plat_obj) and issubclass(plat_obj, capirca.lib.aclgenerator.ACLGenerator):
log.debug('Identified Capirca class %s for %s', plat_obj, platform)
return plat_obj
log.error('Unable to identify any Capirca plaform class for %s', platform) | [
"def",
"_import_platform_generator",
"(",
"platform",
")",
":",
"log",
".",
"debug",
"(",
"'Using platform: %s'",
",",
"platform",
")",
"for",
"mod_name",
",",
"mod_obj",
"in",
"inspect",
".",
"getmembers",
"(",
"capirca",
".",
"aclgen",
")",
":",
"if",
"mod... | Given a specific platform (under the Capirca conventions),
return the generator class.
The generator class is identified looking under the <platform> module
for a class inheriting the `ACLGenerator` class. | [
"Given",
"a",
"specific",
"platform",
"(",
"under",
"the",
"Capirca",
"conventions",
")",
"return",
"the",
"generator",
"class",
".",
"The",
"generator",
"class",
"is",
"identified",
"looking",
"under",
"the",
"<platform",
">",
"module",
"for",
"a",
"class",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L197-L211 | train |
saltstack/salt | salt/modules/capirca_acl.py | _get_services_mapping | def _get_services_mapping():
'''
Build a map of services based on the IANA assignment list:
http://www.iana.org/assignments/port-numbers
It will load the /etc/services file and will build the mapping on the fly,
similar to the Capirca's SERVICES file:
https://github.com/google/capirca/blob/master/def/SERVICES.svc
As this module is be available on Unix systems only,
we'll read the services from /etc/services.
In the worst case, the user will not be able to specify the
services shortcut and they will need to specify the protocol / port combination
using the source_port / destination_port & protocol fields.
'''
if _SERVICES:
return _SERVICES
services_txt = ''
try:
with salt.utils.files.fopen('/etc/services', 'r') as srv_f:
services_txt = salt.utils.stringutils.to_unicode(srv_f.read())
except IOError as ioe:
log.error('Unable to read from /etc/services:')
log.error(ioe)
return _SERVICES # no mapping possible, sorry
# will return the default mapping
service_rgx = re.compile(r'^([a-zA-Z0-9-]+)\s+(\d+)\/(tcp|udp)(.*)$')
for line in services_txt.splitlines():
service_rgx_s = service_rgx.search(line)
if service_rgx_s and len(service_rgx_s.groups()) == 4:
srv_name, port, protocol, _ = service_rgx_s.groups()
if srv_name not in _SERVICES:
_SERVICES[srv_name] = {
'port': [],
'protocol': []
}
try:
_SERVICES[srv_name]['port'].append(int(port))
except ValueError as verr:
log.error(verr)
log.error('Did not read that properly:')
log.error(line)
log.error('Please report the above error: %s does not seem a valid port value!', port)
_SERVICES[srv_name]['protocol'].append(protocol)
return _SERVICES | python | def _get_services_mapping():
'''
Build a map of services based on the IANA assignment list:
http://www.iana.org/assignments/port-numbers
It will load the /etc/services file and will build the mapping on the fly,
similar to the Capirca's SERVICES file:
https://github.com/google/capirca/blob/master/def/SERVICES.svc
As this module is be available on Unix systems only,
we'll read the services from /etc/services.
In the worst case, the user will not be able to specify the
services shortcut and they will need to specify the protocol / port combination
using the source_port / destination_port & protocol fields.
'''
if _SERVICES:
return _SERVICES
services_txt = ''
try:
with salt.utils.files.fopen('/etc/services', 'r') as srv_f:
services_txt = salt.utils.stringutils.to_unicode(srv_f.read())
except IOError as ioe:
log.error('Unable to read from /etc/services:')
log.error(ioe)
return _SERVICES # no mapping possible, sorry
# will return the default mapping
service_rgx = re.compile(r'^([a-zA-Z0-9-]+)\s+(\d+)\/(tcp|udp)(.*)$')
for line in services_txt.splitlines():
service_rgx_s = service_rgx.search(line)
if service_rgx_s and len(service_rgx_s.groups()) == 4:
srv_name, port, protocol, _ = service_rgx_s.groups()
if srv_name not in _SERVICES:
_SERVICES[srv_name] = {
'port': [],
'protocol': []
}
try:
_SERVICES[srv_name]['port'].append(int(port))
except ValueError as verr:
log.error(verr)
log.error('Did not read that properly:')
log.error(line)
log.error('Please report the above error: %s does not seem a valid port value!', port)
_SERVICES[srv_name]['protocol'].append(protocol)
return _SERVICES | [
"def",
"_get_services_mapping",
"(",
")",
":",
"if",
"_SERVICES",
":",
"return",
"_SERVICES",
"services_txt",
"=",
"''",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/etc/services'",
",",
"'r'",
")",
"as",
"srv_f",
":",
"s... | Build a map of services based on the IANA assignment list:
http://www.iana.org/assignments/port-numbers
It will load the /etc/services file and will build the mapping on the fly,
similar to the Capirca's SERVICES file:
https://github.com/google/capirca/blob/master/def/SERVICES.svc
As this module is be available on Unix systems only,
we'll read the services from /etc/services.
In the worst case, the user will not be able to specify the
services shortcut and they will need to specify the protocol / port combination
using the source_port / destination_port & protocol fields. | [
"Build",
"a",
"map",
"of",
"services",
"based",
"on",
"the",
"IANA",
"assignment",
"list",
":",
"http",
":",
"//",
"www",
".",
"iana",
".",
"org",
"/",
"assignments",
"/",
"port",
"-",
"numbers"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L214-L258 | train |
saltstack/salt | salt/modules/capirca_acl.py | _translate_port | def _translate_port(port):
'''
Look into services and return the port value using the
service name as lookup value.
'''
services = _get_services_mapping()
if port in services and services[port]['port']:
return services[port]['port'][0]
return port | python | def _translate_port(port):
'''
Look into services and return the port value using the
service name as lookup value.
'''
services = _get_services_mapping()
if port in services and services[port]['port']:
return services[port]['port'][0]
return port | [
"def",
"_translate_port",
"(",
"port",
")",
":",
"services",
"=",
"_get_services_mapping",
"(",
")",
"if",
"port",
"in",
"services",
"and",
"services",
"[",
"port",
"]",
"[",
"'port'",
"]",
":",
"return",
"services",
"[",
"port",
"]",
"[",
"'port'",
"]",... | Look into services and return the port value using the
service name as lookup value. | [
"Look",
"into",
"services",
"and",
"return",
"the",
"port",
"value",
"using",
"the",
"service",
"name",
"as",
"lookup",
"value",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L261-L269 | train |
saltstack/salt | salt/modules/capirca_acl.py | _make_it_list | def _make_it_list(dict_, field_name, value):
'''
Return the object list.
'''
prev_value = []
# firsly we'll collect the prev value
if field_name in dict_:
prev_value = dict_[field_name]
if value is None:
return prev_value
elif isinstance(value, (tuple, list)):
# other type of iterables
if field_name in ('source_port', 'destination_port'):
# port fields are more special
# they can either be a list of integers, either a list of tuples
# list of integers = a list of ports
# list of tuples = a list of ranges,
# e.g.: [(1000, 2000), (3000, 4000)] means the 1000-2000 and 3000-4000 ranges
portval = []
for port in value:
if not isinstance(port, (tuple, list)):
# to make sure everything is consistent,
# we'll transform indivitual ports into tuples
# thus an individual port e.g. 1000 will be transormed into the port range 1000-1000
# which is the equivalent
# but assures consistency for the Capirca parser
portval.append((port, port))
else:
portval.append(port)
translated_portval = []
# and the ports sent as string, e.g. ntp instead of 123
# needs to be translated
# again, using the same /etc/services
for port_start, port_end in portval:
if not isinstance(port_start, int):
port_start = _translate_port(port_start)
if not isinstance(port_end, int):
port_end = _translate_port(port_end)
translated_portval.append(
(port_start, port_end)
)
return list(set(prev_value + translated_portval))
return list(set(prev_value + list(value)))
if field_name in ('source_port', 'destination_port'):
if not isinstance(value, int):
value = _translate_port(value)
return list(set(prev_value + [(value, value)])) # a list of tuples
# anything else will be enclosed in a list-type
return list(set(prev_value + [value])) | python | def _make_it_list(dict_, field_name, value):
'''
Return the object list.
'''
prev_value = []
# firsly we'll collect the prev value
if field_name in dict_:
prev_value = dict_[field_name]
if value is None:
return prev_value
elif isinstance(value, (tuple, list)):
# other type of iterables
if field_name in ('source_port', 'destination_port'):
# port fields are more special
# they can either be a list of integers, either a list of tuples
# list of integers = a list of ports
# list of tuples = a list of ranges,
# e.g.: [(1000, 2000), (3000, 4000)] means the 1000-2000 and 3000-4000 ranges
portval = []
for port in value:
if not isinstance(port, (tuple, list)):
# to make sure everything is consistent,
# we'll transform indivitual ports into tuples
# thus an individual port e.g. 1000 will be transormed into the port range 1000-1000
# which is the equivalent
# but assures consistency for the Capirca parser
portval.append((port, port))
else:
portval.append(port)
translated_portval = []
# and the ports sent as string, e.g. ntp instead of 123
# needs to be translated
# again, using the same /etc/services
for port_start, port_end in portval:
if not isinstance(port_start, int):
port_start = _translate_port(port_start)
if not isinstance(port_end, int):
port_end = _translate_port(port_end)
translated_portval.append(
(port_start, port_end)
)
return list(set(prev_value + translated_portval))
return list(set(prev_value + list(value)))
if field_name in ('source_port', 'destination_port'):
if not isinstance(value, int):
value = _translate_port(value)
return list(set(prev_value + [(value, value)])) # a list of tuples
# anything else will be enclosed in a list-type
return list(set(prev_value + [value])) | [
"def",
"_make_it_list",
"(",
"dict_",
",",
"field_name",
",",
"value",
")",
":",
"prev_value",
"=",
"[",
"]",
"# firsly we'll collect the prev value",
"if",
"field_name",
"in",
"dict_",
":",
"prev_value",
"=",
"dict_",
"[",
"field_name",
"]",
"if",
"value",
"i... | Return the object list. | [
"Return",
"the",
"object",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L272-L320 | train |
saltstack/salt | salt/modules/capirca_acl.py | _clean_term_opts | def _clean_term_opts(term_opts):
'''
Cleanup the term opts:
- strip Null and empty valuee, defaulting their value to their base definition from _TERM_FIELDS
- convert to `nacaddr.IP` fields from `_IP_FILEDS`
- create lists for those fields requiring it
'''
clean_opts = {}
_services = _get_services_mapping()
for field, value in six.iteritems(term_opts):
# firstly we'll process special fields like source_service or destination_services
# which will inject values directly in the source or destination port and protocol
if field == 'source_service' and value:
if isinstance(value, six.string_types):
value = _make_it_list(clean_opts, field, value)
log.debug('Processing special source services:')
log.debug(value)
for service in value:
if service and service in _services:
# if valid source_service
# take the port and protocol values from the global and inject in the term config
clean_opts['source_port'] = _make_it_list(clean_opts,
'source_port',
_services[service]['port'])
clean_opts['protocol'] = _make_it_list(clean_opts,
'protocol',
_services[service]['protocol'])
log.debug('Built source_port field, after processing special source services:')
log.debug(clean_opts.get('source_port'))
log.debug('Built protocol field, after processing special source services:')
log.debug(clean_opts.get('protocol'))
elif field == 'destination_service' and value:
if isinstance(value, six.string_types):
value = _make_it_list(clean_opts, field, value)
log.debug('Processing special destination services:')
log.debug(value)
for service in value:
if service and service in _services:
# if valid destination_service
# take the port and protocol values from the global and inject in the term config
clean_opts['destination_port'] = _make_it_list(clean_opts,
'destination_port',
_services[service]['port'])
clean_opts['protocol'] = _make_it_list(clean_opts,
'protocol',
_services[service]['protocol'])
log.debug('Built source_port field, after processing special destination services:')
log.debug(clean_opts.get('destination_service'))
log.debug('Built protocol field, after processing special destination services:')
log.debug(clean_opts.get('protocol'))
# not a special field, but it has to be a valid one
elif field in _TERM_FIELDS and value and value != _TERM_FIELDS[field]:
# if not a special field type
if isinstance(_TERM_FIELDS[field], list):
value = _make_it_list(clean_opts, field, value)
if field in _IP_FILEDS:
# IP-type fields need to be transformed
ip_values = []
for addr in value:
if six.PY2:
addr = six.text_type(addr)
# Adding this, as ipaddress would complain about valid
# addresses not being valid. #pythonIsFun
ip_values.append(capirca.lib.policy.nacaddr.IP(addr))
value = ip_values[:]
clean_opts[field] = value
return clean_opts | python | def _clean_term_opts(term_opts):
'''
Cleanup the term opts:
- strip Null and empty valuee, defaulting their value to their base definition from _TERM_FIELDS
- convert to `nacaddr.IP` fields from `_IP_FILEDS`
- create lists for those fields requiring it
'''
clean_opts = {}
_services = _get_services_mapping()
for field, value in six.iteritems(term_opts):
# firstly we'll process special fields like source_service or destination_services
# which will inject values directly in the source or destination port and protocol
if field == 'source_service' and value:
if isinstance(value, six.string_types):
value = _make_it_list(clean_opts, field, value)
log.debug('Processing special source services:')
log.debug(value)
for service in value:
if service and service in _services:
# if valid source_service
# take the port and protocol values from the global and inject in the term config
clean_opts['source_port'] = _make_it_list(clean_opts,
'source_port',
_services[service]['port'])
clean_opts['protocol'] = _make_it_list(clean_opts,
'protocol',
_services[service]['protocol'])
log.debug('Built source_port field, after processing special source services:')
log.debug(clean_opts.get('source_port'))
log.debug('Built protocol field, after processing special source services:')
log.debug(clean_opts.get('protocol'))
elif field == 'destination_service' and value:
if isinstance(value, six.string_types):
value = _make_it_list(clean_opts, field, value)
log.debug('Processing special destination services:')
log.debug(value)
for service in value:
if service and service in _services:
# if valid destination_service
# take the port and protocol values from the global and inject in the term config
clean_opts['destination_port'] = _make_it_list(clean_opts,
'destination_port',
_services[service]['port'])
clean_opts['protocol'] = _make_it_list(clean_opts,
'protocol',
_services[service]['protocol'])
log.debug('Built source_port field, after processing special destination services:')
log.debug(clean_opts.get('destination_service'))
log.debug('Built protocol field, after processing special destination services:')
log.debug(clean_opts.get('protocol'))
# not a special field, but it has to be a valid one
elif field in _TERM_FIELDS and value and value != _TERM_FIELDS[field]:
# if not a special field type
if isinstance(_TERM_FIELDS[field], list):
value = _make_it_list(clean_opts, field, value)
if field in _IP_FILEDS:
# IP-type fields need to be transformed
ip_values = []
for addr in value:
if six.PY2:
addr = six.text_type(addr)
# Adding this, as ipaddress would complain about valid
# addresses not being valid. #pythonIsFun
ip_values.append(capirca.lib.policy.nacaddr.IP(addr))
value = ip_values[:]
clean_opts[field] = value
return clean_opts | [
"def",
"_clean_term_opts",
"(",
"term_opts",
")",
":",
"clean_opts",
"=",
"{",
"}",
"_services",
"=",
"_get_services_mapping",
"(",
")",
"for",
"field",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"term_opts",
")",
":",
"# firstly we'll process special fie... | Cleanup the term opts:
- strip Null and empty valuee, defaulting their value to their base definition from _TERM_FIELDS
- convert to `nacaddr.IP` fields from `_IP_FILEDS`
- create lists for those fields requiring it | [
"Cleanup",
"the",
"term",
"opts",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L323-L390 | train |
saltstack/salt | salt/modules/capirca_acl.py | _lookup_element | def _lookup_element(lst, key):
'''
Find an dictionary in a list of dictionaries, given its main key.
'''
if not lst:
return {}
for ele in lst:
if not ele or not isinstance(ele, dict):
continue
if ele.keys()[0] == key:
return ele.values()[0]
return {} | python | def _lookup_element(lst, key):
'''
Find an dictionary in a list of dictionaries, given its main key.
'''
if not lst:
return {}
for ele in lst:
if not ele or not isinstance(ele, dict):
continue
if ele.keys()[0] == key:
return ele.values()[0]
return {} | [
"def",
"_lookup_element",
"(",
"lst",
",",
"key",
")",
":",
"if",
"not",
"lst",
":",
"return",
"{",
"}",
"for",
"ele",
"in",
"lst",
":",
"if",
"not",
"ele",
"or",
"not",
"isinstance",
"(",
"ele",
",",
"dict",
")",
":",
"continue",
"if",
"ele",
".... | Find an dictionary in a list of dictionaries, given its main key. | [
"Find",
"an",
"dictionary",
"in",
"a",
"list",
"of",
"dictionaries",
"given",
"its",
"main",
"key",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L393-L404 | train |
saltstack/salt | salt/modules/capirca_acl.py | _get_pillar_cfg | def _get_pillar_cfg(pillar_key,
pillarenv=None,
saltenv=None):
'''
Retrieve the pillar data from the right environment.
'''
pillar_cfg = __salt__['pillar.get'](pillar_key,
pillarenv=pillarenv,
saltenv=saltenv)
return pillar_cfg | python | def _get_pillar_cfg(pillar_key,
pillarenv=None,
saltenv=None):
'''
Retrieve the pillar data from the right environment.
'''
pillar_cfg = __salt__['pillar.get'](pillar_key,
pillarenv=pillarenv,
saltenv=saltenv)
return pillar_cfg | [
"def",
"_get_pillar_cfg",
"(",
"pillar_key",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
")",
":",
"pillar_cfg",
"=",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"pillar_key",
",",
"pillarenv",
"=",
"pillarenv",
",",
"saltenv",
"=",
"saltenv",... | Retrieve the pillar data from the right environment. | [
"Retrieve",
"the",
"pillar",
"data",
"from",
"the",
"right",
"environment",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L407-L416 | train |
saltstack/salt | salt/modules/capirca_acl.py | _cleanup | def _cleanup(lst):
'''
Return a list of non-empty dictionaries.
'''
clean = []
for ele in lst:
if ele and isinstance(ele, dict):
clean.append(ele)
return clean | python | def _cleanup(lst):
'''
Return a list of non-empty dictionaries.
'''
clean = []
for ele in lst:
if ele and isinstance(ele, dict):
clean.append(ele)
return clean | [
"def",
"_cleanup",
"(",
"lst",
")",
":",
"clean",
"=",
"[",
"]",
"for",
"ele",
"in",
"lst",
":",
"if",
"ele",
"and",
"isinstance",
"(",
"ele",
",",
"dict",
")",
":",
"clean",
".",
"append",
"(",
"ele",
")",
"return",
"clean"
] | Return a list of non-empty dictionaries. | [
"Return",
"a",
"list",
"of",
"non",
"-",
"empty",
"dictionaries",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L419-L427 | train |
saltstack/salt | salt/modules/capirca_acl.py | _merge_list_of_dict | def _merge_list_of_dict(first, second, prepend=True):
'''
Merge lists of dictionaries.
Each element of the list is a dictionary having one single key.
That key is then used as unique lookup.
The first element list has higher priority than the second.
When there's an overlap between the two lists,
it won't change the position, but the content.
'''
first = _cleanup(first)
second = _cleanup(second)
if not first and not second:
return []
if not first and second:
return second
if first and not second:
return first
# Determine overlaps
# So we dont change the position of the existing terms/filters
overlaps = []
merged = []
appended = []
for ele in first:
if _lookup_element(second, ele.keys()[0]):
overlaps.append(ele)
elif prepend:
merged.append(ele)
elif not prepend:
appended.append(ele)
for ele in second:
ele_key = ele.keys()[0]
if _lookup_element(overlaps, ele_key):
# If theres an overlap, get the value from the first
# But inserted into the right position
ele_val_first = _lookup_element(first, ele_key)
merged.append({ele_key: ele_val_first})
else:
merged.append(ele)
if not prepend:
merged.extend(appended)
return merged | python | def _merge_list_of_dict(first, second, prepend=True):
'''
Merge lists of dictionaries.
Each element of the list is a dictionary having one single key.
That key is then used as unique lookup.
The first element list has higher priority than the second.
When there's an overlap between the two lists,
it won't change the position, but the content.
'''
first = _cleanup(first)
second = _cleanup(second)
if not first and not second:
return []
if not first and second:
return second
if first and not second:
return first
# Determine overlaps
# So we dont change the position of the existing terms/filters
overlaps = []
merged = []
appended = []
for ele in first:
if _lookup_element(second, ele.keys()[0]):
overlaps.append(ele)
elif prepend:
merged.append(ele)
elif not prepend:
appended.append(ele)
for ele in second:
ele_key = ele.keys()[0]
if _lookup_element(overlaps, ele_key):
# If theres an overlap, get the value from the first
# But inserted into the right position
ele_val_first = _lookup_element(first, ele_key)
merged.append({ele_key: ele_val_first})
else:
merged.append(ele)
if not prepend:
merged.extend(appended)
return merged | [
"def",
"_merge_list_of_dict",
"(",
"first",
",",
"second",
",",
"prepend",
"=",
"True",
")",
":",
"first",
"=",
"_cleanup",
"(",
"first",
")",
"second",
"=",
"_cleanup",
"(",
"second",
")",
"if",
"not",
"first",
"and",
"not",
"second",
":",
"return",
"... | Merge lists of dictionaries.
Each element of the list is a dictionary having one single key.
That key is then used as unique lookup.
The first element list has higher priority than the second.
When there's an overlap between the two lists,
it won't change the position, but the content. | [
"Merge",
"lists",
"of",
"dictionaries",
".",
"Each",
"element",
"of",
"the",
"list",
"is",
"a",
"dictionary",
"having",
"one",
"single",
"key",
".",
"That",
"key",
"is",
"then",
"used",
"as",
"unique",
"lookup",
".",
"The",
"first",
"element",
"list",
"h... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L430-L470 | train |
saltstack/salt | salt/modules/capirca_acl.py | _get_term_object | def _get_term_object(filter_name,
term_name,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
**term_fields):
'''
Return an instance of the ``_Term`` class given the term options.
'''
log.debug('Generating config for term %s under filter %s', term_name, filter_name)
term = _Term()
term.name = term_name
term_opts = {}
if merge_pillar:
term_opts = get_term_pillar(filter_name,
term_name,
pillar_key=pillar_key,
saltenv=saltenv,
pillarenv=pillarenv)
log.debug('Merging with pillar data:')
log.debug(term_opts)
term_opts = _clean_term_opts(term_opts)
log.debug('Cleaning up pillar data:')
log.debug(term_opts)
log.debug('Received processing opts:')
log.debug(term_fields)
log.debug('Cleaning up processing opts:')
term_fields = _clean_term_opts(term_fields)
log.debug(term_fields)
log.debug('Final term opts:')
term_opts.update(term_fields)
log.debug(term_fields)
for field, value in six.iteritems(term_opts):
# setting the field attributes to the term instance of _Term
setattr(term, field, value)
log.debug('Term config:')
log.debug(six.text_type(term))
return term | python | def _get_term_object(filter_name,
term_name,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
**term_fields):
'''
Return an instance of the ``_Term`` class given the term options.
'''
log.debug('Generating config for term %s under filter %s', term_name, filter_name)
term = _Term()
term.name = term_name
term_opts = {}
if merge_pillar:
term_opts = get_term_pillar(filter_name,
term_name,
pillar_key=pillar_key,
saltenv=saltenv,
pillarenv=pillarenv)
log.debug('Merging with pillar data:')
log.debug(term_opts)
term_opts = _clean_term_opts(term_opts)
log.debug('Cleaning up pillar data:')
log.debug(term_opts)
log.debug('Received processing opts:')
log.debug(term_fields)
log.debug('Cleaning up processing opts:')
term_fields = _clean_term_opts(term_fields)
log.debug(term_fields)
log.debug('Final term opts:')
term_opts.update(term_fields)
log.debug(term_fields)
for field, value in six.iteritems(term_opts):
# setting the field attributes to the term instance of _Term
setattr(term, field, value)
log.debug('Term config:')
log.debug(six.text_type(term))
return term | [
"def",
"_get_term_object",
"(",
"filter_name",
",",
"term_name",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
",",
"merge_pillar",
"=",
"True",
",",
"*",
"*",
"term_fields",
")",
":",
"log",
".",
"debug",
"... | Return an instance of the ``_Term`` class given the term options. | [
"Return",
"an",
"instance",
"of",
"the",
"_Term",
"class",
"given",
"the",
"term",
"options",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L473-L511 | train |
saltstack/salt | salt/modules/capirca_acl.py | _get_policy_object | def _get_policy_object(platform,
filters=None,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True):
'''
Return an instance of the ``_Policy`` class given the filters config.
'''
policy = _Policy()
policy_filters = []
if not filters:
filters = []
for filter_ in filters:
if not filter_ or not isinstance(filter_, dict):
continue # go to the next filter
filter_name = filter_.keys()[0]
filter_config = filter_.values()[0]
header = capirca.lib.policy.Header() # same header everywhere
target_opts = [
platform,
filter_name
]
filter_options = filter_config.pop('options', None)
if filter_options:
filter_options = _make_it_list({}, filter_name, filter_options)
# make sure the filter options are sent as list
target_opts.extend(filter_options)
target = capirca.lib.policy.Target(target_opts)
header.AddObject(target)
filter_terms = []
for term_ in filter_config.get('terms', []):
if term_ and isinstance(term_, dict):
term_name = term_.keys()[0]
term_fields = term_.values()[0]
term = _get_term_object(filter_name,
term_name,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar,
**term_fields)
filter_terms.append(term)
policy_filters.append(
(header, filter_terms)
)
policy.filters = policy_filters
log.debug('Policy config:')
log.debug(six.text_type(policy))
platform_generator = _import_platform_generator(platform)
policy_config = platform_generator(policy, 2)
log.debug('Generating policy config for %s:', platform)
log.debug(six.text_type(policy_config))
return policy_config | python | def _get_policy_object(platform,
filters=None,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True):
'''
Return an instance of the ``_Policy`` class given the filters config.
'''
policy = _Policy()
policy_filters = []
if not filters:
filters = []
for filter_ in filters:
if not filter_ or not isinstance(filter_, dict):
continue # go to the next filter
filter_name = filter_.keys()[0]
filter_config = filter_.values()[0]
header = capirca.lib.policy.Header() # same header everywhere
target_opts = [
platform,
filter_name
]
filter_options = filter_config.pop('options', None)
if filter_options:
filter_options = _make_it_list({}, filter_name, filter_options)
# make sure the filter options are sent as list
target_opts.extend(filter_options)
target = capirca.lib.policy.Target(target_opts)
header.AddObject(target)
filter_terms = []
for term_ in filter_config.get('terms', []):
if term_ and isinstance(term_, dict):
term_name = term_.keys()[0]
term_fields = term_.values()[0]
term = _get_term_object(filter_name,
term_name,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar,
**term_fields)
filter_terms.append(term)
policy_filters.append(
(header, filter_terms)
)
policy.filters = policy_filters
log.debug('Policy config:')
log.debug(six.text_type(policy))
platform_generator = _import_platform_generator(platform)
policy_config = platform_generator(policy, 2)
log.debug('Generating policy config for %s:', platform)
log.debug(six.text_type(policy_config))
return policy_config | [
"def",
"_get_policy_object",
"(",
"platform",
",",
"filters",
"=",
"None",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
",",
"merge_pillar",
"=",
"True",
")",
":",
"policy",
"=",
"_Policy",
"(",
")",
"polic... | Return an instance of the ``_Policy`` class given the filters config. | [
"Return",
"an",
"instance",
"of",
"the",
"_Policy",
"class",
"given",
"the",
"filters",
"config",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L514-L567 | train |
saltstack/salt | salt/modules/capirca_acl.py | _revision_tag | def _revision_tag(text,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d'):
'''
Refactor revision tag comments.
Capirca generates the filter text having the following tag keys:
- $Id:$
- $Revision:$
- $Date:$
This function goes through all the config lines and replaces
those tags with the content requested by the user.
If a certain value is not provided, the corresponding tag will be stripped.
'''
timestamp = datetime.datetime.now().strftime(revision_date_format)
new_text = []
for line in text.splitlines():
if '$Id:$' in line:
if not revision_id: # if no explicit revision ID required
continue # jump to next line, ignore this one
line = line.replace('$Id:$', '$Id: {rev_id} $'.format(rev_id=revision_id))
if '$Revision:$' in line:
if not revision_no: # if no explicit revision number required
continue # jump to next line, ignore this one
line = line.replace('$Revision:$', '$Revision: {rev_no} $'.format(rev_no=revision_no))
if '$Date:$' in line:
if not revision_date:
continue # jump
line = line.replace('$Date:$', '$Date: {ts} $'.format(ts=timestamp))
new_text.append(line)
return '\n'.join(new_text) | python | def _revision_tag(text,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d'):
'''
Refactor revision tag comments.
Capirca generates the filter text having the following tag keys:
- $Id:$
- $Revision:$
- $Date:$
This function goes through all the config lines and replaces
those tags with the content requested by the user.
If a certain value is not provided, the corresponding tag will be stripped.
'''
timestamp = datetime.datetime.now().strftime(revision_date_format)
new_text = []
for line in text.splitlines():
if '$Id:$' in line:
if not revision_id: # if no explicit revision ID required
continue # jump to next line, ignore this one
line = line.replace('$Id:$', '$Id: {rev_id} $'.format(rev_id=revision_id))
if '$Revision:$' in line:
if not revision_no: # if no explicit revision number required
continue # jump to next line, ignore this one
line = line.replace('$Revision:$', '$Revision: {rev_no} $'.format(rev_no=revision_no))
if '$Date:$' in line:
if not revision_date:
continue # jump
line = line.replace('$Date:$', '$Date: {ts} $'.format(ts=timestamp))
new_text.append(line)
return '\n'.join(new_text) | [
"def",
"_revision_tag",
"(",
"text",
",",
"revision_id",
"=",
"None",
",",
"revision_no",
"=",
"None",
",",
"revision_date",
"=",
"True",
",",
"revision_date_format",
"=",
"'%Y/%m/%d'",
")",
":",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"now",
"("... | Refactor revision tag comments.
Capirca generates the filter text having the following tag keys:
- $Id:$
- $Revision:$
- $Date:$
This function goes through all the config lines and replaces
those tags with the content requested by the user.
If a certain value is not provided, the corresponding tag will be stripped. | [
"Refactor",
"revision",
"tag",
"comments",
".",
"Capirca",
"generates",
"the",
"filter",
"text",
"having",
"the",
"following",
"tag",
"keys",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L570-L603 | train |
saltstack/salt | salt/modules/capirca_acl.py | get_term_config | def get_term_config(platform,
filter_name,
term_name,
filter_options=None,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d',
source_service=None,
destination_service=None,
**term_fields):
'''
Return the configuration of a single policy term.
platform
The name of the Capirca platform.
filter_name
The name of the policy filter.
term_name
The name of the term.
filter_options
Additional filter options. These options are platform-specific.
E.g.: ``inet6``, ``bridge``, ``object-group``,
See the complete list of options_.
.. _options: https://github.com/google/capirca/wiki/Policy-format#header-section
pillar_key: ``acl``
The key in the pillar containing the default attributes values. Default: ``acl``.
If the pillar contains the following structure:
.. code-block:: yaml
firewall:
- my-filter:
terms:
- my-term:
source_port: 1234
source_address:
- 1.2.3.4/32
- 5.6.7.8/32
The ``pillar_key`` field would be specified as ``firewall``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
merge_pillar: ``True``
Merge the CLI variables with the pillar. Default: ``True``.
revision_id
Add a comment in the term config having the description for the changes applied.
revision_no
The revision count.
revision_date: ``True``
Boolean flag: display the date when the term configuration was generated. Default: ``True``.
revision_date_format: ``%Y/%m/%d``
The date format to be used when generating the perforce data. Default: ``%Y/%m/%d`` (<year>/<month>/<day>).
source_service
A special service to choose from. This is a helper so the user is able to
select a source just using the name, instead of specifying a source_port and protocol.
As this module is available on Unix platforms only,
it reads the IANA_ port assignment from ``/etc/services``.
If the user requires additional shortcuts to be referenced, they can add entries under ``/etc/services``,
which can be managed using the :mod:`file state <salt.states.file>`.
.. _IANA: http://www.iana.org/assignments/port-numbers
destination_service
A special service to choose from. This is a helper so the user is able to
select a source just using the name, instead of specifying a destination_port and protocol.
Allows the same options as ``source_service``.
term_fields
Term attributes.
To see what fields are supported, please consult the list of supported keywords_.
Some platforms have few other optional_ keywords.
.. _keywords: https://github.com/google/capirca/wiki/Policy-format#keywords
.. _optional: https://github.com/google/capirca/wiki/Policy-format#optionally-supported-keywords
.. note::
The following fields are accepted:
- action
- address
- address_exclude
- comment
- counter
- expiration
- destination_address
- destination_address_exclude
- destination_port
- destination_prefix
- forwarding_class
- forwarding_class_except
- logging
- log_name
- loss_priority
- option
- policer
- port
- precedence
- principals
- protocol
- protocol_except
- qos
- pan_application
- routing_instance
- source_address
- source_address_exclude
- source_port
- source_prefix
- verbatim
- packet_length
- fragment_offset
- hop_limit
- icmp_type
- ether_type
- traffic_class_count
- traffic_type
- translated
- dscp_set
- dscp_match
- dscp_except
- next_ip
- flexible_match_range
- source_prefix_except
- destination_prefix_except
- vpn
- source_tag
- destination_tag
- source_interface
- destination_interface
- flattened
- flattened_addr
- flattened_saddr
- flattened_daddr
- priority
.. note::
The following fields can be also a single value and a list of values:
- action
- address
- address_exclude
- comment
- destination_address
- destination_address_exclude
- destination_port
- destination_prefix
- forwarding_class
- forwarding_class_except
- logging
- option
- port
- precedence
- principals
- protocol
- protocol_except
- pan_application
- source_address
- source_address_exclude
- source_port
- source_prefix
- verbatim
- icmp_type
- ether_type
- traffic_type
- dscp_match
- dscp_except
- flexible_match_range
- source_prefix_except
- destination_prefix_except
- source_tag
- destination_tag
- source_service
- destination_service
Example: ``destination_address`` can be either defined as:
.. code-block:: yaml
destination_address: 172.17.17.1/24
or as a list of destination IP addresses:
.. code-block:: yaml
destination_address:
- 172.17.17.1/24
- 172.17.19.1/24
or a list of services to be matched:
.. code-block:: yaml
source_service:
- ntp
- snmp
- ldap
- bgpd
.. note::
The port fields ``source_port`` and ``destination_port`` can be used as above to select either
a single value, either a list of values, but also they can select port ranges. Example:
.. code-block:: yaml
source_port:
- [1000, 2000]
- [3000, 4000]
With the configuration above, the user is able to select the 1000-2000 and 3000-4000 source port ranges.
CLI Example:
.. code-block:: bash
salt '*' capirca.get_term_config arista filter-name term-name source_address=1.2.3.4 destination_address=5.6.7.8 action=accept
Output Example:
.. code-block:: text
! $Date: 2017/03/22 $
no ip access-list filter-name
ip access-list filter-name
remark term-name
permit ip host 1.2.3.4 host 5.6.7.8
exit
'''
terms = []
term = {
term_name: {
}
}
term[term_name].update(term_fields)
term[term_name].update({
'source_service': _make_it_list({}, 'source_service', source_service),
'destination_service': _make_it_list({}, 'destination_service', destination_service),
})
terms.append(term)
if not filter_options:
filter_options = []
return get_filter_config(platform,
filter_name,
filter_options=filter_options,
terms=terms,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar,
only_lower_merge=True,
revision_id=revision_id,
revision_no=revision_no,
revision_date=revision_date,
revision_date_format=revision_date_format) | python | def get_term_config(platform,
filter_name,
term_name,
filter_options=None,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d',
source_service=None,
destination_service=None,
**term_fields):
'''
Return the configuration of a single policy term.
platform
The name of the Capirca platform.
filter_name
The name of the policy filter.
term_name
The name of the term.
filter_options
Additional filter options. These options are platform-specific.
E.g.: ``inet6``, ``bridge``, ``object-group``,
See the complete list of options_.
.. _options: https://github.com/google/capirca/wiki/Policy-format#header-section
pillar_key: ``acl``
The key in the pillar containing the default attributes values. Default: ``acl``.
If the pillar contains the following structure:
.. code-block:: yaml
firewall:
- my-filter:
terms:
- my-term:
source_port: 1234
source_address:
- 1.2.3.4/32
- 5.6.7.8/32
The ``pillar_key`` field would be specified as ``firewall``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
merge_pillar: ``True``
Merge the CLI variables with the pillar. Default: ``True``.
revision_id
Add a comment in the term config having the description for the changes applied.
revision_no
The revision count.
revision_date: ``True``
Boolean flag: display the date when the term configuration was generated. Default: ``True``.
revision_date_format: ``%Y/%m/%d``
The date format to be used when generating the perforce data. Default: ``%Y/%m/%d`` (<year>/<month>/<day>).
source_service
A special service to choose from. This is a helper so the user is able to
select a source just using the name, instead of specifying a source_port and protocol.
As this module is available on Unix platforms only,
it reads the IANA_ port assignment from ``/etc/services``.
If the user requires additional shortcuts to be referenced, they can add entries under ``/etc/services``,
which can be managed using the :mod:`file state <salt.states.file>`.
.. _IANA: http://www.iana.org/assignments/port-numbers
destination_service
A special service to choose from. This is a helper so the user is able to
select a source just using the name, instead of specifying a destination_port and protocol.
Allows the same options as ``source_service``.
term_fields
Term attributes.
To see what fields are supported, please consult the list of supported keywords_.
Some platforms have few other optional_ keywords.
.. _keywords: https://github.com/google/capirca/wiki/Policy-format#keywords
.. _optional: https://github.com/google/capirca/wiki/Policy-format#optionally-supported-keywords
.. note::
The following fields are accepted:
- action
- address
- address_exclude
- comment
- counter
- expiration
- destination_address
- destination_address_exclude
- destination_port
- destination_prefix
- forwarding_class
- forwarding_class_except
- logging
- log_name
- loss_priority
- option
- policer
- port
- precedence
- principals
- protocol
- protocol_except
- qos
- pan_application
- routing_instance
- source_address
- source_address_exclude
- source_port
- source_prefix
- verbatim
- packet_length
- fragment_offset
- hop_limit
- icmp_type
- ether_type
- traffic_class_count
- traffic_type
- translated
- dscp_set
- dscp_match
- dscp_except
- next_ip
- flexible_match_range
- source_prefix_except
- destination_prefix_except
- vpn
- source_tag
- destination_tag
- source_interface
- destination_interface
- flattened
- flattened_addr
- flattened_saddr
- flattened_daddr
- priority
.. note::
The following fields can be also a single value and a list of values:
- action
- address
- address_exclude
- comment
- destination_address
- destination_address_exclude
- destination_port
- destination_prefix
- forwarding_class
- forwarding_class_except
- logging
- option
- port
- precedence
- principals
- protocol
- protocol_except
- pan_application
- source_address
- source_address_exclude
- source_port
- source_prefix
- verbatim
- icmp_type
- ether_type
- traffic_type
- dscp_match
- dscp_except
- flexible_match_range
- source_prefix_except
- destination_prefix_except
- source_tag
- destination_tag
- source_service
- destination_service
Example: ``destination_address`` can be either defined as:
.. code-block:: yaml
destination_address: 172.17.17.1/24
or as a list of destination IP addresses:
.. code-block:: yaml
destination_address:
- 172.17.17.1/24
- 172.17.19.1/24
or a list of services to be matched:
.. code-block:: yaml
source_service:
- ntp
- snmp
- ldap
- bgpd
.. note::
The port fields ``source_port`` and ``destination_port`` can be used as above to select either
a single value, either a list of values, but also they can select port ranges. Example:
.. code-block:: yaml
source_port:
- [1000, 2000]
- [3000, 4000]
With the configuration above, the user is able to select the 1000-2000 and 3000-4000 source port ranges.
CLI Example:
.. code-block:: bash
salt '*' capirca.get_term_config arista filter-name term-name source_address=1.2.3.4 destination_address=5.6.7.8 action=accept
Output Example:
.. code-block:: text
! $Date: 2017/03/22 $
no ip access-list filter-name
ip access-list filter-name
remark term-name
permit ip host 1.2.3.4 host 5.6.7.8
exit
'''
terms = []
term = {
term_name: {
}
}
term[term_name].update(term_fields)
term[term_name].update({
'source_service': _make_it_list({}, 'source_service', source_service),
'destination_service': _make_it_list({}, 'destination_service', destination_service),
})
terms.append(term)
if not filter_options:
filter_options = []
return get_filter_config(platform,
filter_name,
filter_options=filter_options,
terms=terms,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar,
only_lower_merge=True,
revision_id=revision_id,
revision_no=revision_no,
revision_date=revision_date,
revision_date_format=revision_date_format) | [
"def",
"get_term_config",
"(",
"platform",
",",
"filter_name",
",",
"term_name",
",",
"filter_options",
"=",
"None",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
",",
"merge_pillar",
"=",
"True",
",",
"revision... | Return the configuration of a single policy term.
platform
The name of the Capirca platform.
filter_name
The name of the policy filter.
term_name
The name of the term.
filter_options
Additional filter options. These options are platform-specific.
E.g.: ``inet6``, ``bridge``, ``object-group``,
See the complete list of options_.
.. _options: https://github.com/google/capirca/wiki/Policy-format#header-section
pillar_key: ``acl``
The key in the pillar containing the default attributes values. Default: ``acl``.
If the pillar contains the following structure:
.. code-block:: yaml
firewall:
- my-filter:
terms:
- my-term:
source_port: 1234
source_address:
- 1.2.3.4/32
- 5.6.7.8/32
The ``pillar_key`` field would be specified as ``firewall``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
merge_pillar: ``True``
Merge the CLI variables with the pillar. Default: ``True``.
revision_id
Add a comment in the term config having the description for the changes applied.
revision_no
The revision count.
revision_date: ``True``
Boolean flag: display the date when the term configuration was generated. Default: ``True``.
revision_date_format: ``%Y/%m/%d``
The date format to be used when generating the perforce data. Default: ``%Y/%m/%d`` (<year>/<month>/<day>).
source_service
A special service to choose from. This is a helper so the user is able to
select a source just using the name, instead of specifying a source_port and protocol.
As this module is available on Unix platforms only,
it reads the IANA_ port assignment from ``/etc/services``.
If the user requires additional shortcuts to be referenced, they can add entries under ``/etc/services``,
which can be managed using the :mod:`file state <salt.states.file>`.
.. _IANA: http://www.iana.org/assignments/port-numbers
destination_service
A special service to choose from. This is a helper so the user is able to
select a source just using the name, instead of specifying a destination_port and protocol.
Allows the same options as ``source_service``.
term_fields
Term attributes.
To see what fields are supported, please consult the list of supported keywords_.
Some platforms have few other optional_ keywords.
.. _keywords: https://github.com/google/capirca/wiki/Policy-format#keywords
.. _optional: https://github.com/google/capirca/wiki/Policy-format#optionally-supported-keywords
.. note::
The following fields are accepted:
- action
- address
- address_exclude
- comment
- counter
- expiration
- destination_address
- destination_address_exclude
- destination_port
- destination_prefix
- forwarding_class
- forwarding_class_except
- logging
- log_name
- loss_priority
- option
- policer
- port
- precedence
- principals
- protocol
- protocol_except
- qos
- pan_application
- routing_instance
- source_address
- source_address_exclude
- source_port
- source_prefix
- verbatim
- packet_length
- fragment_offset
- hop_limit
- icmp_type
- ether_type
- traffic_class_count
- traffic_type
- translated
- dscp_set
- dscp_match
- dscp_except
- next_ip
- flexible_match_range
- source_prefix_except
- destination_prefix_except
- vpn
- source_tag
- destination_tag
- source_interface
- destination_interface
- flattened
- flattened_addr
- flattened_saddr
- flattened_daddr
- priority
.. note::
The following fields can be also a single value and a list of values:
- action
- address
- address_exclude
- comment
- destination_address
- destination_address_exclude
- destination_port
- destination_prefix
- forwarding_class
- forwarding_class_except
- logging
- option
- port
- precedence
- principals
- protocol
- protocol_except
- pan_application
- source_address
- source_address_exclude
- source_port
- source_prefix
- verbatim
- icmp_type
- ether_type
- traffic_type
- dscp_match
- dscp_except
- flexible_match_range
- source_prefix_except
- destination_prefix_except
- source_tag
- destination_tag
- source_service
- destination_service
Example: ``destination_address`` can be either defined as:
.. code-block:: yaml
destination_address: 172.17.17.1/24
or as a list of destination IP addresses:
.. code-block:: yaml
destination_address:
- 172.17.17.1/24
- 172.17.19.1/24
or a list of services to be matched:
.. code-block:: yaml
source_service:
- ntp
- snmp
- ldap
- bgpd
.. note::
The port fields ``source_port`` and ``destination_port`` can be used as above to select either
a single value, either a list of values, but also they can select port ranges. Example:
.. code-block:: yaml
source_port:
- [1000, 2000]
- [3000, 4000]
With the configuration above, the user is able to select the 1000-2000 and 3000-4000 source port ranges.
CLI Example:
.. code-block:: bash
salt '*' capirca.get_term_config arista filter-name term-name source_address=1.2.3.4 destination_address=5.6.7.8 action=accept
Output Example:
.. code-block:: text
! $Date: 2017/03/22 $
no ip access-list filter-name
ip access-list filter-name
remark term-name
permit ip host 1.2.3.4 host 5.6.7.8
exit | [
"Return",
"the",
"configuration",
"of",
"a",
"single",
"policy",
"term",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L610-L885 | train |
saltstack/salt | salt/modules/capirca_acl.py | get_filter_config | def get_filter_config(platform,
filter_name,
filter_options=None,
terms=None,
prepend=True,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
only_lower_merge=False,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d'):
'''
Return the configuration of a policy filter.
platform
The name of the Capirca platform.
filter_name
The name of the policy filter.
filter_options
Additional filter options. These options are platform-specific.
See the complete list of options_.
.. _options: https://github.com/google/capirca/wiki/Policy-format#header-section
terms
List of terms for this policy filter.
If not specified or empty, will try to load the configuration from the pillar,
unless ``merge_pillar`` is set as ``False``.
prepend: ``True``
When ``merge_pillar`` is set as ``True``, the final list of terms generated by merging
the terms from ``terms`` with those defined in the pillar (if any): new terms are prepended
at the beginning, while existing ones will preserve the position. To add the new terms
at the end of the list, set this argument to ``False``.
pillar_key: ``acl``
The key in the pillar containing the default attributes values. Default: ``acl``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
merge_pillar: ``True``
Merge the CLI variables with the pillar. Default: ``True``.
only_lower_merge: ``False``
Specify if it should merge only the terms fields. Otherwise it will try
to merge also filters fields. Default: ``False``.
revision_id
Add a comment in the filter config having the description for the changes applied.
revision_no
The revision count.
revision_date: ``True``
Boolean flag: display the date when the filter configuration was generated. Default: ``True``.
revision_date_format: ``%Y/%m/%d``
The date format to be used when generating the perforce data. Default: ``%Y/%m/%d`` (<year>/<month>/<day>).
CLI Example:
.. code-block:: bash
salt '*' capirca.get_filter_config ciscoxr my-filter pillar_key=netacl
Output Example:
.. code-block:: text
! $Id:$
! $Date:$
! $Revision:$
no ipv4 access-list my-filter
ipv4 access-list my-filter
remark $Id:$
remark my-term
deny ipv4 any eq 1234 any
deny ipv4 any eq 1235 any
remark my-other-term
permit tcp any range 5678 5680 any
exit
The filter configuration has been loaded from the pillar, having the following structure:
.. code-block:: yaml
netacl:
- my-filter:
terms:
- my-term:
source_port: [1234, 1235]
action: reject
- my-other-term:
source_port:
- [5678, 5680]
protocol: tcp
action: accept
'''
if not filter_options:
filter_options = []
if not terms:
terms = []
if merge_pillar and not only_lower_merge:
acl_pillar_cfg = _get_pillar_cfg(pillar_key,
saltenv=saltenv,
pillarenv=pillarenv)
filter_pillar_cfg = _lookup_element(acl_pillar_cfg, filter_name)
filter_options = filter_options or filter_pillar_cfg.pop('options', None)
if filter_pillar_cfg:
# Only when it was able to find the filter in the ACL config
pillar_terms = filter_pillar_cfg.get('terms', []) # No problem if empty in the pillar
terms = _merge_list_of_dict(terms, pillar_terms, prepend=prepend)
# merge the passed variable with the pillar data
# any filter term not defined here, will be appended from the pillar
# new terms won't be removed
filters = []
filters.append({
filter_name: {
'options': _make_it_list({}, filter_name, filter_options),
'terms': terms
}
})
return get_policy_config(platform,
filters=filters,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar,
only_lower_merge=True,
revision_id=revision_id,
revision_no=revision_no,
revision_date=revision_date,
revision_date_format=revision_date_format) | python | def get_filter_config(platform,
filter_name,
filter_options=None,
terms=None,
prepend=True,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
only_lower_merge=False,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d'):
'''
Return the configuration of a policy filter.
platform
The name of the Capirca platform.
filter_name
The name of the policy filter.
filter_options
Additional filter options. These options are platform-specific.
See the complete list of options_.
.. _options: https://github.com/google/capirca/wiki/Policy-format#header-section
terms
List of terms for this policy filter.
If not specified or empty, will try to load the configuration from the pillar,
unless ``merge_pillar`` is set as ``False``.
prepend: ``True``
When ``merge_pillar`` is set as ``True``, the final list of terms generated by merging
the terms from ``terms`` with those defined in the pillar (if any): new terms are prepended
at the beginning, while existing ones will preserve the position. To add the new terms
at the end of the list, set this argument to ``False``.
pillar_key: ``acl``
The key in the pillar containing the default attributes values. Default: ``acl``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
merge_pillar: ``True``
Merge the CLI variables with the pillar. Default: ``True``.
only_lower_merge: ``False``
Specify if it should merge only the terms fields. Otherwise it will try
to merge also filters fields. Default: ``False``.
revision_id
Add a comment in the filter config having the description for the changes applied.
revision_no
The revision count.
revision_date: ``True``
Boolean flag: display the date when the filter configuration was generated. Default: ``True``.
revision_date_format: ``%Y/%m/%d``
The date format to be used when generating the perforce data. Default: ``%Y/%m/%d`` (<year>/<month>/<day>).
CLI Example:
.. code-block:: bash
salt '*' capirca.get_filter_config ciscoxr my-filter pillar_key=netacl
Output Example:
.. code-block:: text
! $Id:$
! $Date:$
! $Revision:$
no ipv4 access-list my-filter
ipv4 access-list my-filter
remark $Id:$
remark my-term
deny ipv4 any eq 1234 any
deny ipv4 any eq 1235 any
remark my-other-term
permit tcp any range 5678 5680 any
exit
The filter configuration has been loaded from the pillar, having the following structure:
.. code-block:: yaml
netacl:
- my-filter:
terms:
- my-term:
source_port: [1234, 1235]
action: reject
- my-other-term:
source_port:
- [5678, 5680]
protocol: tcp
action: accept
'''
if not filter_options:
filter_options = []
if not terms:
terms = []
if merge_pillar and not only_lower_merge:
acl_pillar_cfg = _get_pillar_cfg(pillar_key,
saltenv=saltenv,
pillarenv=pillarenv)
filter_pillar_cfg = _lookup_element(acl_pillar_cfg, filter_name)
filter_options = filter_options or filter_pillar_cfg.pop('options', None)
if filter_pillar_cfg:
# Only when it was able to find the filter in the ACL config
pillar_terms = filter_pillar_cfg.get('terms', []) # No problem if empty in the pillar
terms = _merge_list_of_dict(terms, pillar_terms, prepend=prepend)
# merge the passed variable with the pillar data
# any filter term not defined here, will be appended from the pillar
# new terms won't be removed
filters = []
filters.append({
filter_name: {
'options': _make_it_list({}, filter_name, filter_options),
'terms': terms
}
})
return get_policy_config(platform,
filters=filters,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar,
only_lower_merge=True,
revision_id=revision_id,
revision_no=revision_no,
revision_date=revision_date,
revision_date_format=revision_date_format) | [
"def",
"get_filter_config",
"(",
"platform",
",",
"filter_name",
",",
"filter_options",
"=",
"None",
",",
"terms",
"=",
"None",
",",
"prepend",
"=",
"True",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
",",
... | Return the configuration of a policy filter.
platform
The name of the Capirca platform.
filter_name
The name of the policy filter.
filter_options
Additional filter options. These options are platform-specific.
See the complete list of options_.
.. _options: https://github.com/google/capirca/wiki/Policy-format#header-section
terms
List of terms for this policy filter.
If not specified or empty, will try to load the configuration from the pillar,
unless ``merge_pillar`` is set as ``False``.
prepend: ``True``
When ``merge_pillar`` is set as ``True``, the final list of terms generated by merging
the terms from ``terms`` with those defined in the pillar (if any): new terms are prepended
at the beginning, while existing ones will preserve the position. To add the new terms
at the end of the list, set this argument to ``False``.
pillar_key: ``acl``
The key in the pillar containing the default attributes values. Default: ``acl``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
merge_pillar: ``True``
Merge the CLI variables with the pillar. Default: ``True``.
only_lower_merge: ``False``
Specify if it should merge only the terms fields. Otherwise it will try
to merge also filters fields. Default: ``False``.
revision_id
Add a comment in the filter config having the description for the changes applied.
revision_no
The revision count.
revision_date: ``True``
Boolean flag: display the date when the filter configuration was generated. Default: ``True``.
revision_date_format: ``%Y/%m/%d``
The date format to be used when generating the perforce data. Default: ``%Y/%m/%d`` (<year>/<month>/<day>).
CLI Example:
.. code-block:: bash
salt '*' capirca.get_filter_config ciscoxr my-filter pillar_key=netacl
Output Example:
.. code-block:: text
! $Id:$
! $Date:$
! $Revision:$
no ipv4 access-list my-filter
ipv4 access-list my-filter
remark $Id:$
remark my-term
deny ipv4 any eq 1234 any
deny ipv4 any eq 1235 any
remark my-other-term
permit tcp any range 5678 5680 any
exit
The filter configuration has been loaded from the pillar, having the following structure:
.. code-block:: yaml
netacl:
- my-filter:
terms:
- my-term:
source_port: [1234, 1235]
action: reject
- my-other-term:
source_port:
- [5678, 5680]
protocol: tcp
action: accept | [
"Return",
"the",
"configuration",
"of",
"a",
"policy",
"filter",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L888-L1031 | train |
saltstack/salt | salt/modules/capirca_acl.py | get_policy_config | def get_policy_config(platform,
filters=None,
prepend=True,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
only_lower_merge=False,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d'):
'''
Return the configuration of the whole policy.
platform
The name of the Capirca platform.
filters
List of filters for this policy.
If not specified or empty, will try to load the configuration from the pillar,
unless ``merge_pillar`` is set as ``False``.
prepend: ``True``
When ``merge_pillar`` is set as ``True``, the final list of filters generated by merging
the filters from ``filters`` with those defined in the pillar (if any): new filters are prepended
at the beginning, while existing ones will preserve the position. To add the new filters
at the end of the list, set this argument to ``False``.
pillar_key: ``acl``
The key in the pillar containing the default attributes values. Default: ``acl``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
merge_pillar: ``True``
Merge the CLI variables with the pillar. Default: ``True``.
only_lower_merge: ``False``
Specify if it should merge only the filters and terms fields. Otherwise it will try
to merge everything at the policy level. Default: ``False``.
revision_id
Add a comment in the policy config having the description for the changes applied.
revision_no
The revision count.
revision_date: ``True``
Boolean flag: display the date when the policy configuration was generated. Default: ``True``.
revision_date_format: ``%Y/%m/%d``
The date format to be used when generating the perforce data. Default: ``%Y/%m/%d`` (<year>/<month>/<day>).
CLI Example:
.. code-block:: bash
salt '*' capirca.get_policy_config juniper pillar_key=netacl
Output Example:
.. code-block:: text
firewall {
family inet {
replace:
/*
** $Id:$
** $Date:$
** $Revision:$
**
*/
filter my-filter {
term my-term {
from {
source-port [ 1234 1235 ];
}
then {
reject;
}
}
term my-other-term {
from {
protocol tcp;
source-port 5678-5680;
}
then accept;
}
}
}
}
firewall {
family inet {
replace:
/*
** $Id:$
** $Date:$
** $Revision:$
**
*/
filter my-other-filter {
interface-specific;
term dummy-term {
from {
protocol [ tcp udp ];
}
then {
reject;
}
}
}
}
}
The policy configuration has been loaded from the pillar, having the following structure:
.. code-block:: yaml
netacl:
- my-filter:
options:
- not-interface-specific
terms:
- my-term:
source_port: [1234, 1235]
action: reject
- my-other-term:
source_port:
- [5678, 5680]
protocol: tcp
action: accept
- my-other-filter:
terms:
- dummy-term:
protocol:
- tcp
- udp
action: reject
'''
if not filters:
filters = []
if merge_pillar and not only_lower_merge:
# the pillar key for the policy config is the `pillar_key` itself
policy_pillar_cfg = _get_pillar_cfg(pillar_key,
saltenv=saltenv,
pillarenv=pillarenv)
# now, let's merge everything witht the pillar data
# again, this will not remove any extra filters/terms
# but it will merge with the pillar data
# if this behaviour is not wanted, the user can set `merge_pillar` as `False`
filters = _merge_list_of_dict(filters, policy_pillar_cfg, prepend=prepend)
policy_object = _get_policy_object(platform,
filters=filters,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar)
policy_text = six.text_type(policy_object)
return _revision_tag(policy_text,
revision_id=revision_id,
revision_no=revision_no,
revision_date=revision_date,
revision_date_format=revision_date_format) | python | def get_policy_config(platform,
filters=None,
prepend=True,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
only_lower_merge=False,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d'):
'''
Return the configuration of the whole policy.
platform
The name of the Capirca platform.
filters
List of filters for this policy.
If not specified or empty, will try to load the configuration from the pillar,
unless ``merge_pillar`` is set as ``False``.
prepend: ``True``
When ``merge_pillar`` is set as ``True``, the final list of filters generated by merging
the filters from ``filters`` with those defined in the pillar (if any): new filters are prepended
at the beginning, while existing ones will preserve the position. To add the new filters
at the end of the list, set this argument to ``False``.
pillar_key: ``acl``
The key in the pillar containing the default attributes values. Default: ``acl``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
merge_pillar: ``True``
Merge the CLI variables with the pillar. Default: ``True``.
only_lower_merge: ``False``
Specify if it should merge only the filters and terms fields. Otherwise it will try
to merge everything at the policy level. Default: ``False``.
revision_id
Add a comment in the policy config having the description for the changes applied.
revision_no
The revision count.
revision_date: ``True``
Boolean flag: display the date when the policy configuration was generated. Default: ``True``.
revision_date_format: ``%Y/%m/%d``
The date format to be used when generating the perforce data. Default: ``%Y/%m/%d`` (<year>/<month>/<day>).
CLI Example:
.. code-block:: bash
salt '*' capirca.get_policy_config juniper pillar_key=netacl
Output Example:
.. code-block:: text
firewall {
family inet {
replace:
/*
** $Id:$
** $Date:$
** $Revision:$
**
*/
filter my-filter {
term my-term {
from {
source-port [ 1234 1235 ];
}
then {
reject;
}
}
term my-other-term {
from {
protocol tcp;
source-port 5678-5680;
}
then accept;
}
}
}
}
firewall {
family inet {
replace:
/*
** $Id:$
** $Date:$
** $Revision:$
**
*/
filter my-other-filter {
interface-specific;
term dummy-term {
from {
protocol [ tcp udp ];
}
then {
reject;
}
}
}
}
}
The policy configuration has been loaded from the pillar, having the following structure:
.. code-block:: yaml
netacl:
- my-filter:
options:
- not-interface-specific
terms:
- my-term:
source_port: [1234, 1235]
action: reject
- my-other-term:
source_port:
- [5678, 5680]
protocol: tcp
action: accept
- my-other-filter:
terms:
- dummy-term:
protocol:
- tcp
- udp
action: reject
'''
if not filters:
filters = []
if merge_pillar and not only_lower_merge:
# the pillar key for the policy config is the `pillar_key` itself
policy_pillar_cfg = _get_pillar_cfg(pillar_key,
saltenv=saltenv,
pillarenv=pillarenv)
# now, let's merge everything witht the pillar data
# again, this will not remove any extra filters/terms
# but it will merge with the pillar data
# if this behaviour is not wanted, the user can set `merge_pillar` as `False`
filters = _merge_list_of_dict(filters, policy_pillar_cfg, prepend=prepend)
policy_object = _get_policy_object(platform,
filters=filters,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar)
policy_text = six.text_type(policy_object)
return _revision_tag(policy_text,
revision_id=revision_id,
revision_no=revision_no,
revision_date=revision_date,
revision_date_format=revision_date_format) | [
"def",
"get_policy_config",
"(",
"platform",
",",
"filters",
"=",
"None",
",",
"prepend",
"=",
"True",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
",",
"merge_pillar",
"=",
"True",
",",
"only_lower_merge",
"... | Return the configuration of the whole policy.
platform
The name of the Capirca platform.
filters
List of filters for this policy.
If not specified or empty, will try to load the configuration from the pillar,
unless ``merge_pillar`` is set as ``False``.
prepend: ``True``
When ``merge_pillar`` is set as ``True``, the final list of filters generated by merging
the filters from ``filters`` with those defined in the pillar (if any): new filters are prepended
at the beginning, while existing ones will preserve the position. To add the new filters
at the end of the list, set this argument to ``False``.
pillar_key: ``acl``
The key in the pillar containing the default attributes values. Default: ``acl``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
merge_pillar: ``True``
Merge the CLI variables with the pillar. Default: ``True``.
only_lower_merge: ``False``
Specify if it should merge only the filters and terms fields. Otherwise it will try
to merge everything at the policy level. Default: ``False``.
revision_id
Add a comment in the policy config having the description for the changes applied.
revision_no
The revision count.
revision_date: ``True``
Boolean flag: display the date when the policy configuration was generated. Default: ``True``.
revision_date_format: ``%Y/%m/%d``
The date format to be used when generating the perforce data. Default: ``%Y/%m/%d`` (<year>/<month>/<day>).
CLI Example:
.. code-block:: bash
salt '*' capirca.get_policy_config juniper pillar_key=netacl
Output Example:
.. code-block:: text
firewall {
family inet {
replace:
/*
** $Id:$
** $Date:$
** $Revision:$
**
*/
filter my-filter {
term my-term {
from {
source-port [ 1234 1235 ];
}
then {
reject;
}
}
term my-other-term {
from {
protocol tcp;
source-port 5678-5680;
}
then accept;
}
}
}
}
firewall {
family inet {
replace:
/*
** $Id:$
** $Date:$
** $Revision:$
**
*/
filter my-other-filter {
interface-specific;
term dummy-term {
from {
protocol [ tcp udp ];
}
then {
reject;
}
}
}
}
}
The policy configuration has been loaded from the pillar, having the following structure:
.. code-block:: yaml
netacl:
- my-filter:
options:
- not-interface-specific
terms:
- my-term:
source_port: [1234, 1235]
action: reject
- my-other-term:
source_port:
- [5678, 5680]
protocol: tcp
action: accept
- my-other-filter:
terms:
- dummy-term:
protocol:
- tcp
- udp
action: reject | [
"Return",
"the",
"configuration",
"of",
"the",
"whole",
"policy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L1034-L1202 | train |
saltstack/salt | salt/modules/capirca_acl.py | get_filter_pillar | def get_filter_pillar(filter_name,
pillar_key='acl',
pillarenv=None,
saltenv=None):
'''
Helper that can be used inside a state SLS,
in order to get the filter configuration given its name.
filter_name
The name of the filter.
pillar_key
The root key of the whole policy config.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
'''
pillar_cfg = _get_pillar_cfg(pillar_key,
pillarenv=pillarenv,
saltenv=saltenv)
return _lookup_element(pillar_cfg, filter_name) | python | def get_filter_pillar(filter_name,
pillar_key='acl',
pillarenv=None,
saltenv=None):
'''
Helper that can be used inside a state SLS,
in order to get the filter configuration given its name.
filter_name
The name of the filter.
pillar_key
The root key of the whole policy config.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
'''
pillar_cfg = _get_pillar_cfg(pillar_key,
pillarenv=pillarenv,
saltenv=saltenv)
return _lookup_element(pillar_cfg, filter_name) | [
"def",
"get_filter_pillar",
"(",
"filter_name",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
")",
":",
"pillar_cfg",
"=",
"_get_pillar_cfg",
"(",
"pillar_key",
",",
"pillarenv",
"=",
"pillarenv",
",",
"saltenv",
... | Helper that can be used inside a state SLS,
in order to get the filter configuration given its name.
filter_name
The name of the filter.
pillar_key
The root key of the whole policy config.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored. | [
"Helper",
"that",
"can",
"be",
"used",
"inside",
"a",
"state",
"SLS",
"in",
"order",
"to",
"get",
"the",
"filter",
"configuration",
"given",
"its",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L1205-L1230 | train |
saltstack/salt | salt/modules/capirca_acl.py | get_term_pillar | def get_term_pillar(filter_name,
term_name,
pillar_key='acl',
pillarenv=None,
saltenv=None):
'''
Helper that can be used inside a state SLS,
in order to get the term configuration given its name,
under a certain filter uniquely identified by its name.
filter_name
The name of the filter.
term_name
The name of the term.
pillar_key: ``acl``
The root key of the whole policy config. Default: ``acl``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
'''
filter_pillar_cfg = get_filter_pillar(filter_name,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv)
term_pillar_cfg = filter_pillar_cfg.get('terms', [])
term_opts = _lookup_element(term_pillar_cfg, term_name)
return term_opts | python | def get_term_pillar(filter_name,
term_name,
pillar_key='acl',
pillarenv=None,
saltenv=None):
'''
Helper that can be used inside a state SLS,
in order to get the term configuration given its name,
under a certain filter uniquely identified by its name.
filter_name
The name of the filter.
term_name
The name of the term.
pillar_key: ``acl``
The root key of the whole policy config. Default: ``acl``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
'''
filter_pillar_cfg = get_filter_pillar(filter_name,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv)
term_pillar_cfg = filter_pillar_cfg.get('terms', [])
term_opts = _lookup_element(term_pillar_cfg, term_name)
return term_opts | [
"def",
"get_term_pillar",
"(",
"filter_name",
",",
"term_name",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
")",
":",
"filter_pillar_cfg",
"=",
"get_filter_pillar",
"(",
"filter_name",
",",
"pillar_key",
"=",
"p... | Helper that can be used inside a state SLS,
in order to get the term configuration given its name,
under a certain filter uniquely identified by its name.
filter_name
The name of the filter.
term_name
The name of the term.
pillar_key: ``acl``
The root key of the whole policy config. Default: ``acl``.
pillarenv
Query the master to generate fresh pillar data on the fly,
specifically from the requested pillar environment.
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored. | [
"Helper",
"that",
"can",
"be",
"used",
"inside",
"a",
"state",
"SLS",
"in",
"order",
"to",
"get",
"the",
"term",
"configuration",
"given",
"its",
"name",
"under",
"a",
"certain",
"filter",
"uniquely",
"identified",
"by",
"its",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/capirca_acl.py#L1233-L1266 | train |
saltstack/salt | salt/cli/call.py | SaltCall.run | def run(self):
'''
Execute the salt call!
'''
self.parse_args()
if self.options.file_root:
# check if the argument is pointing to a file on disk
file_root = os.path.abspath(self.options.file_root)
self.config['file_roots'] = {'base': _expand_glob_path([file_root])}
if self.options.pillar_root:
# check if the argument is pointing to a file on disk
pillar_root = os.path.abspath(self.options.pillar_root)
self.config['pillar_roots'] = {'base': _expand_glob_path([pillar_root])}
if self.options.states_dir:
# check if the argument is pointing to a file on disk
states_dir = os.path.abspath(self.options.states_dir)
self.config['states_dirs'] = [states_dir]
if self.options.local:
self.config['file_client'] = 'local'
if self.options.master:
self.config['master'] = self.options.master
# Setup file logging!
self.setup_logfile_logger()
verify_log(self.config)
caller = salt.cli.caller.Caller.factory(self.config)
if self.options.doc:
caller.print_docs()
self.exit(salt.defaults.exitcodes.EX_OK)
if self.options.grains_run:
caller.print_grains()
self.exit(salt.defaults.exitcodes.EX_OK)
caller.run() | python | def run(self):
'''
Execute the salt call!
'''
self.parse_args()
if self.options.file_root:
# check if the argument is pointing to a file on disk
file_root = os.path.abspath(self.options.file_root)
self.config['file_roots'] = {'base': _expand_glob_path([file_root])}
if self.options.pillar_root:
# check if the argument is pointing to a file on disk
pillar_root = os.path.abspath(self.options.pillar_root)
self.config['pillar_roots'] = {'base': _expand_glob_path([pillar_root])}
if self.options.states_dir:
# check if the argument is pointing to a file on disk
states_dir = os.path.abspath(self.options.states_dir)
self.config['states_dirs'] = [states_dir]
if self.options.local:
self.config['file_client'] = 'local'
if self.options.master:
self.config['master'] = self.options.master
# Setup file logging!
self.setup_logfile_logger()
verify_log(self.config)
caller = salt.cli.caller.Caller.factory(self.config)
if self.options.doc:
caller.print_docs()
self.exit(salt.defaults.exitcodes.EX_OK)
if self.options.grains_run:
caller.print_grains()
self.exit(salt.defaults.exitcodes.EX_OK)
caller.run() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"parse_args",
"(",
")",
"if",
"self",
".",
"options",
".",
"file_root",
":",
"# check if the argument is pointing to a file on disk",
"file_root",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"op... | Execute the salt call! | [
"Execute",
"the",
"salt",
"call!"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/call.py#L17-L57 | train |
saltstack/salt | salt/states/highstate_doc.py | note | def note(name, source=None, contents=None, **kwargs):
'''
Add content to a document generated using `highstate_doc.render`.
This state does not preform any tasks on the host. It only is used in highstate_doc lowstate proccessers
to include extra documents.
.. code-block:: yaml
{{sls}} example note:
highstate_doc.note:
- name: example note
- require_in:
- pkg: somepackage
- contents: |
example `highstate_doc.note`
------------------
This state does not do anything to the system! It is only used by a `proccesser`
you can use `requisites` and `order` to move your docs around the rendered file.
.. this message appare aboce the `pkg: somepackage` state.
- source: salt://{{tpldir}}/also_include_a_file.md
{{sls}} extra help:
highstate_doc.note:
- name: example
- order: 0
- source: salt://{{tpldir}}/HELP.md
'''
comment = ''
if source:
comment += 'include file: {0}\n'.format(source)
if contents and len(contents) < 200:
comment += contents
return {'name': name, 'result': True, 'comment': comment, 'changes': {}} | python | def note(name, source=None, contents=None, **kwargs):
'''
Add content to a document generated using `highstate_doc.render`.
This state does not preform any tasks on the host. It only is used in highstate_doc lowstate proccessers
to include extra documents.
.. code-block:: yaml
{{sls}} example note:
highstate_doc.note:
- name: example note
- require_in:
- pkg: somepackage
- contents: |
example `highstate_doc.note`
------------------
This state does not do anything to the system! It is only used by a `proccesser`
you can use `requisites` and `order` to move your docs around the rendered file.
.. this message appare aboce the `pkg: somepackage` state.
- source: salt://{{tpldir}}/also_include_a_file.md
{{sls}} extra help:
highstate_doc.note:
- name: example
- order: 0
- source: salt://{{tpldir}}/HELP.md
'''
comment = ''
if source:
comment += 'include file: {0}\n'.format(source)
if contents and len(contents) < 200:
comment += contents
return {'name': name, 'result': True, 'comment': comment, 'changes': {}} | [
"def",
"note",
"(",
"name",
",",
"source",
"=",
"None",
",",
"contents",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"comment",
"=",
"''",
"if",
"source",
":",
"comment",
"+=",
"'include file: {0}\\n'",
".",
"format",
"(",
"source",
")",
"if",
"c... | Add content to a document generated using `highstate_doc.render`.
This state does not preform any tasks on the host. It only is used in highstate_doc lowstate proccessers
to include extra documents.
.. code-block:: yaml
{{sls}} example note:
highstate_doc.note:
- name: example note
- require_in:
- pkg: somepackage
- contents: |
example `highstate_doc.note`
------------------
This state does not do anything to the system! It is only used by a `proccesser`
you can use `requisites` and `order` to move your docs around the rendered file.
.. this message appare aboce the `pkg: somepackage` state.
- source: salt://{{tpldir}}/also_include_a_file.md
{{sls}} extra help:
highstate_doc.note:
- name: example
- order: 0
- source: salt://{{tpldir}}/HELP.md | [
"Add",
"content",
"to",
"a",
"document",
"generated",
"using",
"highstate_doc",
".",
"render",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/highstate_doc.py#L12-L45 | train |
saltstack/salt | salt/modules/win_wua.py | available | def available(software=True,
drivers=True,
summary=False,
skip_installed=True,
skip_hidden=True,
skip_mandatory=False,
skip_reboot=False,
categories=None,
severities=None,):
'''
.. versionadded:: 2017.7.0
List updates that match the passed criteria. This allows for more filter
options than :func:`list`. Good for finding a specific GUID or KB.
Args:
software (bool):
Include software updates in the results (default is True)
drivers (bool):
Include driver updates in the results (default is True)
summary (bool):
- True: Return a summary of updates available for each category.
- False (default): Return a detailed list of available updates.
skip_installed (bool):
Skip updates that are already installed. Default is False.
skip_hidden (bool):
Skip updates that have been hidden. Default is True.
skip_mandatory (bool):
Skip mandatory updates. Default is False.
skip_reboot (bool):
Skip updates that require a reboot. Default is False.
categories (list):
Specify the categories to list. Must be passed as a list. All
categories returned by default.
Categories include the following:
* Critical Updates
* Definition Updates
* Drivers (make sure you set drivers=True)
* Feature Packs
* Security Updates
* Update Rollups
* Updates
* Update Rollups
* Windows 7
* Windows 8.1
* Windows 8.1 drivers
* Windows 8.1 and later drivers
* Windows Defender
severities (list):
Specify the severities to include. Must be passed as a list. All
severities returned by default.
Severities include the following:
* Critical
* Important
Returns:
dict: Returns a dict containing either a summary or a list of updates:
.. code-block:: cfg
List of Updates:
{'<GUID>': {'Title': <title>,
'KB': <KB>,
'GUID': <the globally unique identifier for the update>
'Description': <description>,
'Downloaded': <has the update been downloaded>,
'Installed': <has the update been installed>,
'Mandatory': <is the update mandatory>,
'UserInput': <is user input required>,
'EULAAccepted': <has the EULA been accepted>,
'Severity': <update severity>,
'NeedsReboot': <is the update installed and awaiting reboot>,
'RebootBehavior': <will the update require a reboot>,
'Categories': [ '<category 1>',
'<category 2>',
...]
}
}
Summary of Updates:
{'Total': <total number of updates returned>,
'Available': <updates that are not downloaded or installed>,
'Downloaded': <updates that are downloaded but not installed>,
'Installed': <updates installed (usually 0 unless installed=True)>,
'Categories': { <category 1>: <total for that category>,
<category 2>: <total for category 2>,
... }
}
CLI Examples:
.. code-block:: bash
# Normal Usage (list all software updates)
salt '*' win_wua.available
# List all updates with categories of Critical Updates and Drivers
salt '*' win_wua.available categories=["Critical Updates","Drivers"]
# List all Critical Security Updates
salt '*' win_wua.available categories=["Security Updates"] severities=["Critical"]
# List all updates with a severity of Critical
salt '*' win_wua.available severities=["Critical"]
# A summary of all available updates
salt '*' win_wua.available summary=True
# A summary of all Feature Packs and Windows 8.1 Updates
salt '*' win_wua.available categories=["Feature Packs","Windows 8.1"] summary=True
'''
# Create a Windows Update Agent instance
wua = salt.utils.win_update.WindowsUpdateAgent()
# Look for available
updates = wua.available(
skip_hidden=skip_hidden, skip_installed=skip_installed,
skip_mandatory=skip_mandatory, skip_reboot=skip_reboot,
software=software, drivers=drivers, categories=categories,
severities=severities)
# Return results as Summary or Details
return updates.summary() if summary else updates.list() | python | def available(software=True,
drivers=True,
summary=False,
skip_installed=True,
skip_hidden=True,
skip_mandatory=False,
skip_reboot=False,
categories=None,
severities=None,):
'''
.. versionadded:: 2017.7.0
List updates that match the passed criteria. This allows for more filter
options than :func:`list`. Good for finding a specific GUID or KB.
Args:
software (bool):
Include software updates in the results (default is True)
drivers (bool):
Include driver updates in the results (default is True)
summary (bool):
- True: Return a summary of updates available for each category.
- False (default): Return a detailed list of available updates.
skip_installed (bool):
Skip updates that are already installed. Default is False.
skip_hidden (bool):
Skip updates that have been hidden. Default is True.
skip_mandatory (bool):
Skip mandatory updates. Default is False.
skip_reboot (bool):
Skip updates that require a reboot. Default is False.
categories (list):
Specify the categories to list. Must be passed as a list. All
categories returned by default.
Categories include the following:
* Critical Updates
* Definition Updates
* Drivers (make sure you set drivers=True)
* Feature Packs
* Security Updates
* Update Rollups
* Updates
* Update Rollups
* Windows 7
* Windows 8.1
* Windows 8.1 drivers
* Windows 8.1 and later drivers
* Windows Defender
severities (list):
Specify the severities to include. Must be passed as a list. All
severities returned by default.
Severities include the following:
* Critical
* Important
Returns:
dict: Returns a dict containing either a summary or a list of updates:
.. code-block:: cfg
List of Updates:
{'<GUID>': {'Title': <title>,
'KB': <KB>,
'GUID': <the globally unique identifier for the update>
'Description': <description>,
'Downloaded': <has the update been downloaded>,
'Installed': <has the update been installed>,
'Mandatory': <is the update mandatory>,
'UserInput': <is user input required>,
'EULAAccepted': <has the EULA been accepted>,
'Severity': <update severity>,
'NeedsReboot': <is the update installed and awaiting reboot>,
'RebootBehavior': <will the update require a reboot>,
'Categories': [ '<category 1>',
'<category 2>',
...]
}
}
Summary of Updates:
{'Total': <total number of updates returned>,
'Available': <updates that are not downloaded or installed>,
'Downloaded': <updates that are downloaded but not installed>,
'Installed': <updates installed (usually 0 unless installed=True)>,
'Categories': { <category 1>: <total for that category>,
<category 2>: <total for category 2>,
... }
}
CLI Examples:
.. code-block:: bash
# Normal Usage (list all software updates)
salt '*' win_wua.available
# List all updates with categories of Critical Updates and Drivers
salt '*' win_wua.available categories=["Critical Updates","Drivers"]
# List all Critical Security Updates
salt '*' win_wua.available categories=["Security Updates"] severities=["Critical"]
# List all updates with a severity of Critical
salt '*' win_wua.available severities=["Critical"]
# A summary of all available updates
salt '*' win_wua.available summary=True
# A summary of all Feature Packs and Windows 8.1 Updates
salt '*' win_wua.available categories=["Feature Packs","Windows 8.1"] summary=True
'''
# Create a Windows Update Agent instance
wua = salt.utils.win_update.WindowsUpdateAgent()
# Look for available
updates = wua.available(
skip_hidden=skip_hidden, skip_installed=skip_installed,
skip_mandatory=skip_mandatory, skip_reboot=skip_reboot,
software=software, drivers=drivers, categories=categories,
severities=severities)
# Return results as Summary or Details
return updates.summary() if summary else updates.list() | [
"def",
"available",
"(",
"software",
"=",
"True",
",",
"drivers",
"=",
"True",
",",
"summary",
"=",
"False",
",",
"skip_installed",
"=",
"True",
",",
"skip_hidden",
"=",
"True",
",",
"skip_mandatory",
"=",
"False",
",",
"skip_reboot",
"=",
"False",
",",
... | .. versionadded:: 2017.7.0
List updates that match the passed criteria. This allows for more filter
options than :func:`list`. Good for finding a specific GUID or KB.
Args:
software (bool):
Include software updates in the results (default is True)
drivers (bool):
Include driver updates in the results (default is True)
summary (bool):
- True: Return a summary of updates available for each category.
- False (default): Return a detailed list of available updates.
skip_installed (bool):
Skip updates that are already installed. Default is False.
skip_hidden (bool):
Skip updates that have been hidden. Default is True.
skip_mandatory (bool):
Skip mandatory updates. Default is False.
skip_reboot (bool):
Skip updates that require a reboot. Default is False.
categories (list):
Specify the categories to list. Must be passed as a list. All
categories returned by default.
Categories include the following:
* Critical Updates
* Definition Updates
* Drivers (make sure you set drivers=True)
* Feature Packs
* Security Updates
* Update Rollups
* Updates
* Update Rollups
* Windows 7
* Windows 8.1
* Windows 8.1 drivers
* Windows 8.1 and later drivers
* Windows Defender
severities (list):
Specify the severities to include. Must be passed as a list. All
severities returned by default.
Severities include the following:
* Critical
* Important
Returns:
dict: Returns a dict containing either a summary or a list of updates:
.. code-block:: cfg
List of Updates:
{'<GUID>': {'Title': <title>,
'KB': <KB>,
'GUID': <the globally unique identifier for the update>
'Description': <description>,
'Downloaded': <has the update been downloaded>,
'Installed': <has the update been installed>,
'Mandatory': <is the update mandatory>,
'UserInput': <is user input required>,
'EULAAccepted': <has the EULA been accepted>,
'Severity': <update severity>,
'NeedsReboot': <is the update installed and awaiting reboot>,
'RebootBehavior': <will the update require a reboot>,
'Categories': [ '<category 1>',
'<category 2>',
...]
}
}
Summary of Updates:
{'Total': <total number of updates returned>,
'Available': <updates that are not downloaded or installed>,
'Downloaded': <updates that are downloaded but not installed>,
'Installed': <updates installed (usually 0 unless installed=True)>,
'Categories': { <category 1>: <total for that category>,
<category 2>: <total for category 2>,
... }
}
CLI Examples:
.. code-block:: bash
# Normal Usage (list all software updates)
salt '*' win_wua.available
# List all updates with categories of Critical Updates and Drivers
salt '*' win_wua.available categories=["Critical Updates","Drivers"]
# List all Critical Security Updates
salt '*' win_wua.available categories=["Security Updates"] severities=["Critical"]
# List all updates with a severity of Critical
salt '*' win_wua.available severities=["Critical"]
# A summary of all available updates
salt '*' win_wua.available summary=True
# A summary of all Feature Packs and Windows 8.1 Updates
salt '*' win_wua.available categories=["Feature Packs","Windows 8.1"] summary=True | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wua.py#L99-L236 | train |
saltstack/salt | salt/modules/win_wua.py | get | def get(name, download=False, install=False):
'''
.. versionadded:: 2017.7.0
Returns details for the named update
Args:
name (str):
The name of the update you're searching for. This can be the GUID, a
KB number, or any part of the name of the update. GUIDs and KBs are
preferred. Run ``list`` to get the GUID for the update you're
looking for.
download (bool):
Download the update returned by this function. Run this function
first to see if the update exists, then set ``download=True`` to
download the update.
install (bool):
Install the update returned by this function. Run this function
first to see if the update exists, then set ``install=True`` to
install the update.
Returns:
dict: Returns a dict containing a list of updates that match the name if
download and install are both set to False. Should usually be a single
update, but can return multiple if a partial name is given.
If download or install is set to true it will return the results of the
operation.
.. code-block:: cfg
List of Updates:
{'<GUID>': {'Title': <title>,
'KB': <KB>,
'GUID': <the globally unique identifier for the update>
'Description': <description>,
'Downloaded': <has the update been downloaded>,
'Installed': <has the update been installed>,
'Mandatory': <is the update mandatory>,
'UserInput': <is user input required>,
'EULAAccepted': <has the EULA been accepted>,
'Severity': <update severity>,
'NeedsReboot': <is the update installed and awaiting reboot>,
'RebootBehavior': <will the update require a reboot>,
'Categories': [ '<category 1>',
'<category 2>',
...]
}
}
CLI Examples:
.. code-block:: bash
# Recommended Usage using GUID without braces
# Use this to find the status of a specific update
salt '*' win_wua.get 12345678-abcd-1234-abcd-1234567890ab
# Use the following if you don't know the GUID:
# Using a KB number
# Not all updates have an associated KB
salt '*' win_wua.get KB3030298
# Using part or all of the name of the update
# Could possibly return multiple results
# Not all updates have an associated KB
salt '*' win_wua.get 'Microsoft Camera Codec Pack'
'''
# Create a Windows Update Agent instance
wua = salt.utils.win_update.WindowsUpdateAgent()
# Search for Update
updates = wua.search(name)
ret = {}
# Download
if download or install:
ret['Download'] = wua.download(updates)
# Install
if install:
ret['Install'] = wua.install(updates)
return ret if ret else updates.list() | python | def get(name, download=False, install=False):
'''
.. versionadded:: 2017.7.0
Returns details for the named update
Args:
name (str):
The name of the update you're searching for. This can be the GUID, a
KB number, or any part of the name of the update. GUIDs and KBs are
preferred. Run ``list`` to get the GUID for the update you're
looking for.
download (bool):
Download the update returned by this function. Run this function
first to see if the update exists, then set ``download=True`` to
download the update.
install (bool):
Install the update returned by this function. Run this function
first to see if the update exists, then set ``install=True`` to
install the update.
Returns:
dict: Returns a dict containing a list of updates that match the name if
download and install are both set to False. Should usually be a single
update, but can return multiple if a partial name is given.
If download or install is set to true it will return the results of the
operation.
.. code-block:: cfg
List of Updates:
{'<GUID>': {'Title': <title>,
'KB': <KB>,
'GUID': <the globally unique identifier for the update>
'Description': <description>,
'Downloaded': <has the update been downloaded>,
'Installed': <has the update been installed>,
'Mandatory': <is the update mandatory>,
'UserInput': <is user input required>,
'EULAAccepted': <has the EULA been accepted>,
'Severity': <update severity>,
'NeedsReboot': <is the update installed and awaiting reboot>,
'RebootBehavior': <will the update require a reboot>,
'Categories': [ '<category 1>',
'<category 2>',
...]
}
}
CLI Examples:
.. code-block:: bash
# Recommended Usage using GUID without braces
# Use this to find the status of a specific update
salt '*' win_wua.get 12345678-abcd-1234-abcd-1234567890ab
# Use the following if you don't know the GUID:
# Using a KB number
# Not all updates have an associated KB
salt '*' win_wua.get KB3030298
# Using part or all of the name of the update
# Could possibly return multiple results
# Not all updates have an associated KB
salt '*' win_wua.get 'Microsoft Camera Codec Pack'
'''
# Create a Windows Update Agent instance
wua = salt.utils.win_update.WindowsUpdateAgent()
# Search for Update
updates = wua.search(name)
ret = {}
# Download
if download or install:
ret['Download'] = wua.download(updates)
# Install
if install:
ret['Install'] = wua.install(updates)
return ret if ret else updates.list() | [
"def",
"get",
"(",
"name",
",",
"download",
"=",
"False",
",",
"install",
"=",
"False",
")",
":",
"# Create a Windows Update Agent instance",
"wua",
"=",
"salt",
".",
"utils",
".",
"win_update",
".",
"WindowsUpdateAgent",
"(",
")",
"# Search for Update",
"update... | .. versionadded:: 2017.7.0
Returns details for the named update
Args:
name (str):
The name of the update you're searching for. This can be the GUID, a
KB number, or any part of the name of the update. GUIDs and KBs are
preferred. Run ``list`` to get the GUID for the update you're
looking for.
download (bool):
Download the update returned by this function. Run this function
first to see if the update exists, then set ``download=True`` to
download the update.
install (bool):
Install the update returned by this function. Run this function
first to see if the update exists, then set ``install=True`` to
install the update.
Returns:
dict: Returns a dict containing a list of updates that match the name if
download and install are both set to False. Should usually be a single
update, but can return multiple if a partial name is given.
If download or install is set to true it will return the results of the
operation.
.. code-block:: cfg
List of Updates:
{'<GUID>': {'Title': <title>,
'KB': <KB>,
'GUID': <the globally unique identifier for the update>
'Description': <description>,
'Downloaded': <has the update been downloaded>,
'Installed': <has the update been installed>,
'Mandatory': <is the update mandatory>,
'UserInput': <is user input required>,
'EULAAccepted': <has the EULA been accepted>,
'Severity': <update severity>,
'NeedsReboot': <is the update installed and awaiting reboot>,
'RebootBehavior': <will the update require a reboot>,
'Categories': [ '<category 1>',
'<category 2>',
...]
}
}
CLI Examples:
.. code-block:: bash
# Recommended Usage using GUID without braces
# Use this to find the status of a specific update
salt '*' win_wua.get 12345678-abcd-1234-abcd-1234567890ab
# Use the following if you don't know the GUID:
# Using a KB number
# Not all updates have an associated KB
salt '*' win_wua.get KB3030298
# Using part or all of the name of the update
# Could possibly return multiple results
# Not all updates have an associated KB
salt '*' win_wua.get 'Microsoft Camera Codec Pack' | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wua.py#L239-L328 | train |
saltstack/salt | salt/modules/win_wua.py | list | def list(software=True,
drivers=False,
summary=False,
skip_installed=True,
categories=None,
severities=None,
download=False,
install=False):
'''
.. versionadded:: 2017.7.0
Returns a detailed list of available updates or a summary. If download or
install is True the same list will be downloaded and/or installed.
Args:
software (bool):
Include software updates in the results (default is True)
drivers (bool):
Include driver updates in the results (default is False)
summary (bool):
- True: Return a summary of updates available for each category.
- False (default): Return a detailed list of available updates.
skip_installed (bool):
Skip installed updates in the results (default is False)
download (bool):
(Overrides reporting functionality) Download the list of updates
returned by this function. Run this function first with
``download=False`` to see what will be downloaded, then set
``download=True`` to download the updates.
install (bool):
(Overrides reporting functionality) Install the list of updates
returned by this function. Run this function first with
``install=False`` to see what will be installed, then set
``install=True`` to install the updates.
categories (list):
Specify the categories to list. Must be passed as a list. All
categories returned by default.
Categories include the following:
* Critical Updates
* Definition Updates
* Drivers (make sure you set drivers=True)
* Feature Packs
* Security Updates
* Update Rollups
* Updates
* Update Rollups
* Windows 7
* Windows 8.1
* Windows 8.1 drivers
* Windows 8.1 and later drivers
* Windows Defender
severities (list):
Specify the severities to include. Must be passed as a list. All
severities returned by default.
Severities include the following:
* Critical
* Important
Returns:
dict: Returns a dict containing either a summary or a list of updates:
.. code-block:: cfg
List of Updates:
{'<GUID>': {'Title': <title>,
'KB': <KB>,
'GUID': <the globally unique identifier for the update>
'Description': <description>,
'Downloaded': <has the update been downloaded>,
'Installed': <has the update been installed>,
'Mandatory': <is the update mandatory>,
'UserInput': <is user input required>,
'EULAAccepted': <has the EULA been accepted>,
'Severity': <update severity>,
'NeedsReboot': <is the update installed and awaiting reboot>,
'RebootBehavior': <will the update require a reboot>,
'Categories': [ '<category 1>',
'<category 2>',
...]
}
}
Summary of Updates:
{'Total': <total number of updates returned>,
'Available': <updates that are not downloaded or installed>,
'Downloaded': <updates that are downloaded but not installed>,
'Installed': <updates installed (usually 0 unless installed=True)>,
'Categories': { <category 1>: <total for that category>,
<category 2>: <total for category 2>,
... }
}
CLI Examples:
.. code-block:: bash
# Normal Usage (list all software updates)
salt '*' win_wua.list
# List all updates with categories of Critical Updates and Drivers
salt '*' win_wua.list categories=['Critical Updates','Drivers']
# List all Critical Security Updates
salt '*' win_wua.list categories=['Security Updates'] severities=['Critical']
# List all updates with a severity of Critical
salt '*' win_wua.list severities=['Critical']
# A summary of all available updates
salt '*' win_wua.list summary=True
# A summary of all Feature Packs and Windows 8.1 Updates
salt '*' win_wua.list categories=['Feature Packs','Windows 8.1'] summary=True
'''
# Create a Windows Update Agent instance
wua = salt.utils.win_update.WindowsUpdateAgent()
# Search for Update
updates = wua.available(skip_installed=skip_installed, software=software,
drivers=drivers, categories=categories,
severities=severities)
ret = {}
# Download
if download or install:
ret['Download'] = wua.download(updates)
# Install
if install:
ret['Install'] = wua.install(updates)
if not ret:
return updates.summary() if summary else updates.list()
return ret | python | def list(software=True,
drivers=False,
summary=False,
skip_installed=True,
categories=None,
severities=None,
download=False,
install=False):
'''
.. versionadded:: 2017.7.0
Returns a detailed list of available updates or a summary. If download or
install is True the same list will be downloaded and/or installed.
Args:
software (bool):
Include software updates in the results (default is True)
drivers (bool):
Include driver updates in the results (default is False)
summary (bool):
- True: Return a summary of updates available for each category.
- False (default): Return a detailed list of available updates.
skip_installed (bool):
Skip installed updates in the results (default is False)
download (bool):
(Overrides reporting functionality) Download the list of updates
returned by this function. Run this function first with
``download=False`` to see what will be downloaded, then set
``download=True`` to download the updates.
install (bool):
(Overrides reporting functionality) Install the list of updates
returned by this function. Run this function first with
``install=False`` to see what will be installed, then set
``install=True`` to install the updates.
categories (list):
Specify the categories to list. Must be passed as a list. All
categories returned by default.
Categories include the following:
* Critical Updates
* Definition Updates
* Drivers (make sure you set drivers=True)
* Feature Packs
* Security Updates
* Update Rollups
* Updates
* Update Rollups
* Windows 7
* Windows 8.1
* Windows 8.1 drivers
* Windows 8.1 and later drivers
* Windows Defender
severities (list):
Specify the severities to include. Must be passed as a list. All
severities returned by default.
Severities include the following:
* Critical
* Important
Returns:
dict: Returns a dict containing either a summary or a list of updates:
.. code-block:: cfg
List of Updates:
{'<GUID>': {'Title': <title>,
'KB': <KB>,
'GUID': <the globally unique identifier for the update>
'Description': <description>,
'Downloaded': <has the update been downloaded>,
'Installed': <has the update been installed>,
'Mandatory': <is the update mandatory>,
'UserInput': <is user input required>,
'EULAAccepted': <has the EULA been accepted>,
'Severity': <update severity>,
'NeedsReboot': <is the update installed and awaiting reboot>,
'RebootBehavior': <will the update require a reboot>,
'Categories': [ '<category 1>',
'<category 2>',
...]
}
}
Summary of Updates:
{'Total': <total number of updates returned>,
'Available': <updates that are not downloaded or installed>,
'Downloaded': <updates that are downloaded but not installed>,
'Installed': <updates installed (usually 0 unless installed=True)>,
'Categories': { <category 1>: <total for that category>,
<category 2>: <total for category 2>,
... }
}
CLI Examples:
.. code-block:: bash
# Normal Usage (list all software updates)
salt '*' win_wua.list
# List all updates with categories of Critical Updates and Drivers
salt '*' win_wua.list categories=['Critical Updates','Drivers']
# List all Critical Security Updates
salt '*' win_wua.list categories=['Security Updates'] severities=['Critical']
# List all updates with a severity of Critical
salt '*' win_wua.list severities=['Critical']
# A summary of all available updates
salt '*' win_wua.list summary=True
# A summary of all Feature Packs and Windows 8.1 Updates
salt '*' win_wua.list categories=['Feature Packs','Windows 8.1'] summary=True
'''
# Create a Windows Update Agent instance
wua = salt.utils.win_update.WindowsUpdateAgent()
# Search for Update
updates = wua.available(skip_installed=skip_installed, software=software,
drivers=drivers, categories=categories,
severities=severities)
ret = {}
# Download
if download or install:
ret['Download'] = wua.download(updates)
# Install
if install:
ret['Install'] = wua.install(updates)
if not ret:
return updates.summary() if summary else updates.list()
return ret | [
"def",
"list",
"(",
"software",
"=",
"True",
",",
"drivers",
"=",
"False",
",",
"summary",
"=",
"False",
",",
"skip_installed",
"=",
"True",
",",
"categories",
"=",
"None",
",",
"severities",
"=",
"None",
",",
"download",
"=",
"False",
",",
"install",
... | .. versionadded:: 2017.7.0
Returns a detailed list of available updates or a summary. If download or
install is True the same list will be downloaded and/or installed.
Args:
software (bool):
Include software updates in the results (default is True)
drivers (bool):
Include driver updates in the results (default is False)
summary (bool):
- True: Return a summary of updates available for each category.
- False (default): Return a detailed list of available updates.
skip_installed (bool):
Skip installed updates in the results (default is False)
download (bool):
(Overrides reporting functionality) Download the list of updates
returned by this function. Run this function first with
``download=False`` to see what will be downloaded, then set
``download=True`` to download the updates.
install (bool):
(Overrides reporting functionality) Install the list of updates
returned by this function. Run this function first with
``install=False`` to see what will be installed, then set
``install=True`` to install the updates.
categories (list):
Specify the categories to list. Must be passed as a list. All
categories returned by default.
Categories include the following:
* Critical Updates
* Definition Updates
* Drivers (make sure you set drivers=True)
* Feature Packs
* Security Updates
* Update Rollups
* Updates
* Update Rollups
* Windows 7
* Windows 8.1
* Windows 8.1 drivers
* Windows 8.1 and later drivers
* Windows Defender
severities (list):
Specify the severities to include. Must be passed as a list. All
severities returned by default.
Severities include the following:
* Critical
* Important
Returns:
dict: Returns a dict containing either a summary or a list of updates:
.. code-block:: cfg
List of Updates:
{'<GUID>': {'Title': <title>,
'KB': <KB>,
'GUID': <the globally unique identifier for the update>
'Description': <description>,
'Downloaded': <has the update been downloaded>,
'Installed': <has the update been installed>,
'Mandatory': <is the update mandatory>,
'UserInput': <is user input required>,
'EULAAccepted': <has the EULA been accepted>,
'Severity': <update severity>,
'NeedsReboot': <is the update installed and awaiting reboot>,
'RebootBehavior': <will the update require a reboot>,
'Categories': [ '<category 1>',
'<category 2>',
...]
}
}
Summary of Updates:
{'Total': <total number of updates returned>,
'Available': <updates that are not downloaded or installed>,
'Downloaded': <updates that are downloaded but not installed>,
'Installed': <updates installed (usually 0 unless installed=True)>,
'Categories': { <category 1>: <total for that category>,
<category 2>: <total for category 2>,
... }
}
CLI Examples:
.. code-block:: bash
# Normal Usage (list all software updates)
salt '*' win_wua.list
# List all updates with categories of Critical Updates and Drivers
salt '*' win_wua.list categories=['Critical Updates','Drivers']
# List all Critical Security Updates
salt '*' win_wua.list categories=['Security Updates'] severities=['Critical']
# List all updates with a severity of Critical
salt '*' win_wua.list severities=['Critical']
# A summary of all available updates
salt '*' win_wua.list summary=True
# A summary of all Feature Packs and Windows 8.1 Updates
salt '*' win_wua.list categories=['Feature Packs','Windows 8.1'] summary=True | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wua.py#L331-L479 | train |
saltstack/salt | salt/modules/win_wua.py | download | def download(names):
'''
.. versionadded:: 2017.7.0
Downloads updates that match the list of passed identifiers. It's easier to
use this function by using list_updates and setting install=True.
Args:
names (str, list):
A single update or a list of updates to download. This can be any
combination of GUIDs, KB numbers, or names. GUIDs or KBs are
preferred.
.. note::
An error will be raised if there are more results than there are items
in the names parameter
Returns:
dict: A dictionary containing the details about the downloaded updates
CLI Examples:
.. code-block:: bash
# Normal Usage
salt '*' win_wua.download names=['12345678-abcd-1234-abcd-1234567890ab', 'KB2131233']
'''
# Create a Windows Update Agent instance
wua = salt.utils.win_update.WindowsUpdateAgent()
# Search for Update
updates = wua.search(names)
if updates.count() == 0:
raise CommandExecutionError('No updates found')
# Make sure it's a list so count comparison is correct
if isinstance(names, six.string_types):
names = [names]
if isinstance(names, six.integer_types):
names = [six.text_type(names)]
if updates.count() > len(names):
raise CommandExecutionError('Multiple updates found, names need to be '
'more specific')
return wua.download(updates) | python | def download(names):
'''
.. versionadded:: 2017.7.0
Downloads updates that match the list of passed identifiers. It's easier to
use this function by using list_updates and setting install=True.
Args:
names (str, list):
A single update or a list of updates to download. This can be any
combination of GUIDs, KB numbers, or names. GUIDs or KBs are
preferred.
.. note::
An error will be raised if there are more results than there are items
in the names parameter
Returns:
dict: A dictionary containing the details about the downloaded updates
CLI Examples:
.. code-block:: bash
# Normal Usage
salt '*' win_wua.download names=['12345678-abcd-1234-abcd-1234567890ab', 'KB2131233']
'''
# Create a Windows Update Agent instance
wua = salt.utils.win_update.WindowsUpdateAgent()
# Search for Update
updates = wua.search(names)
if updates.count() == 0:
raise CommandExecutionError('No updates found')
# Make sure it's a list so count comparison is correct
if isinstance(names, six.string_types):
names = [names]
if isinstance(names, six.integer_types):
names = [six.text_type(names)]
if updates.count() > len(names):
raise CommandExecutionError('Multiple updates found, names need to be '
'more specific')
return wua.download(updates) | [
"def",
"download",
"(",
"names",
")",
":",
"# Create a Windows Update Agent instance",
"wua",
"=",
"salt",
".",
"utils",
".",
"win_update",
".",
"WindowsUpdateAgent",
"(",
")",
"# Search for Update",
"updates",
"=",
"wua",
".",
"search",
"(",
"names",
")",
"if",... | .. versionadded:: 2017.7.0
Downloads updates that match the list of passed identifiers. It's easier to
use this function by using list_updates and setting install=True.
Args:
names (str, list):
A single update or a list of updates to download. This can be any
combination of GUIDs, KB numbers, or names. GUIDs or KBs are
preferred.
.. note::
An error will be raised if there are more results than there are items
in the names parameter
Returns:
dict: A dictionary containing the details about the downloaded updates
CLI Examples:
.. code-block:: bash
# Normal Usage
salt '*' win_wua.download names=['12345678-abcd-1234-abcd-1234567890ab', 'KB2131233'] | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wua.py#L482-L531 | train |
saltstack/salt | salt/modules/win_wua.py | uninstall | def uninstall(names):
'''
.. versionadded:: 2017.7.0
Uninstall updates.
Args:
names (str, list):
A single update or a list of updates to uninstall. This can be any
combination of GUIDs, KB numbers, or names. GUIDs or KBs are
preferred.
Returns:
dict: A dictionary containing the details about the uninstalled updates
CLI Examples:
.. code-block:: bash
# Normal Usage
salt '*' win_wua.uninstall KB3121212
# As a list
salt '*' win_wua.uninstall guid=['12345678-abcd-1234-abcd-1234567890ab', 'KB1231231']
'''
# Create a Windows Update Agent instance
wua = salt.utils.win_update.WindowsUpdateAgent()
# Search for Updates
updates = wua.search(names)
if updates.count() == 0:
raise CommandExecutionError('No updates found')
return wua.uninstall(updates) | python | def uninstall(names):
'''
.. versionadded:: 2017.7.0
Uninstall updates.
Args:
names (str, list):
A single update or a list of updates to uninstall. This can be any
combination of GUIDs, KB numbers, or names. GUIDs or KBs are
preferred.
Returns:
dict: A dictionary containing the details about the uninstalled updates
CLI Examples:
.. code-block:: bash
# Normal Usage
salt '*' win_wua.uninstall KB3121212
# As a list
salt '*' win_wua.uninstall guid=['12345678-abcd-1234-abcd-1234567890ab', 'KB1231231']
'''
# Create a Windows Update Agent instance
wua = salt.utils.win_update.WindowsUpdateAgent()
# Search for Updates
updates = wua.search(names)
if updates.count() == 0:
raise CommandExecutionError('No updates found')
return wua.uninstall(updates) | [
"def",
"uninstall",
"(",
"names",
")",
":",
"# Create a Windows Update Agent instance",
"wua",
"=",
"salt",
".",
"utils",
".",
"win_update",
".",
"WindowsUpdateAgent",
"(",
")",
"# Search for Updates",
"updates",
"=",
"wua",
".",
"search",
"(",
"names",
")",
"if... | .. versionadded:: 2017.7.0
Uninstall updates.
Args:
names (str, list):
A single update or a list of updates to uninstall. This can be any
combination of GUIDs, KB numbers, or names. GUIDs or KBs are
preferred.
Returns:
dict: A dictionary containing the details about the uninstalled updates
CLI Examples:
.. code-block:: bash
# Normal Usage
salt '*' win_wua.uninstall KB3121212
# As a list
salt '*' win_wua.uninstall guid=['12345678-abcd-1234-abcd-1234567890ab', 'KB1231231'] | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wua.py#L586-L622 | train |
saltstack/salt | salt/modules/win_wua.py | set_wu_settings | def set_wu_settings(level=None,
recommended=None,
featured=None,
elevated=None,
msupdate=None,
day=None,
time=None):
'''
Change Windows Update settings. If no parameters are passed, the current
value will be returned.
Supported:
- Windows Vista / Server 2008
- Windows 7 / Server 2008R2
- Windows 8 / Server 2012
- Windows 8.1 / Server 2012R2
.. note:
Microsoft began using the Unified Update Platform (UUP) starting with
Windows 10 / Server 2016. The Windows Update settings have changed and
the ability to 'Save' Windows Update settings has been removed. Windows
Update settings are read-only. See MSDN documentation:
https://msdn.microsoft.com/en-us/library/aa385829(v=vs.85).aspx
Args:
level (int):
Number from 1 to 4 indicating the update level:
1. Never check for updates
2. Check for updates but let me choose whether to download and install them
3. Download updates but let me choose whether to install them
4. Install updates automatically
recommended (bool):
Boolean value that indicates whether to include optional or
recommended updates when a search for updates and installation of
updates is performed.
featured (bool):
Boolean value that indicates whether to display notifications for
featured updates.
elevated (bool):
Boolean value that indicates whether non-administrators can perform
some update-related actions without administrator approval.
msupdate (bool):
Boolean value that indicates whether to turn on Microsoft Update for
other Microsoft products
day (str):
Days of the week on which Automatic Updates installs or uninstalls
updates. Accepted values:
- Everyday
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
time (str):
Time at which Automatic Updates installs or uninstalls updates. Must
be in the ##:## 24hr format, eg. 3:00 PM would be 15:00. Must be in
1 hour increments.
Returns:
dict: Returns a dictionary containing the results.
CLI Examples:
.. code-block:: bash
salt '*' win_wua.set_wu_settings level=4 recommended=True featured=False
'''
# The AutomaticUpdateSettings.Save() method used in this function does not
# work on Windows 10 / Server 2016. It is called in throughout this function
# like this:
#
# with salt.utils.winapi.Com():
# obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')
# obj_au_settings = obj_au.Settings
# obj_au_settings.Save()
#
# The `Save()` method reports success but doesn't actually change anything.
# Windows Update settings are read-only in Windows 10 / Server 2016. There's
# a little blurb on MSDN that mentions this, but gives no alternative for
# changing these settings in Windows 10 / Server 2016.
#
# https://msdn.microsoft.com/en-us/library/aa385829(v=vs.85).aspx
#
# Apparently the Windows Update framework in Windows Vista - Windows 8.1 has
# been changed quite a bit in Windows 10 / Server 2016. It is now called the
# Unified Update Platform (UUP). I haven't found an API or a Powershell
# commandlet for working with the the UUP. Perhaps there will be something
# forthcoming. The `win_lgpo` module might be an option for changing the
# Windows Update settings using local group policy.
ret = {'Success': True}
# Initialize the PyCom system
with salt.utils.winapi.Com():
# Create an AutoUpdate object
obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')
# Create an AutoUpdate Settings Object
obj_au_settings = obj_au.Settings
# Only change the setting if it's passed
if level is not None:
obj_au_settings.NotificationLevel = int(level)
result = obj_au_settings.Save()
if result is None:
ret['Level'] = level
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if recommended is not None:
obj_au_settings.IncludeRecommendedUpdates = recommended
result = obj_au_settings.Save()
if result is None:
ret['Recommended'] = recommended
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if featured is not None:
obj_au_settings.FeaturedUpdatesEnabled = featured
result = obj_au_settings.Save()
if result is None:
ret['Featured'] = featured
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if elevated is not None:
obj_au_settings.NonAdministratorsElevated = elevated
result = obj_au_settings.Save()
if result is None:
ret['Elevated'] = elevated
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if day is not None:
# Check that day is valid
days = {'Everyday': 0,
'Sunday': 1,
'Monday': 2,
'Tuesday': 3,
'Wednesday': 4,
'Thursday': 5,
'Friday': 6,
'Saturday': 7}
if day not in days:
ret['Comment'] = "Day needs to be one of the following: Everyday," \
"Monday, Tuesday, Wednesday, Thursday, Friday, " \
"Saturday"
ret['Success'] = False
else:
# Set the numeric equivalent for the day setting
obj_au_settings.ScheduledInstallationDay = days[day]
result = obj_au_settings.Save()
if result is None:
ret['Day'] = day
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if time is not None:
# Check for time as a string: if the time is not quoted, yaml will
# treat it as an integer
if not isinstance(time, six.string_types):
ret['Comment'] = "Time argument needs to be a string; it may need to"\
"be quoted. Passed {0}. Time not set.".format(time)
ret['Success'] = False
# Check for colon in the time
elif ':' not in time:
ret['Comment'] = "Time argument needs to be in 00:00 format." \
" Passed {0}. Time not set.".format(time)
ret['Success'] = False
else:
# Split the time by :
t = time.split(":")
# We only need the hours value
obj_au_settings.FeaturedUpdatesEnabled = t[0]
result = obj_au_settings.Save()
if result is None:
ret['Time'] = time
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if msupdate is not None:
# Microsoft Update requires special handling
# First load the MS Update Service Manager
with salt.utils.winapi.Com():
obj_sm = win32com.client.Dispatch('Microsoft.Update.ServiceManager')
# Give it a bogus name
obj_sm.ClientApplicationID = "My App"
if msupdate:
# msupdate is true, so add it to the services
try:
obj_sm.AddService2('7971f918-a847-4430-9279-4a52d1efe18d', 7, '')
ret['msupdate'] = msupdate
except Exception as error:
hr, msg, exc, arg = error.args # pylint: disable=W0633
# Consider checking for -2147024891 (0x80070005) Access Denied
ret['Comment'] = "Failed with failure code: {0}".format(exc[5])
ret['Success'] = False
else:
# msupdate is false, so remove it from the services
# check to see if the update is there or the RemoveService function
# will fail
if _get_msupdate_status():
# Service found, remove the service
try:
obj_sm.RemoveService('7971f918-a847-4430-9279-4a52d1efe18d')
ret['msupdate'] = msupdate
except Exception as error:
hr, msg, exc, arg = error.args # pylint: disable=W0633
# Consider checking for the following
# -2147024891 (0x80070005) Access Denied
# -2145091564 (0x80248014) Service Not Found (shouldn't get
# this with the check for _get_msupdate_status above
ret['Comment'] = "Failed with failure code: {0}".format(exc[5])
ret['Success'] = False
else:
ret['msupdate'] = msupdate
ret['Reboot'] = get_needs_reboot()
return ret | python | def set_wu_settings(level=None,
recommended=None,
featured=None,
elevated=None,
msupdate=None,
day=None,
time=None):
'''
Change Windows Update settings. If no parameters are passed, the current
value will be returned.
Supported:
- Windows Vista / Server 2008
- Windows 7 / Server 2008R2
- Windows 8 / Server 2012
- Windows 8.1 / Server 2012R2
.. note:
Microsoft began using the Unified Update Platform (UUP) starting with
Windows 10 / Server 2016. The Windows Update settings have changed and
the ability to 'Save' Windows Update settings has been removed. Windows
Update settings are read-only. See MSDN documentation:
https://msdn.microsoft.com/en-us/library/aa385829(v=vs.85).aspx
Args:
level (int):
Number from 1 to 4 indicating the update level:
1. Never check for updates
2. Check for updates but let me choose whether to download and install them
3. Download updates but let me choose whether to install them
4. Install updates automatically
recommended (bool):
Boolean value that indicates whether to include optional or
recommended updates when a search for updates and installation of
updates is performed.
featured (bool):
Boolean value that indicates whether to display notifications for
featured updates.
elevated (bool):
Boolean value that indicates whether non-administrators can perform
some update-related actions without administrator approval.
msupdate (bool):
Boolean value that indicates whether to turn on Microsoft Update for
other Microsoft products
day (str):
Days of the week on which Automatic Updates installs or uninstalls
updates. Accepted values:
- Everyday
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
time (str):
Time at which Automatic Updates installs or uninstalls updates. Must
be in the ##:## 24hr format, eg. 3:00 PM would be 15:00. Must be in
1 hour increments.
Returns:
dict: Returns a dictionary containing the results.
CLI Examples:
.. code-block:: bash
salt '*' win_wua.set_wu_settings level=4 recommended=True featured=False
'''
# The AutomaticUpdateSettings.Save() method used in this function does not
# work on Windows 10 / Server 2016. It is called in throughout this function
# like this:
#
# with salt.utils.winapi.Com():
# obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')
# obj_au_settings = obj_au.Settings
# obj_au_settings.Save()
#
# The `Save()` method reports success but doesn't actually change anything.
# Windows Update settings are read-only in Windows 10 / Server 2016. There's
# a little blurb on MSDN that mentions this, but gives no alternative for
# changing these settings in Windows 10 / Server 2016.
#
# https://msdn.microsoft.com/en-us/library/aa385829(v=vs.85).aspx
#
# Apparently the Windows Update framework in Windows Vista - Windows 8.1 has
# been changed quite a bit in Windows 10 / Server 2016. It is now called the
# Unified Update Platform (UUP). I haven't found an API or a Powershell
# commandlet for working with the the UUP. Perhaps there will be something
# forthcoming. The `win_lgpo` module might be an option for changing the
# Windows Update settings using local group policy.
ret = {'Success': True}
# Initialize the PyCom system
with salt.utils.winapi.Com():
# Create an AutoUpdate object
obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')
# Create an AutoUpdate Settings Object
obj_au_settings = obj_au.Settings
# Only change the setting if it's passed
if level is not None:
obj_au_settings.NotificationLevel = int(level)
result = obj_au_settings.Save()
if result is None:
ret['Level'] = level
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if recommended is not None:
obj_au_settings.IncludeRecommendedUpdates = recommended
result = obj_au_settings.Save()
if result is None:
ret['Recommended'] = recommended
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if featured is not None:
obj_au_settings.FeaturedUpdatesEnabled = featured
result = obj_au_settings.Save()
if result is None:
ret['Featured'] = featured
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if elevated is not None:
obj_au_settings.NonAdministratorsElevated = elevated
result = obj_au_settings.Save()
if result is None:
ret['Elevated'] = elevated
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if day is not None:
# Check that day is valid
days = {'Everyday': 0,
'Sunday': 1,
'Monday': 2,
'Tuesday': 3,
'Wednesday': 4,
'Thursday': 5,
'Friday': 6,
'Saturday': 7}
if day not in days:
ret['Comment'] = "Day needs to be one of the following: Everyday," \
"Monday, Tuesday, Wednesday, Thursday, Friday, " \
"Saturday"
ret['Success'] = False
else:
# Set the numeric equivalent for the day setting
obj_au_settings.ScheduledInstallationDay = days[day]
result = obj_au_settings.Save()
if result is None:
ret['Day'] = day
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if time is not None:
# Check for time as a string: if the time is not quoted, yaml will
# treat it as an integer
if not isinstance(time, six.string_types):
ret['Comment'] = "Time argument needs to be a string; it may need to"\
"be quoted. Passed {0}. Time not set.".format(time)
ret['Success'] = False
# Check for colon in the time
elif ':' not in time:
ret['Comment'] = "Time argument needs to be in 00:00 format." \
" Passed {0}. Time not set.".format(time)
ret['Success'] = False
else:
# Split the time by :
t = time.split(":")
# We only need the hours value
obj_au_settings.FeaturedUpdatesEnabled = t[0]
result = obj_au_settings.Save()
if result is None:
ret['Time'] = time
else:
ret['Comment'] = "Settings failed to save. Check permissions."
ret['Success'] = False
if msupdate is not None:
# Microsoft Update requires special handling
# First load the MS Update Service Manager
with salt.utils.winapi.Com():
obj_sm = win32com.client.Dispatch('Microsoft.Update.ServiceManager')
# Give it a bogus name
obj_sm.ClientApplicationID = "My App"
if msupdate:
# msupdate is true, so add it to the services
try:
obj_sm.AddService2('7971f918-a847-4430-9279-4a52d1efe18d', 7, '')
ret['msupdate'] = msupdate
except Exception as error:
hr, msg, exc, arg = error.args # pylint: disable=W0633
# Consider checking for -2147024891 (0x80070005) Access Denied
ret['Comment'] = "Failed with failure code: {0}".format(exc[5])
ret['Success'] = False
else:
# msupdate is false, so remove it from the services
# check to see if the update is there or the RemoveService function
# will fail
if _get_msupdate_status():
# Service found, remove the service
try:
obj_sm.RemoveService('7971f918-a847-4430-9279-4a52d1efe18d')
ret['msupdate'] = msupdate
except Exception as error:
hr, msg, exc, arg = error.args # pylint: disable=W0633
# Consider checking for the following
# -2147024891 (0x80070005) Access Denied
# -2145091564 (0x80248014) Service Not Found (shouldn't get
# this with the check for _get_msupdate_status above
ret['Comment'] = "Failed with failure code: {0}".format(exc[5])
ret['Success'] = False
else:
ret['msupdate'] = msupdate
ret['Reboot'] = get_needs_reboot()
return ret | [
"def",
"set_wu_settings",
"(",
"level",
"=",
"None",
",",
"recommended",
"=",
"None",
",",
"featured",
"=",
"None",
",",
"elevated",
"=",
"None",
",",
"msupdate",
"=",
"None",
",",
"day",
"=",
"None",
",",
"time",
"=",
"None",
")",
":",
"# The Automati... | Change Windows Update settings. If no parameters are passed, the current
value will be returned.
Supported:
- Windows Vista / Server 2008
- Windows 7 / Server 2008R2
- Windows 8 / Server 2012
- Windows 8.1 / Server 2012R2
.. note:
Microsoft began using the Unified Update Platform (UUP) starting with
Windows 10 / Server 2016. The Windows Update settings have changed and
the ability to 'Save' Windows Update settings has been removed. Windows
Update settings are read-only. See MSDN documentation:
https://msdn.microsoft.com/en-us/library/aa385829(v=vs.85).aspx
Args:
level (int):
Number from 1 to 4 indicating the update level:
1. Never check for updates
2. Check for updates but let me choose whether to download and install them
3. Download updates but let me choose whether to install them
4. Install updates automatically
recommended (bool):
Boolean value that indicates whether to include optional or
recommended updates when a search for updates and installation of
updates is performed.
featured (bool):
Boolean value that indicates whether to display notifications for
featured updates.
elevated (bool):
Boolean value that indicates whether non-administrators can perform
some update-related actions without administrator approval.
msupdate (bool):
Boolean value that indicates whether to turn on Microsoft Update for
other Microsoft products
day (str):
Days of the week on which Automatic Updates installs or uninstalls
updates. Accepted values:
- Everyday
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
time (str):
Time at which Automatic Updates installs or uninstalls updates. Must
be in the ##:## 24hr format, eg. 3:00 PM would be 15:00. Must be in
1 hour increments.
Returns:
dict: Returns a dictionary containing the results.
CLI Examples:
.. code-block:: bash
salt '*' win_wua.set_wu_settings level=4 recommended=True featured=False | [
"Change",
"Windows",
"Update",
"settings",
".",
"If",
"no",
"parameters",
"are",
"passed",
"the",
"current",
"value",
"will",
"be",
"returned",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wua.py#L625-L863 | train |
saltstack/salt | salt/modules/win_wua.py | get_wu_settings | def get_wu_settings():
'''
Get current Windows Update settings.
Returns:
dict: A dictionary of Windows Update settings:
Featured Updates:
Boolean value that indicates whether to display notifications for
featured updates.
Group Policy Required (Read-only):
Boolean value that indicates whether Group Policy requires the
Automatic Updates service.
Microsoft Update:
Boolean value that indicates whether to turn on Microsoft Update for
other Microsoft Products
Needs Reboot:
Boolean value that indicates whether the machine is in a reboot
pending state.
Non Admins Elevated:
Boolean value that indicates whether non-administrators can perform
some update-related actions without administrator approval.
Notification Level:
Number 1 to 4 indicating the update level:
1. Never check for updates
2. Check for updates but let me choose whether to download and
install them
3. Download updates but let me choose whether to install them
4. Install updates automatically
Read Only (Read-only):
Boolean value that indicates whether the Automatic Update
settings are read-only.
Recommended Updates:
Boolean value that indicates whether to include optional or
recommended updates when a search for updates and installation of
updates is performed.
Scheduled Day:
Days of the week on which Automatic Updates installs or uninstalls
updates.
Scheduled Time:
Time at which Automatic Updates installs or uninstalls updates.
CLI Examples:
.. code-block:: bash
salt '*' win_wua.get_wu_settings
'''
ret = {}
day = ['Every Day',
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday']
# Initialize the PyCom system
with salt.utils.winapi.Com():
# Create an AutoUpdate object
obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')
# Create an AutoUpdate Settings Object
obj_au_settings = obj_au.Settings
# Populate the return dictionary
ret['Featured Updates'] = obj_au_settings.FeaturedUpdatesEnabled
ret['Group Policy Required'] = obj_au_settings.Required
ret['Microsoft Update'] = _get_msupdate_status()
ret['Needs Reboot'] = get_needs_reboot()
ret['Non Admins Elevated'] = obj_au_settings.NonAdministratorsElevated
ret['Notification Level'] = obj_au_settings.NotificationLevel
ret['Read Only'] = obj_au_settings.ReadOnly
ret['Recommended Updates'] = obj_au_settings.IncludeRecommendedUpdates
ret['Scheduled Day'] = day[obj_au_settings.ScheduledInstallationDay]
# Scheduled Installation Time requires special handling to return the time
# in the right format
if obj_au_settings.ScheduledInstallationTime < 10:
ret['Scheduled Time'] = '0{0}:00'.\
format(obj_au_settings.ScheduledInstallationTime)
else:
ret['Scheduled Time'] = '{0}:00'.\
format(obj_au_settings.ScheduledInstallationTime)
return ret | python | def get_wu_settings():
'''
Get current Windows Update settings.
Returns:
dict: A dictionary of Windows Update settings:
Featured Updates:
Boolean value that indicates whether to display notifications for
featured updates.
Group Policy Required (Read-only):
Boolean value that indicates whether Group Policy requires the
Automatic Updates service.
Microsoft Update:
Boolean value that indicates whether to turn on Microsoft Update for
other Microsoft Products
Needs Reboot:
Boolean value that indicates whether the machine is in a reboot
pending state.
Non Admins Elevated:
Boolean value that indicates whether non-administrators can perform
some update-related actions without administrator approval.
Notification Level:
Number 1 to 4 indicating the update level:
1. Never check for updates
2. Check for updates but let me choose whether to download and
install them
3. Download updates but let me choose whether to install them
4. Install updates automatically
Read Only (Read-only):
Boolean value that indicates whether the Automatic Update
settings are read-only.
Recommended Updates:
Boolean value that indicates whether to include optional or
recommended updates when a search for updates and installation of
updates is performed.
Scheduled Day:
Days of the week on which Automatic Updates installs or uninstalls
updates.
Scheduled Time:
Time at which Automatic Updates installs or uninstalls updates.
CLI Examples:
.. code-block:: bash
salt '*' win_wua.get_wu_settings
'''
ret = {}
day = ['Every Day',
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday']
# Initialize the PyCom system
with salt.utils.winapi.Com():
# Create an AutoUpdate object
obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')
# Create an AutoUpdate Settings Object
obj_au_settings = obj_au.Settings
# Populate the return dictionary
ret['Featured Updates'] = obj_au_settings.FeaturedUpdatesEnabled
ret['Group Policy Required'] = obj_au_settings.Required
ret['Microsoft Update'] = _get_msupdate_status()
ret['Needs Reboot'] = get_needs_reboot()
ret['Non Admins Elevated'] = obj_au_settings.NonAdministratorsElevated
ret['Notification Level'] = obj_au_settings.NotificationLevel
ret['Read Only'] = obj_au_settings.ReadOnly
ret['Recommended Updates'] = obj_au_settings.IncludeRecommendedUpdates
ret['Scheduled Day'] = day[obj_au_settings.ScheduledInstallationDay]
# Scheduled Installation Time requires special handling to return the time
# in the right format
if obj_au_settings.ScheduledInstallationTime < 10:
ret['Scheduled Time'] = '0{0}:00'.\
format(obj_au_settings.ScheduledInstallationTime)
else:
ret['Scheduled Time'] = '{0}:00'.\
format(obj_au_settings.ScheduledInstallationTime)
return ret | [
"def",
"get_wu_settings",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"day",
"=",
"[",
"'Every Day'",
",",
"'Sunday'",
",",
"'Monday'",
",",
"'Tuesday'",
",",
"'Wednesday'",
",",
"'Thursday'",
",",
"'Friday'",
",",
"'Saturday'",
"]",
"# Initialize the PyCom system",
... | Get current Windows Update settings.
Returns:
dict: A dictionary of Windows Update settings:
Featured Updates:
Boolean value that indicates whether to display notifications for
featured updates.
Group Policy Required (Read-only):
Boolean value that indicates whether Group Policy requires the
Automatic Updates service.
Microsoft Update:
Boolean value that indicates whether to turn on Microsoft Update for
other Microsoft Products
Needs Reboot:
Boolean value that indicates whether the machine is in a reboot
pending state.
Non Admins Elevated:
Boolean value that indicates whether non-administrators can perform
some update-related actions without administrator approval.
Notification Level:
Number 1 to 4 indicating the update level:
1. Never check for updates
2. Check for updates but let me choose whether to download and
install them
3. Download updates but let me choose whether to install them
4. Install updates automatically
Read Only (Read-only):
Boolean value that indicates whether the Automatic Update
settings are read-only.
Recommended Updates:
Boolean value that indicates whether to include optional or
recommended updates when a search for updates and installation of
updates is performed.
Scheduled Day:
Days of the week on which Automatic Updates installs or uninstalls
updates.
Scheduled Time:
Time at which Automatic Updates installs or uninstalls updates.
CLI Examples:
.. code-block:: bash
salt '*' win_wua.get_wu_settings | [
"Get",
"current",
"Windows",
"Update",
"settings",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wua.py#L866-L953 | train |
saltstack/salt | salt/modules/win_wua.py | _get_msupdate_status | def _get_msupdate_status():
'''
Check to see if Microsoft Update is Enabled
Return Boolean
'''
# To get the status of Microsoft Update we actually have to check the
# Microsoft Update Service Manager
# Initialize the PyCom system
with salt.utils.winapi.Com():
# Create a ServiceManager Object
obj_sm = win32com.client.Dispatch('Microsoft.Update.ServiceManager')
# Return a collection of loaded Services
col_services = obj_sm.Services
# Loop through the collection to find the Microsoft Udpate Service
# If it exists return True otherwise False
for service in col_services:
if service.name == 'Microsoft Update':
return True
return False | python | def _get_msupdate_status():
'''
Check to see if Microsoft Update is Enabled
Return Boolean
'''
# To get the status of Microsoft Update we actually have to check the
# Microsoft Update Service Manager
# Initialize the PyCom system
with salt.utils.winapi.Com():
# Create a ServiceManager Object
obj_sm = win32com.client.Dispatch('Microsoft.Update.ServiceManager')
# Return a collection of loaded Services
col_services = obj_sm.Services
# Loop through the collection to find the Microsoft Udpate Service
# If it exists return True otherwise False
for service in col_services:
if service.name == 'Microsoft Update':
return True
return False | [
"def",
"_get_msupdate_status",
"(",
")",
":",
"# To get the status of Microsoft Update we actually have to check the",
"# Microsoft Update Service Manager",
"# Initialize the PyCom system",
"with",
"salt",
".",
"utils",
".",
"winapi",
".",
"Com",
"(",
")",
":",
"# Create a Serv... | Check to see if Microsoft Update is Enabled
Return Boolean | [
"Check",
"to",
"see",
"if",
"Microsoft",
"Update",
"is",
"Enabled",
"Return",
"Boolean"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_wua.py#L956-L977 | train |
saltstack/salt | salt/modules/boto_s3.py | get_object_metadata | def get_object_metadata(
name,
extra_args=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Get metadata about an S3 object.
Returns None if the object does not exist.
You can pass AWS SSE-C related args and/or RequestPayer in extra_args.
CLI Example:
.. code-block:: bash
salt myminion boto_s3.get_object_metadata \\
my_bucket/path/to/object \\
region=us-east-1 \\
key=key \\
keyid=keyid \\
profile=profile \\
'''
bucket, _, s3_key = name.partition('/')
if extra_args is None:
extra_args = {}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
metadata = conn.head_object(
Bucket=bucket,
Key=s3_key,
**extra_args
)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Message'] == 'Not Found':
return {'result': None}
return {'error': __utils__['boto3.get_error'](e)}
return {'result': metadata} | python | def get_object_metadata(
name,
extra_args=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Get metadata about an S3 object.
Returns None if the object does not exist.
You can pass AWS SSE-C related args and/or RequestPayer in extra_args.
CLI Example:
.. code-block:: bash
salt myminion boto_s3.get_object_metadata \\
my_bucket/path/to/object \\
region=us-east-1 \\
key=key \\
keyid=keyid \\
profile=profile \\
'''
bucket, _, s3_key = name.partition('/')
if extra_args is None:
extra_args = {}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
metadata = conn.head_object(
Bucket=bucket,
Key=s3_key,
**extra_args
)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Message'] == 'Not Found':
return {'result': None}
return {'error': __utils__['boto3.get_error'](e)}
return {'result': metadata} | [
"def",
"get_object_metadata",
"(",
"name",
",",
"extra_args",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
")",
":",
"bucket",
",",
"_",
",",
"s3_key",
"=",
"name",
"... | Get metadata about an S3 object.
Returns None if the object does not exist.
You can pass AWS SSE-C related args and/or RequestPayer in extra_args.
CLI Example:
.. code-block:: bash
salt myminion boto_s3.get_object_metadata \\
my_bucket/path/to/object \\
region=us-east-1 \\
key=key \\
keyid=keyid \\
profile=profile \\ | [
"Get",
"metadata",
"about",
"an",
"S3",
"object",
".",
"Returns",
"None",
"if",
"the",
"object",
"does",
"not",
"exist",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3.py#L90-L132 | train |
saltstack/salt | salt/modules/boto_s3.py | upload_file | def upload_file(
source,
name,
extra_args=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Upload a local file as an S3 object.
CLI Example:
.. code-block:: bash
salt myminion boto_s3.upload_file \\
/path/to/local/file \\
my_bucket/path/to/object \\
region=us-east-1 \\
key=key \\
keyid=keyid \\
profile=profile \\
'''
bucket, _, s3_key = name.partition('/')
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
conn.upload_file(source, bucket, s3_key, ExtraArgs=extra_args)
except boto3.exceptions.S3UploadFailedError as e:
return {'error': __utils__['boto3.get_error'](e)}
log.info('S3 object uploaded to %s', name)
return {'result': True} | python | def upload_file(
source,
name,
extra_args=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Upload a local file as an S3 object.
CLI Example:
.. code-block:: bash
salt myminion boto_s3.upload_file \\
/path/to/local/file \\
my_bucket/path/to/object \\
region=us-east-1 \\
key=key \\
keyid=keyid \\
profile=profile \\
'''
bucket, _, s3_key = name.partition('/')
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
conn.upload_file(source, bucket, s3_key, ExtraArgs=extra_args)
except boto3.exceptions.S3UploadFailedError as e:
return {'error': __utils__['boto3.get_error'](e)}
log.info('S3 object uploaded to %s', name)
return {'result': True} | [
"def",
"upload_file",
"(",
"source",
",",
"name",
",",
"extra_args",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
")",
":",
"bucket",
",",
"_",
",",
"s3_key",
"=",
... | Upload a local file as an S3 object.
CLI Example:
.. code-block:: bash
salt myminion boto_s3.upload_file \\
/path/to/local/file \\
my_bucket/path/to/object \\
region=us-east-1 \\
key=key \\
keyid=keyid \\
profile=profile \\ | [
"Upload",
"a",
"local",
"file",
"as",
"an",
"S3",
"object",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3.py#L135-L169 | train |
saltstack/salt | salt/utils/profile.py | profile_func | def profile_func(filename=None):
'''
Decorator for adding profiling to a nested function in Salt
'''
def proffunc(fun):
def profiled_func(*args, **kwargs):
logging.info('Profiling function %s', fun.__name__)
try:
profiler = cProfile.Profile()
retval = profiler.runcall(fun, *args, **kwargs)
profiler.dump_stats((filename or '{0}_func.profile'
.format(fun.__name__)))
except IOError:
logging.exception('Could not open profile file %s', filename)
return retval
return profiled_func
return proffunc | python | def profile_func(filename=None):
'''
Decorator for adding profiling to a nested function in Salt
'''
def proffunc(fun):
def profiled_func(*args, **kwargs):
logging.info('Profiling function %s', fun.__name__)
try:
profiler = cProfile.Profile()
retval = profiler.runcall(fun, *args, **kwargs)
profiler.dump_stats((filename or '{0}_func.profile'
.format(fun.__name__)))
except IOError:
logging.exception('Could not open profile file %s', filename)
return retval
return profiled_func
return proffunc | [
"def",
"profile_func",
"(",
"filename",
"=",
"None",
")",
":",
"def",
"proffunc",
"(",
"fun",
")",
":",
"def",
"profiled_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logging",
".",
"info",
"(",
"'Profiling function %s'",
",",
"fun",
"."... | Decorator for adding profiling to a nested function in Salt | [
"Decorator",
"for",
"adding",
"profiling",
"to",
"a",
"nested",
"function",
"in",
"Salt"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/profile.py#L30-L47 | train |
saltstack/salt | salt/modules/djangomod.py | _get_django_admin | def _get_django_admin(bin_env):
'''
Return the django admin
'''
if not bin_env:
if salt.utils.path.which('django-admin.py'):
return 'django-admin.py'
elif salt.utils.path.which('django-admin'):
return 'django-admin'
else:
raise salt.exceptions.CommandExecutionError(
"django-admin or django-admin.py not found on PATH")
# try to get django-admin.py bin from env
if os.path.exists(os.path.join(bin_env, 'bin', 'django-admin.py')):
return os.path.join(bin_env, 'bin', 'django-admin.py')
return bin_env | python | def _get_django_admin(bin_env):
'''
Return the django admin
'''
if not bin_env:
if salt.utils.path.which('django-admin.py'):
return 'django-admin.py'
elif salt.utils.path.which('django-admin'):
return 'django-admin'
else:
raise salt.exceptions.CommandExecutionError(
"django-admin or django-admin.py not found on PATH")
# try to get django-admin.py bin from env
if os.path.exists(os.path.join(bin_env, 'bin', 'django-admin.py')):
return os.path.join(bin_env, 'bin', 'django-admin.py')
return bin_env | [
"def",
"_get_django_admin",
"(",
"bin_env",
")",
":",
"if",
"not",
"bin_env",
":",
"if",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'django-admin.py'",
")",
":",
"return",
"'django-admin.py'",
"elif",
"salt",
".",
"utils",
".",
"path",
".",
"... | Return the django admin | [
"Return",
"the",
"django",
"admin"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/djangomod.py#L26-L42 | train |
saltstack/salt | salt/modules/djangomod.py | command | def command(settings_module,
command,
bin_env=None,
pythonpath=None,
env=None,
runas=None,
*args, **kwargs):
'''
Run arbitrary django management command
CLI Example:
.. code-block:: bash
salt '*' django.command <settings_module> <command>
'''
dja = _get_django_admin(bin_env)
cmd = '{0} {1} --settings={2}'.format(dja, command, settings_module)
if pythonpath:
cmd = '{0} --pythonpath={1}'.format(cmd, pythonpath)
for arg in args:
cmd = '{0} --{1}'.format(cmd, arg)
for key, value in six.iteritems(kwargs):
if not key.startswith('__'):
cmd = '{0} --{1}={2}'.format(cmd, key, value)
return __salt__['cmd.run'](cmd, env=env, runas=runas, python_shell=False) | python | def command(settings_module,
command,
bin_env=None,
pythonpath=None,
env=None,
runas=None,
*args, **kwargs):
'''
Run arbitrary django management command
CLI Example:
.. code-block:: bash
salt '*' django.command <settings_module> <command>
'''
dja = _get_django_admin(bin_env)
cmd = '{0} {1} --settings={2}'.format(dja, command, settings_module)
if pythonpath:
cmd = '{0} --pythonpath={1}'.format(cmd, pythonpath)
for arg in args:
cmd = '{0} --{1}'.format(cmd, arg)
for key, value in six.iteritems(kwargs):
if not key.startswith('__'):
cmd = '{0} --{1}={2}'.format(cmd, key, value)
return __salt__['cmd.run'](cmd, env=env, runas=runas, python_shell=False) | [
"def",
"command",
"(",
"settings_module",
",",
"command",
",",
"bin_env",
"=",
"None",
",",
"pythonpath",
"=",
"None",
",",
"env",
"=",
"None",
",",
"runas",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dja",
"=",
"_get_django_a... | Run arbitrary django management command
CLI Example:
.. code-block:: bash
salt '*' django.command <settings_module> <command> | [
"Run",
"arbitrary",
"django",
"management",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/djangomod.py#L45-L73 | train |
saltstack/salt | salt/modules/djangomod.py | syncdb | def syncdb(settings_module,
bin_env=None,
migrate=False,
database=None,
pythonpath=None,
env=None,
noinput=True,
runas=None):
'''
Run syncdb
Execute the Django-Admin syncdb command, if South is available on the
minion the ``migrate`` option can be passed as ``True`` calling the
migrations to run after the syncdb completes
NOTE: The syncdb command was deprecated in Django 1.7 and removed in Django 1.9.
For Django versions 1.9 or higher use the `migrate` command instead.
CLI Example:
.. code-block:: bash
salt '*' django.syncdb <settings_module>
'''
args = []
kwargs = {}
if migrate:
args.append('migrate')
if database:
kwargs['database'] = database
if noinput:
args.append('noinput')
return command(settings_module,
'syncdb',
bin_env,
pythonpath,
env,
runas,
*args, **kwargs) | python | def syncdb(settings_module,
bin_env=None,
migrate=False,
database=None,
pythonpath=None,
env=None,
noinput=True,
runas=None):
'''
Run syncdb
Execute the Django-Admin syncdb command, if South is available on the
minion the ``migrate`` option can be passed as ``True`` calling the
migrations to run after the syncdb completes
NOTE: The syncdb command was deprecated in Django 1.7 and removed in Django 1.9.
For Django versions 1.9 or higher use the `migrate` command instead.
CLI Example:
.. code-block:: bash
salt '*' django.syncdb <settings_module>
'''
args = []
kwargs = {}
if migrate:
args.append('migrate')
if database:
kwargs['database'] = database
if noinput:
args.append('noinput')
return command(settings_module,
'syncdb',
bin_env,
pythonpath,
env,
runas,
*args, **kwargs) | [
"def",
"syncdb",
"(",
"settings_module",
",",
"bin_env",
"=",
"None",
",",
"migrate",
"=",
"False",
",",
"database",
"=",
"None",
",",
"pythonpath",
"=",
"None",
",",
"env",
"=",
"None",
",",
"noinput",
"=",
"True",
",",
"runas",
"=",
"None",
")",
":... | Run syncdb
Execute the Django-Admin syncdb command, if South is available on the
minion the ``migrate`` option can be passed as ``True`` calling the
migrations to run after the syncdb completes
NOTE: The syncdb command was deprecated in Django 1.7 and removed in Django 1.9.
For Django versions 1.9 or higher use the `migrate` command instead.
CLI Example:
.. code-block:: bash
salt '*' django.syncdb <settings_module> | [
"Run",
"syncdb"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/djangomod.py#L76-L115 | train |
saltstack/salt | salt/modules/djangomod.py | migrate | def migrate(settings_module,
app_label=None,
migration_name=None,
bin_env=None,
database=None,
pythonpath=None,
env=None,
noinput=True,
runas=None):
'''
Run migrate
Execute the Django-Admin migrate command (requires Django 1.7 or higher).
.. versionadded:: Neon
settings_module
Specifies the settings module to use.
The settings module should be in Python package syntax, e.g. mysite.settings.
If this isn’t provided, django-admin will use the DJANGO_SETTINGS_MODULE
environment variable.
app_label
Specific app to run migrations for, instead of all apps.
This may involve running other apps’ migrations too, due to dependencies.
migration_name
Named migration to be applied to a specific app.
Brings the database schema to a state where the named migration is applied,
but no later migrations in the same app are applied. This may involve
unapplying migrations if you have previously migrated past the named migration.
Use the name zero to unapply all migrations for an app.
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
database
Database to migrate. Defaults to 'default'.
pythonpath
Adds the given filesystem path to the Python import search path.
If this isn’t provided, django-admin will use the PYTHONPATH environment variable.
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
module.run:
- name: django.migrate
- settings_module: my_django_app.settings
- env:
- DATABASE_USER: 'mydbuser'
noinput
Suppresses all user prompts. Defaults to True.
runas
The user name to run the command as.
CLI Example:
.. code-block:: bash
salt '*' django.migrate <settings_module>
salt '*' django.migrate <settings_module> <app_label>
salt '*' django.migrate <settings_module> <app_label> <migration_name>
'''
args = []
kwargs = {}
if database:
kwargs['database'] = database
if noinput:
args.append('noinput')
if app_label and migration_name:
cmd = "migrate {0} {1}".format(app_label, migration_name)
elif app_label:
cmd = "migrate {0}".format(app_label)
else:
cmd = 'migrate'
return command(settings_module,
cmd,
bin_env,
pythonpath,
env,
runas,
*args, **kwargs) | python | def migrate(settings_module,
app_label=None,
migration_name=None,
bin_env=None,
database=None,
pythonpath=None,
env=None,
noinput=True,
runas=None):
'''
Run migrate
Execute the Django-Admin migrate command (requires Django 1.7 or higher).
.. versionadded:: Neon
settings_module
Specifies the settings module to use.
The settings module should be in Python package syntax, e.g. mysite.settings.
If this isn’t provided, django-admin will use the DJANGO_SETTINGS_MODULE
environment variable.
app_label
Specific app to run migrations for, instead of all apps.
This may involve running other apps’ migrations too, due to dependencies.
migration_name
Named migration to be applied to a specific app.
Brings the database schema to a state where the named migration is applied,
but no later migrations in the same app are applied. This may involve
unapplying migrations if you have previously migrated past the named migration.
Use the name zero to unapply all migrations for an app.
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
database
Database to migrate. Defaults to 'default'.
pythonpath
Adds the given filesystem path to the Python import search path.
If this isn’t provided, django-admin will use the PYTHONPATH environment variable.
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
module.run:
- name: django.migrate
- settings_module: my_django_app.settings
- env:
- DATABASE_USER: 'mydbuser'
noinput
Suppresses all user prompts. Defaults to True.
runas
The user name to run the command as.
CLI Example:
.. code-block:: bash
salt '*' django.migrate <settings_module>
salt '*' django.migrate <settings_module> <app_label>
salt '*' django.migrate <settings_module> <app_label> <migration_name>
'''
args = []
kwargs = {}
if database:
kwargs['database'] = database
if noinput:
args.append('noinput')
if app_label and migration_name:
cmd = "migrate {0} {1}".format(app_label, migration_name)
elif app_label:
cmd = "migrate {0}".format(app_label)
else:
cmd = 'migrate'
return command(settings_module,
cmd,
bin_env,
pythonpath,
env,
runas,
*args, **kwargs) | [
"def",
"migrate",
"(",
"settings_module",
",",
"app_label",
"=",
"None",
",",
"migration_name",
"=",
"None",
",",
"bin_env",
"=",
"None",
",",
"database",
"=",
"None",
",",
"pythonpath",
"=",
"None",
",",
"env",
"=",
"None",
",",
"noinput",
"=",
"True",
... | Run migrate
Execute the Django-Admin migrate command (requires Django 1.7 or higher).
.. versionadded:: Neon
settings_module
Specifies the settings module to use.
The settings module should be in Python package syntax, e.g. mysite.settings.
If this isn’t provided, django-admin will use the DJANGO_SETTINGS_MODULE
environment variable.
app_label
Specific app to run migrations for, instead of all apps.
This may involve running other apps’ migrations too, due to dependencies.
migration_name
Named migration to be applied to a specific app.
Brings the database schema to a state where the named migration is applied,
but no later migrations in the same app are applied. This may involve
unapplying migrations if you have previously migrated past the named migration.
Use the name zero to unapply all migrations for an app.
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
database
Database to migrate. Defaults to 'default'.
pythonpath
Adds the given filesystem path to the Python import search path.
If this isn’t provided, django-admin will use the PYTHONPATH environment variable.
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
module.run:
- name: django.migrate
- settings_module: my_django_app.settings
- env:
- DATABASE_USER: 'mydbuser'
noinput
Suppresses all user prompts. Defaults to True.
runas
The user name to run the command as.
CLI Example:
.. code-block:: bash
salt '*' django.migrate <settings_module>
salt '*' django.migrate <settings_module> <app_label>
salt '*' django.migrate <settings_module> <app_label> <migration_name> | [
"Run",
"migrate"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/djangomod.py#L118-L211 | train |
saltstack/salt | salt/modules/djangomod.py | createsuperuser | def createsuperuser(settings_module,
username,
email,
bin_env=None,
database=None,
pythonpath=None,
env=None,
runas=None):
'''
Create a super user for the database.
This function defaults to use the ``--noinput`` flag which prevents the
creation of a password for the superuser.
CLI Example:
.. code-block:: bash
salt '*' django.createsuperuser <settings_module> user user@example.com
'''
args = ['noinput']
kwargs = dict(
email=email,
username=username,
)
if database:
kwargs['database'] = database
return command(settings_module,
'createsuperuser',
bin_env,
pythonpath,
env,
runas,
*args, **kwargs) | python | def createsuperuser(settings_module,
username,
email,
bin_env=None,
database=None,
pythonpath=None,
env=None,
runas=None):
'''
Create a super user for the database.
This function defaults to use the ``--noinput`` flag which prevents the
creation of a password for the superuser.
CLI Example:
.. code-block:: bash
salt '*' django.createsuperuser <settings_module> user user@example.com
'''
args = ['noinput']
kwargs = dict(
email=email,
username=username,
)
if database:
kwargs['database'] = database
return command(settings_module,
'createsuperuser',
bin_env,
pythonpath,
env,
runas,
*args, **kwargs) | [
"def",
"createsuperuser",
"(",
"settings_module",
",",
"username",
",",
"email",
",",
"bin_env",
"=",
"None",
",",
"database",
"=",
"None",
",",
"pythonpath",
"=",
"None",
",",
"env",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"args",
"=",
"[",
... | Create a super user for the database.
This function defaults to use the ``--noinput`` flag which prevents the
creation of a password for the superuser.
CLI Example:
.. code-block:: bash
salt '*' django.createsuperuser <settings_module> user user@example.com | [
"Create",
"a",
"super",
"user",
"for",
"the",
"database",
".",
"This",
"function",
"defaults",
"to",
"use",
"the",
"--",
"noinput",
"flag",
"which",
"prevents",
"the",
"creation",
"of",
"a",
"password",
"for",
"the",
"superuser",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/djangomod.py#L214-L246 | train |
saltstack/salt | salt/modules/djangomod.py | loaddata | def loaddata(settings_module,
fixtures,
bin_env=None,
database=None,
pythonpath=None,
env=None):
'''
Load fixture data
Fixtures:
comma separated list of fixtures to load
CLI Example:
.. code-block:: bash
salt '*' django.loaddata <settings_module> <comma delimited list of fixtures>
'''
args = []
kwargs = {}
if database:
kwargs['database'] = database
cmd = '{0} {1}'.format('loaddata', ' '.join(fixtures.split(',')))
return command(settings_module,
cmd,
bin_env,
pythonpath,
env,
*args, **kwargs) | python | def loaddata(settings_module,
fixtures,
bin_env=None,
database=None,
pythonpath=None,
env=None):
'''
Load fixture data
Fixtures:
comma separated list of fixtures to load
CLI Example:
.. code-block:: bash
salt '*' django.loaddata <settings_module> <comma delimited list of fixtures>
'''
args = []
kwargs = {}
if database:
kwargs['database'] = database
cmd = '{0} {1}'.format('loaddata', ' '.join(fixtures.split(',')))
return command(settings_module,
cmd,
bin_env,
pythonpath,
env,
*args, **kwargs) | [
"def",
"loaddata",
"(",
"settings_module",
",",
"fixtures",
",",
"bin_env",
"=",
"None",
",",
"database",
"=",
"None",
",",
"pythonpath",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"args",
"=",
"[",
"]",
"kwargs",
"=",
"{",
"}",
"if",
"database"... | Load fixture data
Fixtures:
comma separated list of fixtures to load
CLI Example:
.. code-block:: bash
salt '*' django.loaddata <settings_module> <comma delimited list of fixtures> | [
"Load",
"fixture",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/djangomod.py#L249-L280 | train |
saltstack/salt | salt/modules/djangomod.py | collectstatic | def collectstatic(settings_module,
bin_env=None,
no_post_process=False,
ignore=None,
dry_run=False,
clear=False,
link=False,
no_default_ignore=False,
pythonpath=None,
env=None,
runas=None):
'''
Collect static files from each of your applications into a single location
that can easily be served in production.
CLI Example:
.. code-block:: bash
salt '*' django.collectstatic <settings_module>
'''
args = ['noinput']
kwargs = {}
if no_post_process:
args.append('no-post-process')
if ignore:
kwargs['ignore'] = ignore
if dry_run:
args.append('dry-run')
if clear:
args.append('clear')
if link:
args.append('link')
if no_default_ignore:
args.append('no-default-ignore')
return command(settings_module,
'collectstatic',
bin_env,
pythonpath,
env,
runas,
*args, **kwargs) | python | def collectstatic(settings_module,
bin_env=None,
no_post_process=False,
ignore=None,
dry_run=False,
clear=False,
link=False,
no_default_ignore=False,
pythonpath=None,
env=None,
runas=None):
'''
Collect static files from each of your applications into a single location
that can easily be served in production.
CLI Example:
.. code-block:: bash
salt '*' django.collectstatic <settings_module>
'''
args = ['noinput']
kwargs = {}
if no_post_process:
args.append('no-post-process')
if ignore:
kwargs['ignore'] = ignore
if dry_run:
args.append('dry-run')
if clear:
args.append('clear')
if link:
args.append('link')
if no_default_ignore:
args.append('no-default-ignore')
return command(settings_module,
'collectstatic',
bin_env,
pythonpath,
env,
runas,
*args, **kwargs) | [
"def",
"collectstatic",
"(",
"settings_module",
",",
"bin_env",
"=",
"None",
",",
"no_post_process",
"=",
"False",
",",
"ignore",
"=",
"None",
",",
"dry_run",
"=",
"False",
",",
"clear",
"=",
"False",
",",
"link",
"=",
"False",
",",
"no_default_ignore",
"=... | Collect static files from each of your applications into a single location
that can easily be served in production.
CLI Example:
.. code-block:: bash
salt '*' django.collectstatic <settings_module> | [
"Collect",
"static",
"files",
"from",
"each",
"of",
"your",
"applications",
"into",
"a",
"single",
"location",
"that",
"can",
"easily",
"be",
"served",
"in",
"production",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/djangomod.py#L283-L325 | train |
saltstack/salt | salt/states/postgres_default_privileges.py | present | def present(name,
object_name,
object_type,
defprivileges=None,
grant_option=None,
prepend='public',
maintenance_db=None,
user=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Grant the requested privilege(s) on the specified object to a role
name
Name of the role to which privileges should be granted
object_name
Name of the object on which the grant is to be performed.
'ALL' may be used for objects of type 'table' or 'sequence'.
object_type
The object type, which can be one of the following:
- table
- sequence
- schema
- group
- function
View permissions should specify `object_type: table`.
privileges
List of privileges to grant, from the list below:
- INSERT
- CREATE
- TRUNCATE
- CONNECT
- TRIGGER
- SELECT
- USAGE
- TEMPORARY
- UPDATE
- EXECUTE
- REFERENCES
- DELETE
- ALL
:note: privileges should not be set when granting group membership
grant_option
If grant_option is set to True, the recipient of the privilege can
in turn grant it to others
prepend
Table and Sequence object types live under a schema so this should be
provided if the object is not under the default `public` schema
maintenance_db
The name of the database in which the language is to be installed
user
System user all operations should be performed on behalf of
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': 'The requested default privilege(s) are already set'
}
defprivileges = ','.join(defprivileges) if defprivileges else None
kwargs = {
'defprivileges': defprivileges,
'grant_option': grant_option,
'prepend': prepend,
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
if not __salt__['postgres.has_default_privileges'](
name, object_name, object_type, **kwargs):
_defprivs = object_name if object_type == 'group' else defprivileges
if __opts__['test']:
ret['result'] = None
ret['comment'] = ('The default privilege(s): {0} are'
' set to be granted to {1}').format(_defprivs, name)
return ret
if __salt__['postgres.default_privileges_grant'](
name, object_name, object_type, **kwargs):
ret['comment'] = ('The default privilege(s): {0} have '
'been granted to {1}').format(_defprivs, name)
ret['changes'][name] = 'Present'
else:
ret['comment'] = ('Failed to grant default privilege(s):'
' {0} to {1}').format(_defprivs, name)
ret['result'] = False
return ret | python | def present(name,
object_name,
object_type,
defprivileges=None,
grant_option=None,
prepend='public',
maintenance_db=None,
user=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Grant the requested privilege(s) on the specified object to a role
name
Name of the role to which privileges should be granted
object_name
Name of the object on which the grant is to be performed.
'ALL' may be used for objects of type 'table' or 'sequence'.
object_type
The object type, which can be one of the following:
- table
- sequence
- schema
- group
- function
View permissions should specify `object_type: table`.
privileges
List of privileges to grant, from the list below:
- INSERT
- CREATE
- TRUNCATE
- CONNECT
- TRIGGER
- SELECT
- USAGE
- TEMPORARY
- UPDATE
- EXECUTE
- REFERENCES
- DELETE
- ALL
:note: privileges should not be set when granting group membership
grant_option
If grant_option is set to True, the recipient of the privilege can
in turn grant it to others
prepend
Table and Sequence object types live under a schema so this should be
provided if the object is not under the default `public` schema
maintenance_db
The name of the database in which the language is to be installed
user
System user all operations should be performed on behalf of
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': 'The requested default privilege(s) are already set'
}
defprivileges = ','.join(defprivileges) if defprivileges else None
kwargs = {
'defprivileges': defprivileges,
'grant_option': grant_option,
'prepend': prepend,
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
if not __salt__['postgres.has_default_privileges'](
name, object_name, object_type, **kwargs):
_defprivs = object_name if object_type == 'group' else defprivileges
if __opts__['test']:
ret['result'] = None
ret['comment'] = ('The default privilege(s): {0} are'
' set to be granted to {1}').format(_defprivs, name)
return ret
if __salt__['postgres.default_privileges_grant'](
name, object_name, object_type, **kwargs):
ret['comment'] = ('The default privilege(s): {0} have '
'been granted to {1}').format(_defprivs, name)
ret['changes'][name] = 'Present'
else:
ret['comment'] = ('Failed to grant default privilege(s):'
' {0} to {1}').format(_defprivs, name)
ret['result'] = False
return ret | [
"def",
"present",
"(",
"name",
",",
"object_name",
",",
"object_type",
",",
"defprivileges",
"=",
"None",
",",
"grant_option",
"=",
"None",
",",
"prepend",
"=",
"'public'",
",",
"maintenance_db",
"=",
"None",
",",
"user",
"=",
"None",
",",
"db_password",
"... | Grant the requested privilege(s) on the specified object to a role
name
Name of the role to which privileges should be granted
object_name
Name of the object on which the grant is to be performed.
'ALL' may be used for objects of type 'table' or 'sequence'.
object_type
The object type, which can be one of the following:
- table
- sequence
- schema
- group
- function
View permissions should specify `object_type: table`.
privileges
List of privileges to grant, from the list below:
- INSERT
- CREATE
- TRUNCATE
- CONNECT
- TRIGGER
- SELECT
- USAGE
- TEMPORARY
- UPDATE
- EXECUTE
- REFERENCES
- DELETE
- ALL
:note: privileges should not be set when granting group membership
grant_option
If grant_option is set to True, the recipient of the privilege can
in turn grant it to others
prepend
Table and Sequence object types live under a schema so this should be
provided if the object is not under the default `public` schema
maintenance_db
The name of the database in which the language is to be installed
user
System user all operations should be performed on behalf of
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 | [
"Grant",
"the",
"requested",
"privilege",
"(",
"s",
")",
"on",
"the",
"specified",
"object",
"to",
"a",
"role"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_default_privileges.py#L77-L196 | train |
saltstack/salt | salt/modules/nfs3.py | list_exports | def list_exports(exports='/etc/exports'):
'''
List configured exports
CLI Example:
.. code-block:: bash
salt '*' nfs.list_exports
'''
ret = {}
with salt.utils.files.fopen(exports, 'r') as efl:
for line in salt.utils.stringutils.to_unicode(efl.read()).splitlines():
if not line:
continue
if line.startswith('#'):
continue
comps = line.split()
# Handle the case where the same path is given twice
if not comps[0] in ret:
ret[comps[0]] = []
newshares = []
for perm in comps[1:]:
if perm.startswith('/'):
newshares.append(perm)
continue
permcomps = perm.split('(')
permcomps[1] = permcomps[1].replace(')', '')
hosts = permcomps[0]
if not isinstance(hosts, six.string_types):
# Lists, etc would silently mangle /etc/exports
raise TypeError('hosts argument must be a string')
options = permcomps[1].split(',')
ret[comps[0]].append({'hosts': hosts, 'options': options})
for share in newshares:
ret[share] = ret[comps[0]]
return ret | python | def list_exports(exports='/etc/exports'):
'''
List configured exports
CLI Example:
.. code-block:: bash
salt '*' nfs.list_exports
'''
ret = {}
with salt.utils.files.fopen(exports, 'r') as efl:
for line in salt.utils.stringutils.to_unicode(efl.read()).splitlines():
if not line:
continue
if line.startswith('#'):
continue
comps = line.split()
# Handle the case where the same path is given twice
if not comps[0] in ret:
ret[comps[0]] = []
newshares = []
for perm in comps[1:]:
if perm.startswith('/'):
newshares.append(perm)
continue
permcomps = perm.split('(')
permcomps[1] = permcomps[1].replace(')', '')
hosts = permcomps[0]
if not isinstance(hosts, six.string_types):
# Lists, etc would silently mangle /etc/exports
raise TypeError('hosts argument must be a string')
options = permcomps[1].split(',')
ret[comps[0]].append({'hosts': hosts, 'options': options})
for share in newshares:
ret[share] = ret[comps[0]]
return ret | [
"def",
"list_exports",
"(",
"exports",
"=",
"'/etc/exports'",
")",
":",
"ret",
"=",
"{",
"}",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"exports",
",",
"'r'",
")",
"as",
"efl",
":",
"for",
"line",
"in",
"salt",
".",
"utils",
".... | List configured exports
CLI Example:
.. code-block:: bash
salt '*' nfs.list_exports | [
"List",
"configured",
"exports"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nfs3.py#L28-L66 | train |
saltstack/salt | salt/modules/nfs3.py | del_export | def del_export(exports='/etc/exports', path=None):
'''
Remove an export
CLI Example:
.. code-block:: bash
salt '*' nfs.del_export /media/storage
'''
edict = list_exports(exports)
del edict[path]
_write_exports(exports, edict)
return edict | python | def del_export(exports='/etc/exports', path=None):
'''
Remove an export
CLI Example:
.. code-block:: bash
salt '*' nfs.del_export /media/storage
'''
edict = list_exports(exports)
del edict[path]
_write_exports(exports, edict)
return edict | [
"def",
"del_export",
"(",
"exports",
"=",
"'/etc/exports'",
",",
"path",
"=",
"None",
")",
":",
"edict",
"=",
"list_exports",
"(",
"exports",
")",
"del",
"edict",
"[",
"path",
"]",
"_write_exports",
"(",
"exports",
",",
"edict",
")",
"return",
"edict"
] | Remove an export
CLI Example:
.. code-block:: bash
salt '*' nfs.del_export /media/storage | [
"Remove",
"an",
"export"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nfs3.py#L69-L82 | train |
saltstack/salt | salt/modules/nfs3.py | add_export | def add_export(exports='/etc/exports', path=None, hosts=None, options=None):
'''
Add an export
CLI Example:
.. code-block:: bash
salt '*' nfs3.add_export path='/srv/test' hosts='127.0.0.1' options=['rw']
'''
if options is None:
options = []
if not isinstance(hosts, six.string_types):
# Lists, etc would silently mangle /etc/exports
raise TypeError('hosts argument must be a string')
edict = list_exports(exports)
if path not in edict:
edict[path] = []
new = {'hosts': hosts, 'options': options}
edict[path].append(new)
_write_exports(exports, edict)
return new | python | def add_export(exports='/etc/exports', path=None, hosts=None, options=None):
'''
Add an export
CLI Example:
.. code-block:: bash
salt '*' nfs3.add_export path='/srv/test' hosts='127.0.0.1' options=['rw']
'''
if options is None:
options = []
if not isinstance(hosts, six.string_types):
# Lists, etc would silently mangle /etc/exports
raise TypeError('hosts argument must be a string')
edict = list_exports(exports)
if path not in edict:
edict[path] = []
new = {'hosts': hosts, 'options': options}
edict[path].append(new)
_write_exports(exports, edict)
return new | [
"def",
"add_export",
"(",
"exports",
"=",
"'/etc/exports'",
",",
"path",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"hos... | Add an export
CLI Example:
.. code-block:: bash
salt '*' nfs3.add_export path='/srv/test' hosts='127.0.0.1' options=['rw'] | [
"Add",
"an",
"export"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nfs3.py#L85-L107 | train |
saltstack/salt | salt/modules/nfs3.py | _write_exports | def _write_exports(exports, edict):
'''
Write an exports file to disk
If multiple shares were initially configured per line, like:
/media/storage /media/data *(ro,sync,no_subtree_check)
...then they will be saved to disk with only one share per line:
/media/storage *(ro,sync,no_subtree_check)
/media/data *(ro,sync,no_subtree_check)
'''
with salt.utils.files.fopen(exports, 'w') as efh:
for export in edict:
line = salt.utils.stringutils.to_str(export)
for perms in edict[export]:
hosts = perms['hosts']
options = ','.join(perms['options'])
line += ' {0}({1})'.format(hosts, options)
efh.write('{0}\n'.format(line)) | python | def _write_exports(exports, edict):
'''
Write an exports file to disk
If multiple shares were initially configured per line, like:
/media/storage /media/data *(ro,sync,no_subtree_check)
...then they will be saved to disk with only one share per line:
/media/storage *(ro,sync,no_subtree_check)
/media/data *(ro,sync,no_subtree_check)
'''
with salt.utils.files.fopen(exports, 'w') as efh:
for export in edict:
line = salt.utils.stringutils.to_str(export)
for perms in edict[export]:
hosts = perms['hosts']
options = ','.join(perms['options'])
line += ' {0}({1})'.format(hosts, options)
efh.write('{0}\n'.format(line)) | [
"def",
"_write_exports",
"(",
"exports",
",",
"edict",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"exports",
",",
"'w'",
")",
"as",
"efh",
":",
"for",
"export",
"in",
"edict",
":",
"line",
"=",
"salt",
".",
"utils",
".... | Write an exports file to disk
If multiple shares were initially configured per line, like:
/media/storage /media/data *(ro,sync,no_subtree_check)
...then they will be saved to disk with only one share per line:
/media/storage *(ro,sync,no_subtree_check)
/media/data *(ro,sync,no_subtree_check) | [
"Write",
"an",
"exports",
"file",
"to",
"disk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nfs3.py#L110-L130 | train |
saltstack/salt | salt/modules/nfs3.py | reload_exports | def reload_exports():
'''
Trigger a reload of the exports file to apply changes
CLI Example:
.. code-block:: bash
salt '*' nfs3.reload_exports
'''
ret = {}
command = 'exportfs -r'
output = __salt__['cmd.run_all'](command)
ret['stdout'] = output['stdout']
ret['stderr'] = output['stderr']
# exportfs always returns 0, so retcode is useless
# We will consider it an error if stderr is nonempty
ret['result'] = output['stderr'] == ''
return ret | python | def reload_exports():
'''
Trigger a reload of the exports file to apply changes
CLI Example:
.. code-block:: bash
salt '*' nfs3.reload_exports
'''
ret = {}
command = 'exportfs -r'
output = __salt__['cmd.run_all'](command)
ret['stdout'] = output['stdout']
ret['stderr'] = output['stderr']
# exportfs always returns 0, so retcode is useless
# We will consider it an error if stderr is nonempty
ret['result'] = output['stderr'] == ''
return ret | [
"def",
"reload_exports",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"command",
"=",
"'exportfs -r'",
"output",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"command",
")",
"ret",
"[",
"'stdout'",
"]",
"=",
"output",
"[",
"'stdout'",
"]",
"ret",
"[",
"'st... | Trigger a reload of the exports file to apply changes
CLI Example:
.. code-block:: bash
salt '*' nfs3.reload_exports | [
"Trigger",
"a",
"reload",
"of",
"the",
"exports",
"file",
"to",
"apply",
"changes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nfs3.py#L133-L154 | train |
saltstack/salt | salt/states/docker_image.py | present | def present(name,
tag=None,
build=None,
load=None,
force=False,
insecure_registry=False,
client_timeout=salt.utils.docker.CLIENT_TIMEOUT,
dockerfile=None,
sls=None,
base='opensuse/python',
saltenv='base',
pillarenv=None,
pillar=None,
**kwargs):
'''
.. versionchanged:: 2018.3.0
The ``tag`` argument has been added. It is now required unless pulling
from a registry.
Ensure that an image is present. The image can either be pulled from a
Docker registry, built from a Dockerfile, loaded from a saved image, or
built by running SLS files against a base image.
If none of the ``build``, ``load``, or ``sls`` arguments are used, then Salt
will pull from the :ref:`configured registries <docker-authentication>`. If
the specified image already exists, it will not be pulled unless ``force``
is set to ``True``. Here is an example of a state that will pull an image
from the Docker Hub:
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- tag: mytag
tag
Tag name for the image. Required when using ``build``, ``load``, or
``sls`` to create the image, but optional if pulling from a repository.
.. versionadded:: 2018.3.0
build
Path to directory on the Minion containing a Dockerfile
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- build: /home/myuser/docker/myimage
- tag: mytag
myuser/myimage:
docker_image.present:
- build: /home/myuser/docker/myimage
- tag: mytag
- dockerfile: Dockerfile.alternative
The image will be built using :py:func:`docker.build
<salt.modules.dockermod.build>` and the specified image name and tag
will be applied to it.
.. versionadded:: 2016.11.0
.. versionchanged:: 2018.3.0
The ``tag`` must be manually specified using the ``tag`` argument.
load
Loads a tar archive created with :py:func:`docker.load
<salt.modules.dockermod.load>` (or the ``docker load`` Docker CLI
command), and assigns it the specified repo and tag.
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- load: salt://path/to/image.tar
- tag: mytag
.. versionchanged:: 2018.3.0
The ``tag`` must be manually specified using the ``tag`` argument.
force : False
Set this parameter to ``True`` to force Salt to pull/build/load the
image even if it is already present.
client_timeout
Timeout in seconds for the Docker client. This is not a timeout for
the state, but for receiving a response from the API.
dockerfile
Allows for an alternative Dockerfile to be specified. Path to alternative
Dockefile is relative to the build path for the Docker container.
.. versionadded:: 2016.11.0
sls
Allow for building of image with :py:func:`docker.sls_build
<salt.modules.dockermod.sls_build>` by specifying the SLS files with
which to build. This can be a list or comma-seperated string.
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- tag: latest
- sls:
- webapp1
- webapp2
- base: centos
- saltenv: base
.. versionadded: 2017.7.0
.. versionchanged:: 2018.3.0
The ``tag`` must be manually specified using the ``tag`` argument.
base
Base image with which to start :py:func:`docker.sls_build
<salt.modules.dockermod.sls_build>`
.. versionadded:: 2017.7.0
saltenv
Specify the environment from which to retrieve the SLS indicated by the
`mods` parameter.
.. versionadded:: 2017.7.0
.. versionchanged:: 2018.3.0
Now uses the effective saltenv if not explicitly passed. In earlier
versions, ``base`` was assumed as a default.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
.. versionadded:: 2018.3.0
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. note::
Values passed this way will override Pillar values set via
``pillar_roots`` or an external Pillar source.
.. versionadded:: 2018.3.0
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not isinstance(name, six.string_types):
name = six.text_type(name)
# At most one of the args that result in an image being built can be used
num_build_args = len([x for x in (build, load, sls) if x is not None])
if num_build_args > 1:
ret['comment'] = \
'Only one of \'build\', \'load\', or \'sls\' is permitted.'
return ret
elif num_build_args == 1:
# If building, we need the tag to be specified
if not tag:
ret['comment'] = (
'The \'tag\' argument is required if any one of \'build\', '
'\'load\', or \'sls\' is used.'
)
return ret
if not isinstance(tag, six.string_types):
tag = six.text_type(tag)
full_image = ':'.join((name, tag))
else:
if tag:
name = '{0}:{1}'.format(name, tag)
full_image = name
try:
image_info = __salt__['docker.inspect_image'](full_image)
except CommandExecutionError as exc:
msg = exc.__str__()
if '404' in msg:
# Image not present
image_info = None
else:
ret['comment'] = msg
return ret
if image_info is not None:
# Specified image is present
if not force:
ret['result'] = True
ret['comment'] = 'Image {0} already present'.format(full_image)
return ret
if build or sls:
action = 'built'
elif load:
action = 'loaded'
else:
action = 'pulled'
if __opts__['test']:
ret['result'] = None
if (image_info is not None and force) or image_info is None:
ret['comment'] = 'Image {0} will be {1}'.format(full_image, action)
return ret
if build:
# Get the functions default value and args
argspec = salt.utils.args.get_function_argspec(__salt__['docker.build'])
# Map any if existing args from kwargs into the build_args dictionary
build_args = dict(list(zip(argspec.args, argspec.defaults)))
for k in build_args:
if k in kwargs.get('kwargs', {}):
build_args[k] = kwargs.get('kwargs', {}).get(k)
try:
# map values passed from the state to the build args
build_args['path'] = build
build_args['repository'] = name
build_args['tag'] = tag
build_args['dockerfile'] = dockerfile
image_update = __salt__['docker.build'](**build_args)
except Exception as exc:
ret['comment'] = (
'Encountered error building {0} as {1}: {2}'.format(
build, full_image, exc
)
)
return ret
if image_info is None or image_update['Id'] != image_info['Id'][:12]:
ret['changes'] = image_update
elif sls:
_locals = locals()
sls_build_kwargs = {k: _locals[k] for k in ('saltenv', 'pillarenv', 'pillar')
if _locals[k] is not None}
try:
image_update = __salt__['docker.sls_build'](repository=name,
tag=tag,
base=base,
mods=sls,
**sls_build_kwargs)
except Exception as exc:
ret['comment'] = (
'Encountered error using SLS {0} for building {1}: {2}'
.format(sls, full_image, exc)
)
return ret
if image_info is None or image_update['Id'] != image_info['Id'][:12]:
ret['changes'] = image_update
elif load:
try:
image_update = __salt__['docker.load'](path=load,
repository=name,
tag=tag)
except Exception as exc:
ret['comment'] = (
'Encountered error loading {0} as {1}: {2}'
.format(load, full_image, exc)
)
return ret
if image_info is None or image_update.get('Layers', []):
ret['changes'] = image_update
else:
try:
image_update = __salt__['docker.pull'](
name,
insecure_registry=insecure_registry,
client_timeout=client_timeout
)
except Exception as exc:
ret['comment'] = \
'Encountered error pulling {0}: {1}'.format(full_image, exc)
return ret
if (image_info is not None and image_info['Id'][:12] == image_update
.get('Layers', {})
.get('Already_Pulled', [None])[0]):
# Image was pulled again (because of force) but was also
# already there. No new image was available on the registry.
pass
elif image_info is None or image_update.get('Layers', {}).get('Pulled'):
# Only add to the changes dict if layers were pulled
ret['changes'] = image_update
error = False
try:
__salt__['docker.inspect_image'](full_image)
except CommandExecutionError as exc:
msg = exc.__str__()
if '404' not in msg:
error = 'Failed to inspect image \'{0}\' after it was {1}: {2}'.format(
full_image, action, msg
)
if error:
ret['comment'] = error
else:
ret['result'] = True
if not ret['changes']:
ret['comment'] = (
'Image \'{0}\' was {1}, but there were no changes'.format(
name, action
)
)
else:
ret['comment'] = 'Image \'{0}\' was {1}'.format(full_image, action)
return ret | python | def present(name,
tag=None,
build=None,
load=None,
force=False,
insecure_registry=False,
client_timeout=salt.utils.docker.CLIENT_TIMEOUT,
dockerfile=None,
sls=None,
base='opensuse/python',
saltenv='base',
pillarenv=None,
pillar=None,
**kwargs):
'''
.. versionchanged:: 2018.3.0
The ``tag`` argument has been added. It is now required unless pulling
from a registry.
Ensure that an image is present. The image can either be pulled from a
Docker registry, built from a Dockerfile, loaded from a saved image, or
built by running SLS files against a base image.
If none of the ``build``, ``load``, or ``sls`` arguments are used, then Salt
will pull from the :ref:`configured registries <docker-authentication>`. If
the specified image already exists, it will not be pulled unless ``force``
is set to ``True``. Here is an example of a state that will pull an image
from the Docker Hub:
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- tag: mytag
tag
Tag name for the image. Required when using ``build``, ``load``, or
``sls`` to create the image, but optional if pulling from a repository.
.. versionadded:: 2018.3.0
build
Path to directory on the Minion containing a Dockerfile
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- build: /home/myuser/docker/myimage
- tag: mytag
myuser/myimage:
docker_image.present:
- build: /home/myuser/docker/myimage
- tag: mytag
- dockerfile: Dockerfile.alternative
The image will be built using :py:func:`docker.build
<salt.modules.dockermod.build>` and the specified image name and tag
will be applied to it.
.. versionadded:: 2016.11.0
.. versionchanged:: 2018.3.0
The ``tag`` must be manually specified using the ``tag`` argument.
load
Loads a tar archive created with :py:func:`docker.load
<salt.modules.dockermod.load>` (or the ``docker load`` Docker CLI
command), and assigns it the specified repo and tag.
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- load: salt://path/to/image.tar
- tag: mytag
.. versionchanged:: 2018.3.0
The ``tag`` must be manually specified using the ``tag`` argument.
force : False
Set this parameter to ``True`` to force Salt to pull/build/load the
image even if it is already present.
client_timeout
Timeout in seconds for the Docker client. This is not a timeout for
the state, but for receiving a response from the API.
dockerfile
Allows for an alternative Dockerfile to be specified. Path to alternative
Dockefile is relative to the build path for the Docker container.
.. versionadded:: 2016.11.0
sls
Allow for building of image with :py:func:`docker.sls_build
<salt.modules.dockermod.sls_build>` by specifying the SLS files with
which to build. This can be a list or comma-seperated string.
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- tag: latest
- sls:
- webapp1
- webapp2
- base: centos
- saltenv: base
.. versionadded: 2017.7.0
.. versionchanged:: 2018.3.0
The ``tag`` must be manually specified using the ``tag`` argument.
base
Base image with which to start :py:func:`docker.sls_build
<salt.modules.dockermod.sls_build>`
.. versionadded:: 2017.7.0
saltenv
Specify the environment from which to retrieve the SLS indicated by the
`mods` parameter.
.. versionadded:: 2017.7.0
.. versionchanged:: 2018.3.0
Now uses the effective saltenv if not explicitly passed. In earlier
versions, ``base`` was assumed as a default.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
.. versionadded:: 2018.3.0
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. note::
Values passed this way will override Pillar values set via
``pillar_roots`` or an external Pillar source.
.. versionadded:: 2018.3.0
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not isinstance(name, six.string_types):
name = six.text_type(name)
# At most one of the args that result in an image being built can be used
num_build_args = len([x for x in (build, load, sls) if x is not None])
if num_build_args > 1:
ret['comment'] = \
'Only one of \'build\', \'load\', or \'sls\' is permitted.'
return ret
elif num_build_args == 1:
# If building, we need the tag to be specified
if not tag:
ret['comment'] = (
'The \'tag\' argument is required if any one of \'build\', '
'\'load\', or \'sls\' is used.'
)
return ret
if not isinstance(tag, six.string_types):
tag = six.text_type(tag)
full_image = ':'.join((name, tag))
else:
if tag:
name = '{0}:{1}'.format(name, tag)
full_image = name
try:
image_info = __salt__['docker.inspect_image'](full_image)
except CommandExecutionError as exc:
msg = exc.__str__()
if '404' in msg:
# Image not present
image_info = None
else:
ret['comment'] = msg
return ret
if image_info is not None:
# Specified image is present
if not force:
ret['result'] = True
ret['comment'] = 'Image {0} already present'.format(full_image)
return ret
if build or sls:
action = 'built'
elif load:
action = 'loaded'
else:
action = 'pulled'
if __opts__['test']:
ret['result'] = None
if (image_info is not None and force) or image_info is None:
ret['comment'] = 'Image {0} will be {1}'.format(full_image, action)
return ret
if build:
# Get the functions default value and args
argspec = salt.utils.args.get_function_argspec(__salt__['docker.build'])
# Map any if existing args from kwargs into the build_args dictionary
build_args = dict(list(zip(argspec.args, argspec.defaults)))
for k in build_args:
if k in kwargs.get('kwargs', {}):
build_args[k] = kwargs.get('kwargs', {}).get(k)
try:
# map values passed from the state to the build args
build_args['path'] = build
build_args['repository'] = name
build_args['tag'] = tag
build_args['dockerfile'] = dockerfile
image_update = __salt__['docker.build'](**build_args)
except Exception as exc:
ret['comment'] = (
'Encountered error building {0} as {1}: {2}'.format(
build, full_image, exc
)
)
return ret
if image_info is None or image_update['Id'] != image_info['Id'][:12]:
ret['changes'] = image_update
elif sls:
_locals = locals()
sls_build_kwargs = {k: _locals[k] for k in ('saltenv', 'pillarenv', 'pillar')
if _locals[k] is not None}
try:
image_update = __salt__['docker.sls_build'](repository=name,
tag=tag,
base=base,
mods=sls,
**sls_build_kwargs)
except Exception as exc:
ret['comment'] = (
'Encountered error using SLS {0} for building {1}: {2}'
.format(sls, full_image, exc)
)
return ret
if image_info is None or image_update['Id'] != image_info['Id'][:12]:
ret['changes'] = image_update
elif load:
try:
image_update = __salt__['docker.load'](path=load,
repository=name,
tag=tag)
except Exception as exc:
ret['comment'] = (
'Encountered error loading {0} as {1}: {2}'
.format(load, full_image, exc)
)
return ret
if image_info is None or image_update.get('Layers', []):
ret['changes'] = image_update
else:
try:
image_update = __salt__['docker.pull'](
name,
insecure_registry=insecure_registry,
client_timeout=client_timeout
)
except Exception as exc:
ret['comment'] = \
'Encountered error pulling {0}: {1}'.format(full_image, exc)
return ret
if (image_info is not None and image_info['Id'][:12] == image_update
.get('Layers', {})
.get('Already_Pulled', [None])[0]):
# Image was pulled again (because of force) but was also
# already there. No new image was available on the registry.
pass
elif image_info is None or image_update.get('Layers', {}).get('Pulled'):
# Only add to the changes dict if layers were pulled
ret['changes'] = image_update
error = False
try:
__salt__['docker.inspect_image'](full_image)
except CommandExecutionError as exc:
msg = exc.__str__()
if '404' not in msg:
error = 'Failed to inspect image \'{0}\' after it was {1}: {2}'.format(
full_image, action, msg
)
if error:
ret['comment'] = error
else:
ret['result'] = True
if not ret['changes']:
ret['comment'] = (
'Image \'{0}\' was {1}, but there were no changes'.format(
name, action
)
)
else:
ret['comment'] = 'Image \'{0}\' was {1}'.format(full_image, action)
return ret | [
"def",
"present",
"(",
"name",
",",
"tag",
"=",
"None",
",",
"build",
"=",
"None",
",",
"load",
"=",
"None",
",",
"force",
"=",
"False",
",",
"insecure_registry",
"=",
"False",
",",
"client_timeout",
"=",
"salt",
".",
"utils",
".",
"docker",
".",
"CL... | .. versionchanged:: 2018.3.0
The ``tag`` argument has been added. It is now required unless pulling
from a registry.
Ensure that an image is present. The image can either be pulled from a
Docker registry, built from a Dockerfile, loaded from a saved image, or
built by running SLS files against a base image.
If none of the ``build``, ``load``, or ``sls`` arguments are used, then Salt
will pull from the :ref:`configured registries <docker-authentication>`. If
the specified image already exists, it will not be pulled unless ``force``
is set to ``True``. Here is an example of a state that will pull an image
from the Docker Hub:
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- tag: mytag
tag
Tag name for the image. Required when using ``build``, ``load``, or
``sls`` to create the image, but optional if pulling from a repository.
.. versionadded:: 2018.3.0
build
Path to directory on the Minion containing a Dockerfile
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- build: /home/myuser/docker/myimage
- tag: mytag
myuser/myimage:
docker_image.present:
- build: /home/myuser/docker/myimage
- tag: mytag
- dockerfile: Dockerfile.alternative
The image will be built using :py:func:`docker.build
<salt.modules.dockermod.build>` and the specified image name and tag
will be applied to it.
.. versionadded:: 2016.11.0
.. versionchanged:: 2018.3.0
The ``tag`` must be manually specified using the ``tag`` argument.
load
Loads a tar archive created with :py:func:`docker.load
<salt.modules.dockermod.load>` (or the ``docker load`` Docker CLI
command), and assigns it the specified repo and tag.
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- load: salt://path/to/image.tar
- tag: mytag
.. versionchanged:: 2018.3.0
The ``tag`` must be manually specified using the ``tag`` argument.
force : False
Set this parameter to ``True`` to force Salt to pull/build/load the
image even if it is already present.
client_timeout
Timeout in seconds for the Docker client. This is not a timeout for
the state, but for receiving a response from the API.
dockerfile
Allows for an alternative Dockerfile to be specified. Path to alternative
Dockefile is relative to the build path for the Docker container.
.. versionadded:: 2016.11.0
sls
Allow for building of image with :py:func:`docker.sls_build
<salt.modules.dockermod.sls_build>` by specifying the SLS files with
which to build. This can be a list or comma-seperated string.
.. code-block:: yaml
myuser/myimage:
docker_image.present:
- tag: latest
- sls:
- webapp1
- webapp2
- base: centos
- saltenv: base
.. versionadded: 2017.7.0
.. versionchanged:: 2018.3.0
The ``tag`` must be manually specified using the ``tag`` argument.
base
Base image with which to start :py:func:`docker.sls_build
<salt.modules.dockermod.sls_build>`
.. versionadded:: 2017.7.0
saltenv
Specify the environment from which to retrieve the SLS indicated by the
`mods` parameter.
.. versionadded:: 2017.7.0
.. versionchanged:: 2018.3.0
Now uses the effective saltenv if not explicitly passed. In earlier
versions, ``base`` was assumed as a default.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
.. versionadded:: 2018.3.0
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. note::
Values passed this way will override Pillar values set via
``pillar_roots`` or an external Pillar source.
.. versionadded:: 2018.3.0 | [
"..",
"versionchanged",
"::",
"2018",
".",
"3",
".",
"0",
"The",
"tag",
"argument",
"has",
"been",
"added",
".",
"It",
"is",
"now",
"required",
"unless",
"pulling",
"from",
"a",
"registry",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/docker_image.py#L65-L375 | train |
saltstack/salt | salt/states/docker_image.py | absent | def absent(name=None, images=None, force=False):
'''
Ensure that an image is absent from the Minion. Image names can be
specified either using ``repo:tag`` notation, or just the repo name (in
which case a tag of ``latest`` is assumed).
images
Run this state on more than one image at a time. The following two
examples accomplish the same thing:
.. code-block:: yaml
remove_images:
docker_image.absent:
- names:
- busybox
- centos:6
- nginx
.. code-block:: yaml
remove_images:
docker_image.absent:
- images:
- busybox
- centos:6
- nginx
However, the second example will be a bit quicker since Salt will do
all the deletions in a single run, rather than executing the state
separately on each image (as it would in the first example).
force : False
Salt will fail to remove any images currently in use by a container.
Set this option to true to remove the image even if it is already
present.
.. note::
This option can also be overridden by Pillar data. If the Minion
has a pillar variable named ``docker.running.force`` which is
set to ``True``, it will turn on this option. This pillar variable
can even be set at runtime. For example:
.. code-block:: bash
salt myminion state.sls docker_stuff pillar="{docker.force: True}"
If this pillar variable is present and set to ``False``, then it
will turn off this option.
For more granular control, setting a pillar variable named
``docker.force.image_name`` will affect only the named image.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not name and not images:
ret['comment'] = 'One of \'name\' and \'images\' must be provided'
return ret
elif images is not None:
targets = images
elif name:
targets = [name]
to_delete = []
for target in targets:
resolved_tag = __salt__['docker.resolve_tag'](target)
if resolved_tag is not False:
to_delete.append(resolved_tag)
if not to_delete:
ret['result'] = True
if len(targets) == 1:
ret['comment'] = 'Image {0} is not present'.format(name)
else:
ret['comment'] = 'All specified images are not present'
return ret
if __opts__['test']:
ret['result'] = None
if len(to_delete) == 1:
ret['comment'] = 'Image {0} will be removed'.format(to_delete[0])
else:
ret['comment'] = (
'The following images will be removed: {0}'.format(
', '.join(to_delete)
)
)
return ret
result = __salt__['docker.rmi'](*to_delete, force=force)
post_tags = __salt__['docker.list_tags']()
failed = [x for x in to_delete if x in post_tags]
if failed:
if [x for x in to_delete if x not in post_tags]:
ret['changes'] = result
ret['comment'] = (
'The following image(s) failed to be removed: {0}'.format(
', '.join(failed)
)
)
else:
ret['comment'] = 'None of the specified images were removed'
if 'Errors' in result:
ret['comment'] += (
'. The following errors were encountered: {0}'
.format('; '.join(result['Errors']))
)
else:
ret['changes'] = result
if len(to_delete) == 1:
ret['comment'] = 'Image {0} was removed'.format(to_delete[0])
else:
ret['comment'] = (
'The following images were removed: {0}'.format(
', '.join(to_delete)
)
)
ret['result'] = True
return ret | python | def absent(name=None, images=None, force=False):
'''
Ensure that an image is absent from the Minion. Image names can be
specified either using ``repo:tag`` notation, or just the repo name (in
which case a tag of ``latest`` is assumed).
images
Run this state on more than one image at a time. The following two
examples accomplish the same thing:
.. code-block:: yaml
remove_images:
docker_image.absent:
- names:
- busybox
- centos:6
- nginx
.. code-block:: yaml
remove_images:
docker_image.absent:
- images:
- busybox
- centos:6
- nginx
However, the second example will be a bit quicker since Salt will do
all the deletions in a single run, rather than executing the state
separately on each image (as it would in the first example).
force : False
Salt will fail to remove any images currently in use by a container.
Set this option to true to remove the image even if it is already
present.
.. note::
This option can also be overridden by Pillar data. If the Minion
has a pillar variable named ``docker.running.force`` which is
set to ``True``, it will turn on this option. This pillar variable
can even be set at runtime. For example:
.. code-block:: bash
salt myminion state.sls docker_stuff pillar="{docker.force: True}"
If this pillar variable is present and set to ``False``, then it
will turn off this option.
For more granular control, setting a pillar variable named
``docker.force.image_name`` will affect only the named image.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not name and not images:
ret['comment'] = 'One of \'name\' and \'images\' must be provided'
return ret
elif images is not None:
targets = images
elif name:
targets = [name]
to_delete = []
for target in targets:
resolved_tag = __salt__['docker.resolve_tag'](target)
if resolved_tag is not False:
to_delete.append(resolved_tag)
if not to_delete:
ret['result'] = True
if len(targets) == 1:
ret['comment'] = 'Image {0} is not present'.format(name)
else:
ret['comment'] = 'All specified images are not present'
return ret
if __opts__['test']:
ret['result'] = None
if len(to_delete) == 1:
ret['comment'] = 'Image {0} will be removed'.format(to_delete[0])
else:
ret['comment'] = (
'The following images will be removed: {0}'.format(
', '.join(to_delete)
)
)
return ret
result = __salt__['docker.rmi'](*to_delete, force=force)
post_tags = __salt__['docker.list_tags']()
failed = [x for x in to_delete if x in post_tags]
if failed:
if [x for x in to_delete if x not in post_tags]:
ret['changes'] = result
ret['comment'] = (
'The following image(s) failed to be removed: {0}'.format(
', '.join(failed)
)
)
else:
ret['comment'] = 'None of the specified images were removed'
if 'Errors' in result:
ret['comment'] += (
'. The following errors were encountered: {0}'
.format('; '.join(result['Errors']))
)
else:
ret['changes'] = result
if len(to_delete) == 1:
ret['comment'] = 'Image {0} was removed'.format(to_delete[0])
else:
ret['comment'] = (
'The following images were removed: {0}'.format(
', '.join(to_delete)
)
)
ret['result'] = True
return ret | [
"def",
"absent",
"(",
"name",
"=",
"None",
",",
"images",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",... | Ensure that an image is absent from the Minion. Image names can be
specified either using ``repo:tag`` notation, or just the repo name (in
which case a tag of ``latest`` is assumed).
images
Run this state on more than one image at a time. The following two
examples accomplish the same thing:
.. code-block:: yaml
remove_images:
docker_image.absent:
- names:
- busybox
- centos:6
- nginx
.. code-block:: yaml
remove_images:
docker_image.absent:
- images:
- busybox
- centos:6
- nginx
However, the second example will be a bit quicker since Salt will do
all the deletions in a single run, rather than executing the state
separately on each image (as it would in the first example).
force : False
Salt will fail to remove any images currently in use by a container.
Set this option to true to remove the image even if it is already
present.
.. note::
This option can also be overridden by Pillar data. If the Minion
has a pillar variable named ``docker.running.force`` which is
set to ``True``, it will turn on this option. This pillar variable
can even be set at runtime. For example:
.. code-block:: bash
salt myminion state.sls docker_stuff pillar="{docker.force: True}"
If this pillar variable is present and set to ``False``, then it
will turn off this option.
For more granular control, setting a pillar variable named
``docker.force.image_name`` will affect only the named image. | [
"Ensure",
"that",
"an",
"image",
"is",
"absent",
"from",
"the",
"Minion",
".",
"Image",
"names",
"can",
"be",
"specified",
"either",
"using",
"repo",
":",
"tag",
"notation",
"or",
"just",
"the",
"repo",
"name",
"(",
"in",
"which",
"case",
"a",
"tag",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/docker_image.py#L378-L502 | train |
saltstack/salt | salt/states/docker_image.py | mod_watch | def mod_watch(name, sfun=None, **kwargs):
'''
The docker_image watcher, called to invoke the watch command.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
if sfun == 'present':
# Force image to be updated
kwargs['force'] = True
return present(name, **kwargs)
return {'name': name,
'changes': {},
'result': False,
'comment': 'watch requisite is not implemented for '
'{0}'.format(sfun)} | python | def mod_watch(name, sfun=None, **kwargs):
'''
The docker_image watcher, called to invoke the watch command.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
if sfun == 'present':
# Force image to be updated
kwargs['force'] = True
return present(name, **kwargs)
return {'name': name,
'changes': {},
'result': False,
'comment': 'watch requisite is not implemented for '
'{0}'.format(sfun)} | [
"def",
"mod_watch",
"(",
"name",
",",
"sfun",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sfun",
"==",
"'present'",
":",
"# Force image to be updated",
"kwargs",
"[",
"'force'",
"]",
"=",
"True",
"return",
"present",
"(",
"name",
",",
"*",
"... | The docker_image watcher, called to invoke the watch command.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered. | [
"The",
"docker_image",
"watcher",
"called",
"to",
"invoke",
"the",
"watch",
"command",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/docker_image.py#L505-L524 | train |
saltstack/salt | salt/renderers/genshi.py | render | def render(genshi_data, saltenv='base', sls='', method='xml', **kws):
'''
Render a Genshi template. A method should be passed in as part of the
kwargs. If no method is passed in, xml is assumed. Valid methods are:
.. code-block:
- xml
- xhtml
- html
- text
- newtext
- oldtext
Note that the ``text`` method will call ``NewTextTemplate``. If ``oldtext``
is desired, it must be called explicitly
:rtype: A Python data structure
'''
if not HAS_LIBS:
return {}
if not isinstance(genshi_data, six.string_types):
genshi_data = genshi_data.read()
if genshi_data.startswith('#!'):
genshi_data = genshi_data[(genshi_data.find('\n') + 1):]
if not genshi_data.strip():
return {}
if method == 'text' or method == 'newtext':
tmpl = NewTextTemplate(genshi_data)
elif method == 'oldtext':
tmpl = OldTextTemplate(genshi_data)
else:
tmpl = MarkupTemplate(genshi_data)
return tmpl.generate(**kws).render(method) | python | def render(genshi_data, saltenv='base', sls='', method='xml', **kws):
'''
Render a Genshi template. A method should be passed in as part of the
kwargs. If no method is passed in, xml is assumed. Valid methods are:
.. code-block:
- xml
- xhtml
- html
- text
- newtext
- oldtext
Note that the ``text`` method will call ``NewTextTemplate``. If ``oldtext``
is desired, it must be called explicitly
:rtype: A Python data structure
'''
if not HAS_LIBS:
return {}
if not isinstance(genshi_data, six.string_types):
genshi_data = genshi_data.read()
if genshi_data.startswith('#!'):
genshi_data = genshi_data[(genshi_data.find('\n') + 1):]
if not genshi_data.strip():
return {}
if method == 'text' or method == 'newtext':
tmpl = NewTextTemplate(genshi_data)
elif method == 'oldtext':
tmpl = OldTextTemplate(genshi_data)
else:
tmpl = MarkupTemplate(genshi_data)
return tmpl.generate(**kws).render(method) | [
"def",
"render",
"(",
"genshi_data",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"method",
"=",
"'xml'",
",",
"*",
"*",
"kws",
")",
":",
"if",
"not",
"HAS_LIBS",
":",
"return",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"genshi_data",
... | Render a Genshi template. A method should be passed in as part of the
kwargs. If no method is passed in, xml is assumed. Valid methods are:
.. code-block:
- xml
- xhtml
- html
- text
- newtext
- oldtext
Note that the ``text`` method will call ``NewTextTemplate``. If ``oldtext``
is desired, it must be called explicitly
:rtype: A Python data structure | [
"Render",
"a",
"Genshi",
"template",
".",
"A",
"method",
"should",
"be",
"passed",
"in",
"as",
"part",
"of",
"the",
"kwargs",
".",
"If",
"no",
"method",
"is",
"passed",
"in",
"xml",
"is",
"assumed",
".",
"Valid",
"methods",
"are",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/genshi.py#L21-L58 | train |
saltstack/salt | salt/output/nested.py | output | def output(ret, **kwargs):
'''
Display ret data
'''
# Prefer kwargs before opts
retcode = kwargs.get('_retcode', 0)
base_indent = kwargs.get('nested_indent', 0) \
or __opts__.get('nested_indent', 0)
nest = NestDisplay(retcode=retcode)
lines = nest.display(ret, base_indent, '', [])
try:
return '\n'.join(lines)
except UnicodeDecodeError:
# output contains binary data that can't be decoded
return str('\n').join( # future lint: disable=blacklisted-function
[salt.utils.stringutils.to_str(x) for x in lines]
) | python | def output(ret, **kwargs):
'''
Display ret data
'''
# Prefer kwargs before opts
retcode = kwargs.get('_retcode', 0)
base_indent = kwargs.get('nested_indent', 0) \
or __opts__.get('nested_indent', 0)
nest = NestDisplay(retcode=retcode)
lines = nest.display(ret, base_indent, '', [])
try:
return '\n'.join(lines)
except UnicodeDecodeError:
# output contains binary data that can't be decoded
return str('\n').join( # future lint: disable=blacklisted-function
[salt.utils.stringutils.to_str(x) for x in lines]
) | [
"def",
"output",
"(",
"ret",
",",
"*",
"*",
"kwargs",
")",
":",
"# Prefer kwargs before opts",
"retcode",
"=",
"kwargs",
".",
"get",
"(",
"'_retcode'",
",",
"0",
")",
"base_indent",
"=",
"kwargs",
".",
"get",
"(",
"'nested_indent'",
",",
"0",
")",
"or",
... | Display ret data | [
"Display",
"ret",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/nested.py#L208-L224 | train |
saltstack/salt | salt/output/nested.py | NestDisplay.display | def display(self, ret, indent, prefix, out):
'''
Recursively iterate down through data structures to determine output
'''
if isinstance(ret, bytes):
try:
ret = salt.utils.stringutils.to_unicode(ret)
except UnicodeDecodeError:
# ret contains binary data that can't be decoded
pass
if ret is None or ret is True or ret is False:
out.append(
self.ustring(
indent,
self.LIGHT_YELLOW,
ret,
prefix=prefix
)
)
# Number includes all python numbers types
# (float, int, long, complex, ...)
# use repr() to get the full precision also for older python versions
# as until about python32 it was limited to 12 digits only by default
elif isinstance(ret, Number):
out.append(
self.ustring(
indent,
self.LIGHT_YELLOW,
repr(ret),
prefix=prefix
)
)
elif isinstance(ret, six.string_types):
first_line = True
for line in ret.splitlines():
line_prefix = ' ' * len(prefix) if not first_line else prefix
if isinstance(line, bytes):
out.append(
self.ustring(
indent,
self.YELLOW,
'Not string data',
prefix=line_prefix
)
)
break
if self.strip_colors:
line = salt.output.strip_esc_sequence(line)
out.append(
self.ustring(
indent,
self.GREEN,
line,
prefix=line_prefix
)
)
first_line = False
elif isinstance(ret, (list, tuple)):
color = self.GREEN
if self.retcode != 0:
color = self.RED
for ind in ret:
if isinstance(ind, (list, tuple, Mapping)):
out.append(
self.ustring(
indent,
color,
'|_'
)
)
prefix = '' if isinstance(ind, Mapping) else '- '
self.display(ind, indent + 2, prefix, out)
else:
self.display(ind, indent, '- ', out)
elif isinstance(ret, Mapping):
if indent:
color = self.CYAN
if self.retcode != 0:
color = self.RED
out.append(
self.ustring(
indent,
color,
'----------'
)
)
# respect key ordering of ordered dicts
if isinstance(ret, salt.utils.odict.OrderedDict):
keys = ret.keys()
else:
keys = sorted(ret)
color = self.CYAN
if self.retcode != 0:
color = self.RED
for key in keys:
val = ret[key]
out.append(
self.ustring(
indent,
color,
key,
suffix=':',
prefix=prefix
)
)
self.display(val, indent + 4, '', out)
return out | python | def display(self, ret, indent, prefix, out):
'''
Recursively iterate down through data structures to determine output
'''
if isinstance(ret, bytes):
try:
ret = salt.utils.stringutils.to_unicode(ret)
except UnicodeDecodeError:
# ret contains binary data that can't be decoded
pass
if ret is None or ret is True or ret is False:
out.append(
self.ustring(
indent,
self.LIGHT_YELLOW,
ret,
prefix=prefix
)
)
# Number includes all python numbers types
# (float, int, long, complex, ...)
# use repr() to get the full precision also for older python versions
# as until about python32 it was limited to 12 digits only by default
elif isinstance(ret, Number):
out.append(
self.ustring(
indent,
self.LIGHT_YELLOW,
repr(ret),
prefix=prefix
)
)
elif isinstance(ret, six.string_types):
first_line = True
for line in ret.splitlines():
line_prefix = ' ' * len(prefix) if not first_line else prefix
if isinstance(line, bytes):
out.append(
self.ustring(
indent,
self.YELLOW,
'Not string data',
prefix=line_prefix
)
)
break
if self.strip_colors:
line = salt.output.strip_esc_sequence(line)
out.append(
self.ustring(
indent,
self.GREEN,
line,
prefix=line_prefix
)
)
first_line = False
elif isinstance(ret, (list, tuple)):
color = self.GREEN
if self.retcode != 0:
color = self.RED
for ind in ret:
if isinstance(ind, (list, tuple, Mapping)):
out.append(
self.ustring(
indent,
color,
'|_'
)
)
prefix = '' if isinstance(ind, Mapping) else '- '
self.display(ind, indent + 2, prefix, out)
else:
self.display(ind, indent, '- ', out)
elif isinstance(ret, Mapping):
if indent:
color = self.CYAN
if self.retcode != 0:
color = self.RED
out.append(
self.ustring(
indent,
color,
'----------'
)
)
# respect key ordering of ordered dicts
if isinstance(ret, salt.utils.odict.OrderedDict):
keys = ret.keys()
else:
keys = sorted(ret)
color = self.CYAN
if self.retcode != 0:
color = self.RED
for key in keys:
val = ret[key]
out.append(
self.ustring(
indent,
color,
key,
suffix=':',
prefix=prefix
)
)
self.display(val, indent + 4, '', out)
return out | [
"def",
"display",
"(",
"self",
",",
"ret",
",",
"indent",
",",
"prefix",
",",
"out",
")",
":",
"if",
"isinstance",
"(",
"ret",
",",
"bytes",
")",
":",
"try",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"ret",
... | Recursively iterate down through data structures to determine output | [
"Recursively",
"iterate",
"down",
"through",
"data",
"structures",
"to",
"determine",
"output"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/nested.py#L97-L205 | train |
saltstack/salt | salt/utils/mount.py | _read_file | def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.fopen(path, 'rb') as contents:
return salt.utils.yaml.safe_load(contents)
except (OSError, IOError):
return {} | python | def _read_file(path):
'''
Reads and returns the contents of a text file
'''
try:
with salt.utils.files.fopen(path, 'rb') as contents:
return salt.utils.yaml.safe_load(contents)
except (OSError, IOError):
return {} | [
"def",
"_read_file",
"(",
"path",
")",
":",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"path",
",",
"'rb'",
")",
"as",
"contents",
":",
"return",
"salt",
".",
"utils",
".",
"yaml",
".",
"safe_load",
"(",
"contents",
... | Reads and returns the contents of a text file | [
"Reads",
"and",
"returns",
"the",
"contents",
"of",
"a",
"text",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/mount.py#L20-L28 | train |
saltstack/salt | salt/utils/mount.py | write_cache | def write_cache(cache, opts):
'''
Write the mount cache file.
'''
cache_file = get_cache(opts)
try:
_cache = salt.utils.stringutils.to_bytes(
salt.utils.yaml.safe_dump(cache)
)
with salt.utils.files.fopen(cache_file, 'wb+') as fp_:
fp_.write(_cache)
return True
except (IOError, OSError):
log.error('Failed to cache mounts',
exc_info_on_loglevel=logging.DEBUG)
return False | python | def write_cache(cache, opts):
'''
Write the mount cache file.
'''
cache_file = get_cache(opts)
try:
_cache = salt.utils.stringutils.to_bytes(
salt.utils.yaml.safe_dump(cache)
)
with salt.utils.files.fopen(cache_file, 'wb+') as fp_:
fp_.write(_cache)
return True
except (IOError, OSError):
log.error('Failed to cache mounts',
exc_info_on_loglevel=logging.DEBUG)
return False | [
"def",
"write_cache",
"(",
"cache",
",",
"opts",
")",
":",
"cache_file",
"=",
"get_cache",
"(",
"opts",
")",
"try",
":",
"_cache",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_bytes",
"(",
"salt",
".",
"utils",
".",
"yaml",
".",
"safe_dump",... | Write the mount cache file. | [
"Write",
"the",
"mount",
"cache",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/mount.py#L46-L62 | train |
saltstack/salt | salt/modules/iosconfig.py | _get_diff_text | def _get_diff_text(old, new):
'''
Returns the diff of two text blobs.
'''
diff = difflib.unified_diff(old.splitlines(1),
new.splitlines(1))
return ''.join([x.replace('\r', '') for x in diff]) | python | def _get_diff_text(old, new):
'''
Returns the diff of two text blobs.
'''
diff = difflib.unified_diff(old.splitlines(1),
new.splitlines(1))
return ''.join([x.replace('\r', '') for x in diff]) | [
"def",
"_get_diff_text",
"(",
"old",
",",
"new",
")",
":",
"diff",
"=",
"difflib",
".",
"unified_diff",
"(",
"old",
".",
"splitlines",
"(",
"1",
")",
",",
"new",
".",
"splitlines",
"(",
"1",
")",
")",
"return",
"''",
".",
"join",
"(",
"[",
"x",
"... | Returns the diff of two text blobs. | [
"Returns",
"the",
"diff",
"of",
"two",
"text",
"blobs",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iosconfig.py#L116-L122 | train |
saltstack/salt | salt/modules/iosconfig.py | _print_config_text | def _print_config_text(tree, indentation=0):
'''
Return the config as text from a config tree.
'''
config = ''
for key, value in six.iteritems(tree):
config += '{indent}{line}\n'.format(indent=' '*indentation, line=key)
if value:
config += _print_config_text(value, indentation=indentation+1)
return config | python | def _print_config_text(tree, indentation=0):
'''
Return the config as text from a config tree.
'''
config = ''
for key, value in six.iteritems(tree):
config += '{indent}{line}\n'.format(indent=' '*indentation, line=key)
if value:
config += _print_config_text(value, indentation=indentation+1)
return config | [
"def",
"_print_config_text",
"(",
"tree",
",",
"indentation",
"=",
"0",
")",
":",
"config",
"=",
"''",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"tree",
")",
":",
"config",
"+=",
"'{indent}{line}\\n'",
".",
"format",
"(",
"indent",
... | Return the config as text from a config tree. | [
"Return",
"the",
"config",
"as",
"text",
"from",
"a",
"config",
"tree",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iosconfig.py#L125-L134 | train |
saltstack/salt | salt/modules/iosconfig.py | tree | def tree(config=None,
path=None,
with_tags=False,
saltenv='base'):
'''
Transform Cisco IOS style configuration to structured Python dictionary.
Depending on the value of the ``with_tags`` argument, this function may
provide different views, valuable in different situations.
config
The configuration sent as text. This argument is ignored when ``path``
is configured.
path
Absolute or remote path from where to load the configuration text. This
argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
with_tags: ``False``
Whether this function should return a detailed view, with tags.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.tree path=salt://path/to/my/config.txt
salt '*' iosconfig.tree path=https://bit.ly/2mAdq7z
'''
if path:
config = __salt__['cp.get_file_str'](path, saltenv=saltenv)
if config is False:
raise SaltException('{} is not available'.format(path))
config_lines = config.splitlines()
return _parse_text_config(config_lines, with_tags=with_tags) | python | def tree(config=None,
path=None,
with_tags=False,
saltenv='base'):
'''
Transform Cisco IOS style configuration to structured Python dictionary.
Depending on the value of the ``with_tags`` argument, this function may
provide different views, valuable in different situations.
config
The configuration sent as text. This argument is ignored when ``path``
is configured.
path
Absolute or remote path from where to load the configuration text. This
argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
with_tags: ``False``
Whether this function should return a detailed view, with tags.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.tree path=salt://path/to/my/config.txt
salt '*' iosconfig.tree path=https://bit.ly/2mAdq7z
'''
if path:
config = __salt__['cp.get_file_str'](path, saltenv=saltenv)
if config is False:
raise SaltException('{} is not available'.format(path))
config_lines = config.splitlines()
return _parse_text_config(config_lines, with_tags=with_tags) | [
"def",
"tree",
"(",
"config",
"=",
"None",
",",
"path",
"=",
"None",
",",
"with_tags",
"=",
"False",
",",
"saltenv",
"=",
"'base'",
")",
":",
"if",
"path",
":",
"config",
"=",
"__salt__",
"[",
"'cp.get_file_str'",
"]",
"(",
"path",
",",
"saltenv",
"=... | Transform Cisco IOS style configuration to structured Python dictionary.
Depending on the value of the ``with_tags`` argument, this function may
provide different views, valuable in different situations.
config
The configuration sent as text. This argument is ignored when ``path``
is configured.
path
Absolute or remote path from where to load the configuration text. This
argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
with_tags: ``False``
Whether this function should return a detailed view, with tags.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.tree path=salt://path/to/my/config.txt
salt '*' iosconfig.tree path=https://bit.ly/2mAdq7z | [
"Transform",
"Cisco",
"IOS",
"style",
"configuration",
"to",
"structured",
"Python",
"dictionary",
".",
"Depending",
"on",
"the",
"value",
"of",
"the",
"with_tags",
"argument",
"this",
"function",
"may",
"provide",
"different",
"views",
"valuable",
"in",
"differen... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iosconfig.py#L141-L179 | train |
saltstack/salt | salt/modules/iosconfig.py | clean | def clean(config=None, path=None, saltenv='base'):
'''
Return a clean version of the config, without any special signs (such as
``!`` as an individual line) or empty lines, but just lines with significant
value in the configuration of the network device.
config
The configuration sent as text. This argument is ignored when ``path``
is configured.
path
Absolute or remote path from where to load the configuration text. This
argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.clean path=salt://path/to/my/config.txt
salt '*' iosconfig.clean path=https://bit.ly/2mAdq7z
'''
config_tree = tree(config=config, path=path, saltenv=saltenv)
return _print_config_text(config_tree) | python | def clean(config=None, path=None, saltenv='base'):
'''
Return a clean version of the config, without any special signs (such as
``!`` as an individual line) or empty lines, but just lines with significant
value in the configuration of the network device.
config
The configuration sent as text. This argument is ignored when ``path``
is configured.
path
Absolute or remote path from where to load the configuration text. This
argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.clean path=salt://path/to/my/config.txt
salt '*' iosconfig.clean path=https://bit.ly/2mAdq7z
'''
config_tree = tree(config=config, path=path, saltenv=saltenv)
return _print_config_text(config_tree) | [
"def",
"clean",
"(",
"config",
"=",
"None",
",",
"path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"config_tree",
"=",
"tree",
"(",
"config",
"=",
"config",
",",
"path",
"=",
"path",
",",
"saltenv",
"=",
"saltenv",
")",
"return",
"_print_... | Return a clean version of the config, without any special signs (such as
``!`` as an individual line) or empty lines, but just lines with significant
value in the configuration of the network device.
config
The configuration sent as text. This argument is ignored when ``path``
is configured.
path
Absolute or remote path from where to load the configuration text. This
argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.clean path=salt://path/to/my/config.txt
salt '*' iosconfig.clean path=https://bit.ly/2mAdq7z | [
"Return",
"a",
"clean",
"version",
"of",
"the",
"config",
"without",
"any",
"special",
"signs",
"(",
"such",
"as",
"!",
"as",
"an",
"individual",
"line",
")",
"or",
"empty",
"lines",
"but",
"just",
"lines",
"with",
"significant",
"value",
"in",
"the",
"c... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iosconfig.py#L182-L210 | train |
saltstack/salt | salt/modules/iosconfig.py | merge_tree | def merge_tree(initial_config=None,
initial_path=None,
merge_config=None,
merge_path=None,
saltenv='base'):
'''
Return the merge tree of the ``initial_config`` with the ``merge_config``,
as a Python dictionary.
initial_config
The initial configuration sent as text. This argument is ignored when
``initial_path`` is set.
initial_path
Absolute or remote path from where to load the initial configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``initial_path`` or ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.merge_tree initial_path=salt://path/to/running.cfg merge_path=salt://path/to/merge.cfg
'''
merge_tree = tree(config=merge_config,
path=merge_path,
saltenv=saltenv)
initial_tree = tree(config=initial_config,
path=initial_path,
saltenv=saltenv)
return salt.utils.dictupdate.merge(initial_tree, merge_tree) | python | def merge_tree(initial_config=None,
initial_path=None,
merge_config=None,
merge_path=None,
saltenv='base'):
'''
Return the merge tree of the ``initial_config`` with the ``merge_config``,
as a Python dictionary.
initial_config
The initial configuration sent as text. This argument is ignored when
``initial_path`` is set.
initial_path
Absolute or remote path from where to load the initial configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``initial_path`` or ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.merge_tree initial_path=salt://path/to/running.cfg merge_path=salt://path/to/merge.cfg
'''
merge_tree = tree(config=merge_config,
path=merge_path,
saltenv=saltenv)
initial_tree = tree(config=initial_config,
path=initial_path,
saltenv=saltenv)
return salt.utils.dictupdate.merge(initial_tree, merge_tree) | [
"def",
"merge_tree",
"(",
"initial_config",
"=",
"None",
",",
"initial_path",
"=",
"None",
",",
"merge_config",
"=",
"None",
",",
"merge_path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"merge_tree",
"=",
"tree",
"(",
"config",
"=",
"merge_conf... | Return the merge tree of the ``initial_config`` with the ``merge_config``,
as a Python dictionary.
initial_config
The initial configuration sent as text. This argument is ignored when
``initial_path`` is set.
initial_path
Absolute or remote path from where to load the initial configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``initial_path`` or ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.merge_tree initial_path=salt://path/to/running.cfg merge_path=salt://path/to/merge.cfg | [
"Return",
"the",
"merge",
"tree",
"of",
"the",
"initial_config",
"with",
"the",
"merge_config",
"as",
"a",
"Python",
"dictionary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iosconfig.py#L213-L258 | train |
saltstack/salt | salt/modules/iosconfig.py | merge_text | def merge_text(initial_config=None,
initial_path=None,
merge_config=None,
merge_path=None,
saltenv='base'):
'''
Return the merge result of the ``initial_config`` with the ``merge_config``,
as plain text.
initial_config
The initial configuration sent as text. This argument is ignored when
``initial_path`` is set.
initial_path
Absolute or remote path from where to load the initial configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``initial_path`` or ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.merge_text initial_path=salt://path/to/running.cfg merge_path=salt://path/to/merge.cfg
'''
candidate_tree = merge_tree(initial_config=initial_config,
initial_path=initial_path,
merge_config=merge_config,
merge_path=merge_path,
saltenv=saltenv)
return _print_config_text(candidate_tree) | python | def merge_text(initial_config=None,
initial_path=None,
merge_config=None,
merge_path=None,
saltenv='base'):
'''
Return the merge result of the ``initial_config`` with the ``merge_config``,
as plain text.
initial_config
The initial configuration sent as text. This argument is ignored when
``initial_path`` is set.
initial_path
Absolute or remote path from where to load the initial configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``initial_path`` or ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.merge_text initial_path=salt://path/to/running.cfg merge_path=salt://path/to/merge.cfg
'''
candidate_tree = merge_tree(initial_config=initial_config,
initial_path=initial_path,
merge_config=merge_config,
merge_path=merge_path,
saltenv=saltenv)
return _print_config_text(candidate_tree) | [
"def",
"merge_text",
"(",
"initial_config",
"=",
"None",
",",
"initial_path",
"=",
"None",
",",
"merge_config",
"=",
"None",
",",
"merge_path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"candidate_tree",
"=",
"merge_tree",
"(",
"initial_config",
... | Return the merge result of the ``initial_config`` with the ``merge_config``,
as plain text.
initial_config
The initial configuration sent as text. This argument is ignored when
``initial_path`` is set.
initial_path
Absolute or remote path from where to load the initial configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``initial_path`` or ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.merge_text initial_path=salt://path/to/running.cfg merge_path=salt://path/to/merge.cfg | [
"Return",
"the",
"merge",
"result",
"of",
"the",
"initial_config",
"with",
"the",
"merge_config",
"as",
"plain",
"text",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iosconfig.py#L261-L305 | train |
saltstack/salt | salt/modules/iosconfig.py | merge_diff | def merge_diff(initial_config=None,
initial_path=None,
merge_config=None,
merge_path=None,
saltenv='base'):
'''
Return the merge diff, as text, after merging the merge config into the
initial config.
initial_config
The initial configuration sent as text. This argument is ignored when
``initial_path`` is set.
initial_path
Absolute or remote path from where to load the initial configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``initial_path`` or ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.merge_diff initial_path=salt://path/to/running.cfg merge_path=salt://path/to/merge.cfg
'''
if initial_path:
initial_config = __salt__['cp.get_file_str'](initial_path, saltenv=saltenv)
candidate_config = merge_text(initial_config=initial_config,
merge_config=merge_config,
merge_path=merge_path,
saltenv=saltenv)
clean_running_dict = tree(config=initial_config)
clean_running = _print_config_text(clean_running_dict)
return _get_diff_text(clean_running, candidate_config) | python | def merge_diff(initial_config=None,
initial_path=None,
merge_config=None,
merge_path=None,
saltenv='base'):
'''
Return the merge diff, as text, after merging the merge config into the
initial config.
initial_config
The initial configuration sent as text. This argument is ignored when
``initial_path`` is set.
initial_path
Absolute or remote path from where to load the initial configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``initial_path`` or ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.merge_diff initial_path=salt://path/to/running.cfg merge_path=salt://path/to/merge.cfg
'''
if initial_path:
initial_config = __salt__['cp.get_file_str'](initial_path, saltenv=saltenv)
candidate_config = merge_text(initial_config=initial_config,
merge_config=merge_config,
merge_path=merge_path,
saltenv=saltenv)
clean_running_dict = tree(config=initial_config)
clean_running = _print_config_text(clean_running_dict)
return _get_diff_text(clean_running, candidate_config) | [
"def",
"merge_diff",
"(",
"initial_config",
"=",
"None",
",",
"initial_path",
"=",
"None",
",",
"merge_config",
"=",
"None",
",",
"merge_path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"if",
"initial_path",
":",
"initial_config",
"=",
"__salt__"... | Return the merge diff, as text, after merging the merge config into the
initial config.
initial_config
The initial configuration sent as text. This argument is ignored when
``initial_path`` is set.
initial_path
Absolute or remote path from where to load the initial configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``initial_path`` or ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.merge_diff initial_path=salt://path/to/running.cfg merge_path=salt://path/to/merge.cfg | [
"Return",
"the",
"merge",
"diff",
"as",
"text",
"after",
"merging",
"the",
"merge",
"config",
"into",
"the",
"initial",
"config",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iosconfig.py#L308-L355 | train |
saltstack/salt | salt/modules/iosconfig.py | diff_tree | def diff_tree(candidate_config=None,
candidate_path=None,
running_config=None,
running_path=None,
saltenv='base'):
'''
Return the diff, as Python dictionary, between the candidate and the running
configuration.
candidate_config
The candidate configuration sent as text. This argument is ignored when
``candidate_path`` is set.
candidate_path
Absolute or remote path from where to load the candidate configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
running_config
The running configuration sent as text. This argument is ignored when
``running_path`` is set.
running_path
Absolute or remote path from where to load the runing configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``candidate_path`` or ``running_path`` is not a
``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.diff_tree candidate_path=salt://path/to/candidate.cfg running_path=salt://path/to/running.cfg
'''
candidate_tree = tree(config=candidate_config,
path=candidate_path,
saltenv=saltenv)
running_tree = tree(config=running_config,
path=running_path,
saltenv=saltenv)
return salt.utils.dictdiffer.deep_diff(running_tree, candidate_tree) | python | def diff_tree(candidate_config=None,
candidate_path=None,
running_config=None,
running_path=None,
saltenv='base'):
'''
Return the diff, as Python dictionary, between the candidate and the running
configuration.
candidate_config
The candidate configuration sent as text. This argument is ignored when
``candidate_path`` is set.
candidate_path
Absolute or remote path from where to load the candidate configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
running_config
The running configuration sent as text. This argument is ignored when
``running_path`` is set.
running_path
Absolute or remote path from where to load the runing configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``candidate_path`` or ``running_path`` is not a
``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.diff_tree candidate_path=salt://path/to/candidate.cfg running_path=salt://path/to/running.cfg
'''
candidate_tree = tree(config=candidate_config,
path=candidate_path,
saltenv=saltenv)
running_tree = tree(config=running_config,
path=running_path,
saltenv=saltenv)
return salt.utils.dictdiffer.deep_diff(running_tree, candidate_tree) | [
"def",
"diff_tree",
"(",
"candidate_config",
"=",
"None",
",",
"candidate_path",
"=",
"None",
",",
"running_config",
"=",
"None",
",",
"running_path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"candidate_tree",
"=",
"tree",
"(",
"config",
"=",
... | Return the diff, as Python dictionary, between the candidate and the running
configuration.
candidate_config
The candidate configuration sent as text. This argument is ignored when
``candidate_path`` is set.
candidate_path
Absolute or remote path from where to load the candidate configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
running_config
The running configuration sent as text. This argument is ignored when
``running_path`` is set.
running_path
Absolute or remote path from where to load the runing configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``candidate_path`` or ``running_path`` is not a
``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.diff_tree candidate_path=salt://path/to/candidate.cfg running_path=salt://path/to/running.cfg | [
"Return",
"the",
"diff",
"as",
"Python",
"dictionary",
"between",
"the",
"candidate",
"and",
"the",
"running",
"configuration",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iosconfig.py#L358-L404 | train |
saltstack/salt | salt/modules/iosconfig.py | diff_text | def diff_text(candidate_config=None,
candidate_path=None,
running_config=None,
running_path=None,
saltenv='base'):
'''
Return the diff, as text, between the candidate and the running config.
candidate_config
The candidate configuration sent as text. This argument is ignored when
``candidate_path`` is set.
candidate_path
Absolute or remote path from where to load the candidate configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
running_config
The running configuration sent as text. This argument is ignored when
``running_path`` is set.
running_path
Absolute or remote path from where to load the runing configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``candidate_path`` or ``running_path`` is not a
``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.diff_text candidate_path=salt://path/to/candidate.cfg running_path=salt://path/to/running.cfg
'''
candidate_text = clean(config=candidate_config,
path=candidate_path,
saltenv=saltenv)
running_text = clean(config=running_config,
path=running_path,
saltenv=saltenv)
return _get_diff_text(running_text, candidate_text) | python | def diff_text(candidate_config=None,
candidate_path=None,
running_config=None,
running_path=None,
saltenv='base'):
'''
Return the diff, as text, between the candidate and the running config.
candidate_config
The candidate configuration sent as text. This argument is ignored when
``candidate_path`` is set.
candidate_path
Absolute or remote path from where to load the candidate configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
running_config
The running configuration sent as text. This argument is ignored when
``running_path`` is set.
running_path
Absolute or remote path from where to load the runing configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``candidate_path`` or ``running_path`` is not a
``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.diff_text candidate_path=salt://path/to/candidate.cfg running_path=salt://path/to/running.cfg
'''
candidate_text = clean(config=candidate_config,
path=candidate_path,
saltenv=saltenv)
running_text = clean(config=running_config,
path=running_path,
saltenv=saltenv)
return _get_diff_text(running_text, candidate_text) | [
"def",
"diff_text",
"(",
"candidate_config",
"=",
"None",
",",
"candidate_path",
"=",
"None",
",",
"running_config",
"=",
"None",
",",
"running_path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"candidate_text",
"=",
"clean",
"(",
"config",
"=",
... | Return the diff, as text, between the candidate and the running config.
candidate_config
The candidate configuration sent as text. This argument is ignored when
``candidate_path`` is set.
candidate_path
Absolute or remote path from where to load the candidate configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
running_config
The running configuration sent as text. This argument is ignored when
``running_path`` is set.
running_path
Absolute or remote path from where to load the runing configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``candidate_path`` or ``running_path`` is not a
``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' iosconfig.diff_text candidate_path=salt://path/to/candidate.cfg running_path=salt://path/to/running.cfg | [
"Return",
"the",
"diff",
"as",
"text",
"between",
"the",
"candidate",
"and",
"the",
"running",
"config",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iosconfig.py#L407-L452 | train |
saltstack/salt | salt/modules/pcs.py | item_show | def item_show(item, item_id=None, item_type=None, show='show', extra_args=None, cibfile=None):
'''
Show an item via pcs command
(mainly for use with the pcs state module)
item
config, property, resource, constraint etc.
item_id
id of the item
item_type
item type
show
show command (probably None, default: show)
extra_args
additional options for the pcs command
cibfile
use cibfile instead of the live CIB
'''
cmd = ['pcs']
if isinstance(cibfile, six.string_types):
cmd += ['-f', cibfile]
if isinstance(item, six.string_types):
cmd += [item]
elif isinstance(item, (list, tuple)):
cmd += item
# constraint command follows a different order
if item in ['constraint']:
cmd += [item_type]
if isinstance(show, six.string_types):
cmd += [show]
elif isinstance(show, (list, tuple)):
cmd += show
if isinstance(item_id, six.string_types):
cmd += [item_id]
if isinstance(extra_args, (list, tuple)):
cmd += extra_args
# constraint command only shows id, when using '--full'-parameter
if item in ['constraint']:
if not isinstance(extra_args, (list, tuple)) or '--full' not in extra_args:
cmd += ['--full']
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | python | def item_show(item, item_id=None, item_type=None, show='show', extra_args=None, cibfile=None):
'''
Show an item via pcs command
(mainly for use with the pcs state module)
item
config, property, resource, constraint etc.
item_id
id of the item
item_type
item type
show
show command (probably None, default: show)
extra_args
additional options for the pcs command
cibfile
use cibfile instead of the live CIB
'''
cmd = ['pcs']
if isinstance(cibfile, six.string_types):
cmd += ['-f', cibfile]
if isinstance(item, six.string_types):
cmd += [item]
elif isinstance(item, (list, tuple)):
cmd += item
# constraint command follows a different order
if item in ['constraint']:
cmd += [item_type]
if isinstance(show, six.string_types):
cmd += [show]
elif isinstance(show, (list, tuple)):
cmd += show
if isinstance(item_id, six.string_types):
cmd += [item_id]
if isinstance(extra_args, (list, tuple)):
cmd += extra_args
# constraint command only shows id, when using '--full'-parameter
if item in ['constraint']:
if not isinstance(extra_args, (list, tuple)) or '--full' not in extra_args:
cmd += ['--full']
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | [
"def",
"item_show",
"(",
"item",
",",
"item_id",
"=",
"None",
",",
"item_type",
"=",
"None",
",",
"show",
"=",
"'show'",
",",
"extra_args",
"=",
"None",
",",
"cibfile",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'pcs'",
"]",
"if",
"isinstance",
"(",
... | Show an item via pcs command
(mainly for use with the pcs state module)
item
config, property, resource, constraint etc.
item_id
id of the item
item_type
item type
show
show command (probably None, default: show)
extra_args
additional options for the pcs command
cibfile
use cibfile instead of the live CIB | [
"Show",
"an",
"item",
"via",
"pcs",
"command",
"(",
"mainly",
"for",
"use",
"with",
"the",
"pcs",
"state",
"module",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L29-L77 | train |
saltstack/salt | salt/modules/pcs.py | item_create | def item_create(item, item_id, item_type, create='create', extra_args=None, cibfile=None):
'''
Create an item via pcs command
(mainly for use with the pcs state module)
item
config, property, resource, constraint etc.
item_id
id of the item
item_type
item type
create
create command (create or set f.e., default: create)
extra_args
additional options for the pcs command
cibfile
use cibfile instead of the live CIB
'''
cmd = ['pcs']
if isinstance(cibfile, six.string_types):
cmd += ['-f', cibfile]
if isinstance(item, six.string_types):
cmd += [item]
elif isinstance(item, (list, tuple)):
cmd += item
# constraint command follows a different order
if item in ['constraint']:
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(create, six.string_types):
cmd += [create]
elif isinstance(create, (list, tuple)):
cmd += create
# constraint command needs item_id in format 'id=<id' after all params
# constraint command follows a different order
if item not in ['constraint']:
cmd += [item_id]
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(extra_args, (list, tuple)):
# constraint command needs item_id in format 'id=<id' after all params
if item in ['constraint']:
extra_args = extra_args + ['id={0}'.format(item_id)]
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | python | def item_create(item, item_id, item_type, create='create', extra_args=None, cibfile=None):
'''
Create an item via pcs command
(mainly for use with the pcs state module)
item
config, property, resource, constraint etc.
item_id
id of the item
item_type
item type
create
create command (create or set f.e., default: create)
extra_args
additional options for the pcs command
cibfile
use cibfile instead of the live CIB
'''
cmd = ['pcs']
if isinstance(cibfile, six.string_types):
cmd += ['-f', cibfile]
if isinstance(item, six.string_types):
cmd += [item]
elif isinstance(item, (list, tuple)):
cmd += item
# constraint command follows a different order
if item in ['constraint']:
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(create, six.string_types):
cmd += [create]
elif isinstance(create, (list, tuple)):
cmd += create
# constraint command needs item_id in format 'id=<id' after all params
# constraint command follows a different order
if item not in ['constraint']:
cmd += [item_id]
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(extra_args, (list, tuple)):
# constraint command needs item_id in format 'id=<id' after all params
if item in ['constraint']:
extra_args = extra_args + ['id={0}'.format(item_id)]
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | [
"def",
"item_create",
"(",
"item",
",",
"item_id",
",",
"item_type",
",",
"create",
"=",
"'create'",
",",
"extra_args",
"=",
"None",
",",
"cibfile",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'pcs'",
"]",
"if",
"isinstance",
"(",
"cibfile",
",",
"six",
... | Create an item via pcs command
(mainly for use with the pcs state module)
item
config, property, resource, constraint etc.
item_id
id of the item
item_type
item type
create
create command (create or set f.e., default: create)
extra_args
additional options for the pcs command
cibfile
use cibfile instead of the live CIB | [
"Create",
"an",
"item",
"via",
"pcs",
"command",
"(",
"mainly",
"for",
"use",
"with",
"the",
"pcs",
"state",
"module",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L80-L130 | train |
saltstack/salt | salt/modules/pcs.py | auth | def auth(nodes, pcsuser='hacluster', pcspasswd='hacluster', extra_args=None):
'''
Authorize nodes to the cluster
nodes
a list of nodes which should be authorized to the cluster
pcsuser
user for communitcation with PCS (default: hacluster)
pcspasswd
password for pcsuser (default: hacluster)
extra_args
list of extra option for the \'pcs cluster auth\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.auth nodes='[ node1.example.org node2.example.org ]' pcsuser=hacluster pcspasswd=hoonetorg extra_args="[ '--force' ]"
'''
cmd = ['pcs', 'cluster', 'auth']
if pcsuser:
cmd += ['-u', pcsuser]
if pcspasswd:
cmd += ['-p', pcspasswd]
if isinstance(extra_args, (list, tuple)):
cmd += extra_args
cmd += nodes
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | python | def auth(nodes, pcsuser='hacluster', pcspasswd='hacluster', extra_args=None):
'''
Authorize nodes to the cluster
nodes
a list of nodes which should be authorized to the cluster
pcsuser
user for communitcation with PCS (default: hacluster)
pcspasswd
password for pcsuser (default: hacluster)
extra_args
list of extra option for the \'pcs cluster auth\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.auth nodes='[ node1.example.org node2.example.org ]' pcsuser=hacluster pcspasswd=hoonetorg extra_args="[ '--force' ]"
'''
cmd = ['pcs', 'cluster', 'auth']
if pcsuser:
cmd += ['-u', pcsuser]
if pcspasswd:
cmd += ['-p', pcspasswd]
if isinstance(extra_args, (list, tuple)):
cmd += extra_args
cmd += nodes
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | [
"def",
"auth",
"(",
"nodes",
",",
"pcsuser",
"=",
"'hacluster'",
",",
"pcspasswd",
"=",
"'hacluster'",
",",
"extra_args",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'pcs'",
",",
"'cluster'",
",",
"'auth'",
"]",
"if",
"pcsuser",
":",
"cmd",
"+=",
"[",
"... | Authorize nodes to the cluster
nodes
a list of nodes which should be authorized to the cluster
pcsuser
user for communitcation with PCS (default: hacluster)
pcspasswd
password for pcsuser (default: hacluster)
extra_args
list of extra option for the \'pcs cluster auth\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.auth nodes='[ node1.example.org node2.example.org ]' pcsuser=hacluster pcspasswd=hoonetorg extra_args="[ '--force' ]" | [
"Authorize",
"nodes",
"to",
"the",
"cluster"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L133-L164 | train |
saltstack/salt | salt/modules/pcs.py | is_auth | def is_auth(nodes):
'''
Check if nodes are already authorized
nodes
a list of nodes to be checked for authorization to the cluster
CLI Example:
.. code-block:: bash
salt '*' pcs.is_auth nodes='[node1.example.org node2.example.org]'
'''
cmd = ['pcs', 'cluster', 'auth']
cmd += nodes
return __salt__['cmd.run_all'](cmd, stdin='\n\n', output_loglevel='trace', python_shell=False) | python | def is_auth(nodes):
'''
Check if nodes are already authorized
nodes
a list of nodes to be checked for authorization to the cluster
CLI Example:
.. code-block:: bash
salt '*' pcs.is_auth nodes='[node1.example.org node2.example.org]'
'''
cmd = ['pcs', 'cluster', 'auth']
cmd += nodes
return __salt__['cmd.run_all'](cmd, stdin='\n\n', output_loglevel='trace', python_shell=False) | [
"def",
"is_auth",
"(",
"nodes",
")",
":",
"cmd",
"=",
"[",
"'pcs'",
",",
"'cluster'",
",",
"'auth'",
"]",
"cmd",
"+=",
"nodes",
"return",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"stdin",
"=",
"'\\n\\n'",
",",
"output_loglevel",
"=",
"'t... | Check if nodes are already authorized
nodes
a list of nodes to be checked for authorization to the cluster
CLI Example:
.. code-block:: bash
salt '*' pcs.is_auth nodes='[node1.example.org node2.example.org]' | [
"Check",
"if",
"nodes",
"are",
"already",
"authorized"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L167-L183 | train |
saltstack/salt | salt/modules/pcs.py | cluster_setup | def cluster_setup(nodes, pcsclustername='pcscluster', extra_args=None):
'''
Setup pacemaker cluster via pcs command
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster (default: pcscluster)
extra_args
list of extra option for the \'pcs cluster setup\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_setup nodes='[ node1.example.org node2.example.org ]' pcsclustername=pcscluster
'''
cmd = ['pcs', 'cluster', 'setup']
cmd += ['--name', pcsclustername]
cmd += nodes
if isinstance(extra_args, (list, tuple)):
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | python | def cluster_setup(nodes, pcsclustername='pcscluster', extra_args=None):
'''
Setup pacemaker cluster via pcs command
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster (default: pcscluster)
extra_args
list of extra option for the \'pcs cluster setup\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_setup nodes='[ node1.example.org node2.example.org ]' pcsclustername=pcscluster
'''
cmd = ['pcs', 'cluster', 'setup']
cmd += ['--name', pcsclustername]
cmd += nodes
if isinstance(extra_args, (list, tuple)):
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | [
"def",
"cluster_setup",
"(",
"nodes",
",",
"pcsclustername",
"=",
"'pcscluster'",
",",
"extra_args",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'pcs'",
",",
"'cluster'",
",",
"'setup'",
"]",
"cmd",
"+=",
"[",
"'--name'",
",",
"pcsclustername",
"]",
"cmd",
... | Setup pacemaker cluster via pcs command
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster (default: pcscluster)
extra_args
list of extra option for the \'pcs cluster setup\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_setup nodes='[ node1.example.org node2.example.org ]' pcsclustername=pcscluster | [
"Setup",
"pacemaker",
"cluster",
"via",
"pcs",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L186-L211 | train |
saltstack/salt | salt/modules/pcs.py | cluster_node_add | def cluster_node_add(node, extra_args=None):
'''
Add a node to the pacemaker cluster via pcs command
node
node that should be added
extra_args
list of extra option for the \'pcs cluster node add\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_node_add node=node2.example.org
'''
cmd = ['pcs', 'cluster', 'node', 'add']
cmd += [node]
if isinstance(extra_args, (list, tuple)):
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | python | def cluster_node_add(node, extra_args=None):
'''
Add a node to the pacemaker cluster via pcs command
node
node that should be added
extra_args
list of extra option for the \'pcs cluster node add\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_node_add node=node2.example.org
'''
cmd = ['pcs', 'cluster', 'node', 'add']
cmd += [node]
if isinstance(extra_args, (list, tuple)):
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | [
"def",
"cluster_node_add",
"(",
"node",
",",
"extra_args",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'pcs'",
",",
"'cluster'",
",",
"'node'",
",",
"'add'",
"]",
"cmd",
"+=",
"[",
"node",
"]",
"if",
"isinstance",
"(",
"extra_args",
",",
"(",
"list",
",... | Add a node to the pacemaker cluster via pcs command
node
node that should be added
extra_args
list of extra option for the \'pcs cluster node add\' command
CLI Example:
.. code-block:: bash
salt '*' pcs.cluster_node_add node=node2.example.org | [
"Add",
"a",
"node",
"to",
"the",
"pacemaker",
"cluster",
"via",
"pcs",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L214-L235 | train |
saltstack/salt | salt/modules/pcs.py | cib_create | def cib_create(cibfile, scope='configuration', extra_args=None):
'''
Create a CIB-file from the current CIB of the cluster
cibfile
name/path of the file containing the CIB
scope
specific section of the CIB (default: configuration)
extra_args
additional options for creating the CIB-file
CLI Example:
.. code-block:: bash
salt '*' pcs.cib_create cibfile='/tmp/VIP_apache_1.cib' scope=False
'''
cmd = ['pcs', 'cluster', 'cib', cibfile]
if isinstance(scope, six.string_types):
cmd += ['scope={0}'.format(scope)]
if isinstance(extra_args, (list, tuple)):
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | python | def cib_create(cibfile, scope='configuration', extra_args=None):
'''
Create a CIB-file from the current CIB of the cluster
cibfile
name/path of the file containing the CIB
scope
specific section of the CIB (default: configuration)
extra_args
additional options for creating the CIB-file
CLI Example:
.. code-block:: bash
salt '*' pcs.cib_create cibfile='/tmp/VIP_apache_1.cib' scope=False
'''
cmd = ['pcs', 'cluster', 'cib', cibfile]
if isinstance(scope, six.string_types):
cmd += ['scope={0}'.format(scope)]
if isinstance(extra_args, (list, tuple)):
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) | [
"def",
"cib_create",
"(",
"cibfile",
",",
"scope",
"=",
"'configuration'",
",",
"extra_args",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'pcs'",
",",
"'cluster'",
",",
"'cib'",
",",
"cibfile",
"]",
"if",
"isinstance",
"(",
"scope",
",",
"six",
".",
"stri... | Create a CIB-file from the current CIB of the cluster
cibfile
name/path of the file containing the CIB
scope
specific section of the CIB (default: configuration)
extra_args
additional options for creating the CIB-file
CLI Example:
.. code-block:: bash
salt '*' pcs.cib_create cibfile='/tmp/VIP_apache_1.cib' scope=False | [
"Create",
"a",
"CIB",
"-",
"file",
"from",
"the",
"current",
"CIB",
"of",
"the",
"cluster"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L238-L261 | train |
saltstack/salt | salt/modules/pcs.py | prop_show | def prop_show(prop, extra_args=None, cibfile=None):
'''
Show the value of a cluster property
prop
name of the property
extra_args
additional options for the pcs property command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.prop_show cibfile='/tmp/2_node_cluster.cib' prop='no-quorum-policy' cibfile='/tmp/2_node_cluster.cib'
'''
return item_show(item='property', item_id=prop, extra_args=extra_args, cibfile=cibfile) | python | def prop_show(prop, extra_args=None, cibfile=None):
'''
Show the value of a cluster property
prop
name of the property
extra_args
additional options for the pcs property command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.prop_show cibfile='/tmp/2_node_cluster.cib' prop='no-quorum-policy' cibfile='/tmp/2_node_cluster.cib'
'''
return item_show(item='property', item_id=prop, extra_args=extra_args, cibfile=cibfile) | [
"def",
"prop_show",
"(",
"prop",
",",
"extra_args",
"=",
"None",
",",
"cibfile",
"=",
"None",
")",
":",
"return",
"item_show",
"(",
"item",
"=",
"'property'",
",",
"item_id",
"=",
"prop",
",",
"extra_args",
"=",
"extra_args",
",",
"cibfile",
"=",
"cibfil... | Show the value of a cluster property
prop
name of the property
extra_args
additional options for the pcs property command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.prop_show cibfile='/tmp/2_node_cluster.cib' prop='no-quorum-policy' cibfile='/tmp/2_node_cluster.cib' | [
"Show",
"the",
"value",
"of",
"a",
"cluster",
"property"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L306-L323 | train |
saltstack/salt | salt/modules/pcs.py | prop_set | def prop_set(prop, value, extra_args=None, cibfile=None):
'''
Set the value of a cluster property
prop
name of the property
value
value of the property prop
extra_args
additional options for the pcs property command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.prop_set prop='no-quorum-policy' value='ignore' cibfile='/tmp/2_node_cluster.cib'
'''
return item_create(item='property',
item_id='{0}={1}'.format(prop, value),
item_type=None,
create='set',
extra_args=extra_args,
cibfile=cibfile) | python | def prop_set(prop, value, extra_args=None, cibfile=None):
'''
Set the value of a cluster property
prop
name of the property
value
value of the property prop
extra_args
additional options for the pcs property command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.prop_set prop='no-quorum-policy' value='ignore' cibfile='/tmp/2_node_cluster.cib'
'''
return item_create(item='property',
item_id='{0}={1}'.format(prop, value),
item_type=None,
create='set',
extra_args=extra_args,
cibfile=cibfile) | [
"def",
"prop_set",
"(",
"prop",
",",
"value",
",",
"extra_args",
"=",
"None",
",",
"cibfile",
"=",
"None",
")",
":",
"return",
"item_create",
"(",
"item",
"=",
"'property'",
",",
"item_id",
"=",
"'{0}={1}'",
".",
"format",
"(",
"prop",
",",
"value",
")... | Set the value of a cluster property
prop
name of the property
value
value of the property prop
extra_args
additional options for the pcs property command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.prop_set prop='no-quorum-policy' value='ignore' cibfile='/tmp/2_node_cluster.cib' | [
"Set",
"the",
"value",
"of",
"a",
"cluster",
"property"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L326-L350 | train |
saltstack/salt | salt/modules/pcs.py | stonith_show | def stonith_show(stonith_id, extra_args=None, cibfile=None):
'''
Show the value of a cluster stonith
stonith_id
name for the stonith resource
extra_args
additional options for the pcs stonith command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.stonith_show stonith_id='eps_fence' cibfile='/tmp/2_node_cluster.cib'
'''
return item_show(item='stonith', item_id=stonith_id, extra_args=extra_args, cibfile=cibfile) | python | def stonith_show(stonith_id, extra_args=None, cibfile=None):
'''
Show the value of a cluster stonith
stonith_id
name for the stonith resource
extra_args
additional options for the pcs stonith command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.stonith_show stonith_id='eps_fence' cibfile='/tmp/2_node_cluster.cib'
'''
return item_show(item='stonith', item_id=stonith_id, extra_args=extra_args, cibfile=cibfile) | [
"def",
"stonith_show",
"(",
"stonith_id",
",",
"extra_args",
"=",
"None",
",",
"cibfile",
"=",
"None",
")",
":",
"return",
"item_show",
"(",
"item",
"=",
"'stonith'",
",",
"item_id",
"=",
"stonith_id",
",",
"extra_args",
"=",
"extra_args",
",",
"cibfile",
... | Show the value of a cluster stonith
stonith_id
name for the stonith resource
extra_args
additional options for the pcs stonith command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.stonith_show stonith_id='eps_fence' cibfile='/tmp/2_node_cluster.cib' | [
"Show",
"the",
"value",
"of",
"a",
"cluster",
"stonith"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L353-L370 | train |
saltstack/salt | salt/modules/pcs.py | stonith_create | def stonith_create(stonith_id, stonith_device_type, stonith_device_options=None, cibfile=None):
'''
Create a stonith resource via pcs command
stonith_id
name for the stonith resource
stonith_device_type
name of the stonith agent fence_eps, fence_xvm f.e.
stonith_device_options
additional options for creating the stonith resource
cibfile
use cibfile instead of the live CIB for manipulation
CLI Example:
.. code-block:: bash
salt '*' pcs.stonith_create stonith_id='eps_fence' stonith_device_type='fence_eps'
stonith_device_options="['pcmk_host_map=node1.example.org:01;node2.example.org:02', 'ipaddr=myepsdevice.example.org', 'action=reboot', 'power_wait=5', 'verbose=1', 'debug=/var/log/pcsd/eps_fence.log', 'login=hidden', 'passwd=hoonetorg']" cibfile='/tmp/cib_for_stonith.cib'
'''
return item_create(item='stonith',
item_id=stonith_id,
item_type=stonith_device_type,
extra_args=stonith_device_options,
cibfile=cibfile) | python | def stonith_create(stonith_id, stonith_device_type, stonith_device_options=None, cibfile=None):
'''
Create a stonith resource via pcs command
stonith_id
name for the stonith resource
stonith_device_type
name of the stonith agent fence_eps, fence_xvm f.e.
stonith_device_options
additional options for creating the stonith resource
cibfile
use cibfile instead of the live CIB for manipulation
CLI Example:
.. code-block:: bash
salt '*' pcs.stonith_create stonith_id='eps_fence' stonith_device_type='fence_eps'
stonith_device_options="['pcmk_host_map=node1.example.org:01;node2.example.org:02', 'ipaddr=myepsdevice.example.org', 'action=reboot', 'power_wait=5', 'verbose=1', 'debug=/var/log/pcsd/eps_fence.log', 'login=hidden', 'passwd=hoonetorg']" cibfile='/tmp/cib_for_stonith.cib'
'''
return item_create(item='stonith',
item_id=stonith_id,
item_type=stonith_device_type,
extra_args=stonith_device_options,
cibfile=cibfile) | [
"def",
"stonith_create",
"(",
"stonith_id",
",",
"stonith_device_type",
",",
"stonith_device_options",
"=",
"None",
",",
"cibfile",
"=",
"None",
")",
":",
"return",
"item_create",
"(",
"item",
"=",
"'stonith'",
",",
"item_id",
"=",
"stonith_id",
",",
"item_type"... | Create a stonith resource via pcs command
stonith_id
name for the stonith resource
stonith_device_type
name of the stonith agent fence_eps, fence_xvm f.e.
stonith_device_options
additional options for creating the stonith resource
cibfile
use cibfile instead of the live CIB for manipulation
CLI Example:
.. code-block:: bash
salt '*' pcs.stonith_create stonith_id='eps_fence' stonith_device_type='fence_eps'
stonith_device_options="['pcmk_host_map=node1.example.org:01;node2.example.org:02', 'ipaddr=myepsdevice.example.org', 'action=reboot', 'power_wait=5', 'verbose=1', 'debug=/var/log/pcsd/eps_fence.log', 'login=hidden', 'passwd=hoonetorg']" cibfile='/tmp/cib_for_stonith.cib' | [
"Create",
"a",
"stonith",
"resource",
"via",
"pcs",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L373-L397 | train |
saltstack/salt | salt/modules/pcs.py | resource_show | def resource_show(resource_id, extra_args=None, cibfile=None):
'''
Show a resource via pcs command
resource_id
name of the resource
extra_args
additional options for the pcs command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.resource_show resource_id='galera' cibfile='/tmp/cib_for_galera.cib'
'''
return item_show(item='resource', item_id=resource_id, extra_args=extra_args, cibfile=cibfile) | python | def resource_show(resource_id, extra_args=None, cibfile=None):
'''
Show a resource via pcs command
resource_id
name of the resource
extra_args
additional options for the pcs command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.resource_show resource_id='galera' cibfile='/tmp/cib_for_galera.cib'
'''
return item_show(item='resource', item_id=resource_id, extra_args=extra_args, cibfile=cibfile) | [
"def",
"resource_show",
"(",
"resource_id",
",",
"extra_args",
"=",
"None",
",",
"cibfile",
"=",
"None",
")",
":",
"return",
"item_show",
"(",
"item",
"=",
"'resource'",
",",
"item_id",
"=",
"resource_id",
",",
"extra_args",
"=",
"extra_args",
",",
"cibfile"... | Show a resource via pcs command
resource_id
name of the resource
extra_args
additional options for the pcs command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.resource_show resource_id='galera' cibfile='/tmp/cib_for_galera.cib' | [
"Show",
"a",
"resource",
"via",
"pcs",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L400-L417 | train |
saltstack/salt | salt/modules/pcs.py | resource_create | def resource_create(resource_id, resource_type, resource_options=None, cibfile=None):
'''
Create a resource via pcs command
resource_id
name for the resource
resource_type
resource type (f.e. ocf:heartbeat:IPaddr2 or VirtualIP)
resource_options
additional options for creating the resource
cibfile
use cibfile instead of the live CIB for manipulation
CLI Example:
.. code-block:: bash
salt '*' pcs.resource_create resource_id='galera' resource_type='ocf:heartbeat:galera' resource_options="['wsrep_cluster_address=gcomm://node1.example.org,node2.example.org,node3.example.org', '--master']" cibfile='/tmp/cib_for_galera.cib'
'''
return item_create(item='resource',
item_id=resource_id,
item_type=resource_type,
extra_args=resource_options,
cibfile=cibfile) | python | def resource_create(resource_id, resource_type, resource_options=None, cibfile=None):
'''
Create a resource via pcs command
resource_id
name for the resource
resource_type
resource type (f.e. ocf:heartbeat:IPaddr2 or VirtualIP)
resource_options
additional options for creating the resource
cibfile
use cibfile instead of the live CIB for manipulation
CLI Example:
.. code-block:: bash
salt '*' pcs.resource_create resource_id='galera' resource_type='ocf:heartbeat:galera' resource_options="['wsrep_cluster_address=gcomm://node1.example.org,node2.example.org,node3.example.org', '--master']" cibfile='/tmp/cib_for_galera.cib'
'''
return item_create(item='resource',
item_id=resource_id,
item_type=resource_type,
extra_args=resource_options,
cibfile=cibfile) | [
"def",
"resource_create",
"(",
"resource_id",
",",
"resource_type",
",",
"resource_options",
"=",
"None",
",",
"cibfile",
"=",
"None",
")",
":",
"return",
"item_create",
"(",
"item",
"=",
"'resource'",
",",
"item_id",
"=",
"resource_id",
",",
"item_type",
"=",... | Create a resource via pcs command
resource_id
name for the resource
resource_type
resource type (f.e. ocf:heartbeat:IPaddr2 or VirtualIP)
resource_options
additional options for creating the resource
cibfile
use cibfile instead of the live CIB for manipulation
CLI Example:
.. code-block:: bash
salt '*' pcs.resource_create resource_id='galera' resource_type='ocf:heartbeat:galera' resource_options="['wsrep_cluster_address=gcomm://node1.example.org,node2.example.org,node3.example.org', '--master']" cibfile='/tmp/cib_for_galera.cib' | [
"Create",
"a",
"resource",
"via",
"pcs",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pcs.py#L420-L443 | train |
saltstack/salt | salt/cli/support/console.py | wrap | def wrap(txt, width=80, ident=0):
'''
Wrap text to the required dimensions and clean it up, prepare for display.
:param txt:
:param width:
:return:
'''
ident = ' ' * ident
txt = (txt or '').replace(os.linesep, ' ').strip()
wrapper = textwrap.TextWrapper()
wrapper.fix_sentence_endings = False
wrapper.initial_indent = wrapper.subsequent_indent = ident
return wrapper.wrap(txt) | python | def wrap(txt, width=80, ident=0):
'''
Wrap text to the required dimensions and clean it up, prepare for display.
:param txt:
:param width:
:return:
'''
ident = ' ' * ident
txt = (txt or '').replace(os.linesep, ' ').strip()
wrapper = textwrap.TextWrapper()
wrapper.fix_sentence_endings = False
wrapper.initial_indent = wrapper.subsequent_indent = ident
return wrapper.wrap(txt) | [
"def",
"wrap",
"(",
"txt",
",",
"width",
"=",
"80",
",",
"ident",
"=",
"0",
")",
":",
"ident",
"=",
"' '",
"*",
"ident",
"txt",
"=",
"(",
"txt",
"or",
"''",
")",
".",
"replace",
"(",
"os",
".",
"linesep",
",",
"' '",
")",
".",
"strip",
"(",
... | Wrap text to the required dimensions and clean it up, prepare for display.
:param txt:
:param width:
:return: | [
"Wrap",
"text",
"to",
"the",
"required",
"dimensions",
"and",
"clean",
"it",
"up",
"prepare",
"for",
"display",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/console.py#L150-L165 | train |
saltstack/salt | salt/cli/support/console.py | IndentOutput.put | def put(self, message, indent=0):
'''
Print message with an indent.
:param message:
:param indent:
:return:
'''
color = self._colors_conf.get(indent + indent % 2, self._colors_conf.get(0, self._default_color))
for chunk in [' ' * indent, self._colors[color], message, self._colors['ENDC']]:
self._device.write(str(chunk))
self._device.write(os.linesep)
self._device.flush() | python | def put(self, message, indent=0):
'''
Print message with an indent.
:param message:
:param indent:
:return:
'''
color = self._colors_conf.get(indent + indent % 2, self._colors_conf.get(0, self._default_color))
for chunk in [' ' * indent, self._colors[color], message, self._colors['ENDC']]:
self._device.write(str(chunk))
self._device.write(os.linesep)
self._device.flush() | [
"def",
"put",
"(",
"self",
",",
"message",
",",
"indent",
"=",
"0",
")",
":",
"color",
"=",
"self",
".",
"_colors_conf",
".",
"get",
"(",
"indent",
"+",
"indent",
"%",
"2",
",",
"self",
".",
"_colors_conf",
".",
"get",
"(",
"0",
",",
"self",
".",... | Print message with an indent.
:param message:
:param indent:
:return: | [
"Print",
"message",
"with",
"an",
"indent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/console.py#L30-L43 | train |
saltstack/salt | salt/cli/support/console.py | MessagesOutput.msg | def msg(self, message, title=None, title_color=None, color='BLUE', ident=0):
'''
Hint message.
:param message:
:param title:
:param title_color:
:param color:
:param ident:
:return:
'''
if title and not title_color:
title_color = color
if title_color and not title:
title_color = None
self.__colored_output(title, message, title_color, color, ident=ident) | python | def msg(self, message, title=None, title_color=None, color='BLUE', ident=0):
'''
Hint message.
:param message:
:param title:
:param title_color:
:param color:
:param ident:
:return:
'''
if title and not title_color:
title_color = color
if title_color and not title:
title_color = None
self.__colored_output(title, message, title_color, color, ident=ident) | [
"def",
"msg",
"(",
"self",
",",
"message",
",",
"title",
"=",
"None",
",",
"title_color",
"=",
"None",
",",
"color",
"=",
"'BLUE'",
",",
"ident",
"=",
"0",
")",
":",
"if",
"title",
"and",
"not",
"title_color",
":",
"title_color",
"=",
"color",
"if",
... | Hint message.
:param message:
:param title:
:param title_color:
:param color:
:param ident:
:return: | [
"Hint",
"message",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/console.py#L50-L66 | train |
saltstack/salt | salt/cli/support/console.py | MessagesOutput.highlight | def highlight(self, message, *values, **colors):
'''
Highlighter works the way that message parameter is a template,
the "values" is a list of arguments going one after another as values there.
And so the "colors" should designate either highlight color or alternate for each.
Example:
highlight('Hello {}, there! It is {}.', 'user', 'daytime', _main='GREEN', _highlight='RED')
highlight('Hello {}, there! It is {}.', 'user', 'daytime', _main='GREEN', _highlight='RED', 'daytime'='YELLOW')
First example will highlight all the values in the template with the red color.
Second example will highlight the second value with the yellow color.
Usage:
colors:
_main: Sets the main color (or default is used)
_highlight: Sets the alternative color for everything
'any phrase' that is the same in the "values" can override color.
:param message:
:param formatted:
:param colors:
:return:
'''
m_color = colors.get('_main', self._default_color)
h_color = colors.get('_highlight', self._default_hl_color)
_values = []
for value in values:
_values.append('{p}{c}{r}'.format(p=self._colors[colors.get(value, h_color)],
c=value, r=self._colors[m_color]))
self._device.write('{s}{m}{e}'.format(s=self._colors[m_color],
m=message.format(*_values), e=self._colors['ENDC']))
self._device.write(os.linesep)
self._device.flush() | python | def highlight(self, message, *values, **colors):
'''
Highlighter works the way that message parameter is a template,
the "values" is a list of arguments going one after another as values there.
And so the "colors" should designate either highlight color or alternate for each.
Example:
highlight('Hello {}, there! It is {}.', 'user', 'daytime', _main='GREEN', _highlight='RED')
highlight('Hello {}, there! It is {}.', 'user', 'daytime', _main='GREEN', _highlight='RED', 'daytime'='YELLOW')
First example will highlight all the values in the template with the red color.
Second example will highlight the second value with the yellow color.
Usage:
colors:
_main: Sets the main color (or default is used)
_highlight: Sets the alternative color for everything
'any phrase' that is the same in the "values" can override color.
:param message:
:param formatted:
:param colors:
:return:
'''
m_color = colors.get('_main', self._default_color)
h_color = colors.get('_highlight', self._default_hl_color)
_values = []
for value in values:
_values.append('{p}{c}{r}'.format(p=self._colors[colors.get(value, h_color)],
c=value, r=self._colors[m_color]))
self._device.write('{s}{m}{e}'.format(s=self._colors[m_color],
m=message.format(*_values), e=self._colors['ENDC']))
self._device.write(os.linesep)
self._device.flush() | [
"def",
"highlight",
"(",
"self",
",",
"message",
",",
"*",
"values",
",",
"*",
"*",
"colors",
")",
":",
"m_color",
"=",
"colors",
".",
"get",
"(",
"'_main'",
",",
"self",
".",
"_default_color",
")",
"h_color",
"=",
"colors",
".",
"get",
"(",
"'_highl... | Highlighter works the way that message parameter is a template,
the "values" is a list of arguments going one after another as values there.
And so the "colors" should designate either highlight color or alternate for each.
Example:
highlight('Hello {}, there! It is {}.', 'user', 'daytime', _main='GREEN', _highlight='RED')
highlight('Hello {}, there! It is {}.', 'user', 'daytime', _main='GREEN', _highlight='RED', 'daytime'='YELLOW')
First example will highlight all the values in the template with the red color.
Second example will highlight the second value with the yellow color.
Usage:
colors:
_main: Sets the main color (or default is used)
_highlight: Sets the alternative color for everything
'any phrase' that is the same in the "values" can override color.
:param message:
:param formatted:
:param colors:
:return: | [
"Highlighter",
"works",
"the",
"way",
"that",
"message",
"parameter",
"is",
"a",
"template",
"the",
"values",
"is",
"a",
"list",
"of",
"arguments",
"going",
"one",
"after",
"another",
"as",
"values",
"there",
".",
"And",
"so",
"the",
"colors",
"should",
"d... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/console.py#L110-L147 | train |
saltstack/salt | salt/modules/nspawn.py | _ensure_exists | def _ensure_exists(wrapped):
'''
Decorator to ensure that the named container exists.
'''
@functools.wraps(wrapped)
def check_exists(name, *args, **kwargs):
if not exists(name):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
return wrapped(name, *args, **salt.utils.args.clean_kwargs(**kwargs))
return check_exists | python | def _ensure_exists(wrapped):
'''
Decorator to ensure that the named container exists.
'''
@functools.wraps(wrapped)
def check_exists(name, *args, **kwargs):
if not exists(name):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
return wrapped(name, *args, **salt.utils.args.clean_kwargs(**kwargs))
return check_exists | [
"def",
"_ensure_exists",
"(",
"wrapped",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"wrapped",
")",
"def",
"check_exists",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"exists",
"(",
"name",
")",
":",
"raise",
... | Decorator to ensure that the named container exists. | [
"Decorator",
"to",
"ensure",
"that",
"the",
"named",
"container",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L79-L90 | train |
saltstack/salt | salt/modules/nspawn.py | _root | def _root(name='', all_roots=False):
'''
Return the container root directory. Starting with systemd 219, new
images go into /var/lib/machines.
'''
if _sd_version() >= 219:
if all_roots:
return [os.path.join(x, name)
for x in ('/var/lib/machines', '/var/lib/container')]
else:
return os.path.join('/var/lib/machines', name)
else:
ret = os.path.join('/var/lib/container', name)
if all_roots:
return [ret]
else:
return ret | python | def _root(name='', all_roots=False):
'''
Return the container root directory. Starting with systemd 219, new
images go into /var/lib/machines.
'''
if _sd_version() >= 219:
if all_roots:
return [os.path.join(x, name)
for x in ('/var/lib/machines', '/var/lib/container')]
else:
return os.path.join('/var/lib/machines', name)
else:
ret = os.path.join('/var/lib/container', name)
if all_roots:
return [ret]
else:
return ret | [
"def",
"_root",
"(",
"name",
"=",
"''",
",",
"all_roots",
"=",
"False",
")",
":",
"if",
"_sd_version",
"(",
")",
">=",
"219",
":",
"if",
"all_roots",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"x",
",",
"name",
")",
"for",
"x",
"i... | Return the container root directory. Starting with systemd 219, new
images go into /var/lib/machines. | [
"Return",
"the",
"container",
"root",
"directory",
".",
"Starting",
"with",
"systemd",
"219",
"new",
"images",
"go",
"into",
"/",
"var",
"/",
"lib",
"/",
"machines",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L93-L109 | train |
saltstack/salt | salt/modules/nspawn.py | _make_container_root | def _make_container_root(name):
'''
Make the container root directory
'''
path = _root(name)
if os.path.exists(path):
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError(
'Container {0} already exists'.format(name)
)
else:
try:
os.makedirs(path)
return path
except OSError as exc:
raise CommandExecutionError(
'Unable to make container root directory {0}: {1}'
.format(name, exc)
) | python | def _make_container_root(name):
'''
Make the container root directory
'''
path = _root(name)
if os.path.exists(path):
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError(
'Container {0} already exists'.format(name)
)
else:
try:
os.makedirs(path)
return path
except OSError as exc:
raise CommandExecutionError(
'Unable to make container root directory {0}: {1}'
.format(name, exc)
) | [
"def",
"_make_container_root",
"(",
"name",
")",
":",
"path",
"=",
"_root",
"(",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"__context__",
"[",
"'retcode'",
"]",
"=",
"salt",
".",
"defaults",
".",
"exitcodes",
".",
"S... | Make the container root directory | [
"Make",
"the",
"container",
"root",
"directory"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L112-L130 | train |
saltstack/salt | salt/modules/nspawn.py | _bootstrap_arch | def _bootstrap_arch(name, **kwargs):
'''
Bootstrap an Arch Linux container
'''
if not salt.utils.path.which('pacstrap'):
raise CommandExecutionError(
'pacstrap not found, is the arch-install-scripts package '
'installed?'
)
dst = _make_container_root(name)
cmd = 'pacstrap -c -d {0} base'.format(dst)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_build_failed(dst, name)
return ret | python | def _bootstrap_arch(name, **kwargs):
'''
Bootstrap an Arch Linux container
'''
if not salt.utils.path.which('pacstrap'):
raise CommandExecutionError(
'pacstrap not found, is the arch-install-scripts package '
'installed?'
)
dst = _make_container_root(name)
cmd = 'pacstrap -c -d {0} base'.format(dst)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_build_failed(dst, name)
return ret | [
"def",
"_bootstrap_arch",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'pacstrap'",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'pacstrap not found, is the arch-install-scripts package '"... | Bootstrap an Arch Linux container | [
"Bootstrap",
"an",
"Arch",
"Linux",
"container"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L147-L161 | train |
saltstack/salt | salt/modules/nspawn.py | _bootstrap_debian | def _bootstrap_debian(name, **kwargs):
'''
Bootstrap a Debian Linux container
'''
version = kwargs.get('version', False)
if not version:
if __grains__['os'].lower() == 'debian':
version = __grains__['osrelease']
else:
version = 'stable'
release_blacklist = ['hamm', 'slink', 'potato', 'woody', 'sarge', 'etch', 'lenny', 'squeeze', 'wheezy']
if version in release_blacklist:
raise CommandExecutionError(
'Unsupported Debian version "{0}". '
'Only "stable" or "jessie" and newer are supported'.format(version)
)
dst = _make_container_root(name)
cmd = 'debootstrap --arch=amd64 {0} {1}'.format(version, dst)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_build_failed(dst, name)
return ret | python | def _bootstrap_debian(name, **kwargs):
'''
Bootstrap a Debian Linux container
'''
version = kwargs.get('version', False)
if not version:
if __grains__['os'].lower() == 'debian':
version = __grains__['osrelease']
else:
version = 'stable'
release_blacklist = ['hamm', 'slink', 'potato', 'woody', 'sarge', 'etch', 'lenny', 'squeeze', 'wheezy']
if version in release_blacklist:
raise CommandExecutionError(
'Unsupported Debian version "{0}". '
'Only "stable" or "jessie" and newer are supported'.format(version)
)
dst = _make_container_root(name)
cmd = 'debootstrap --arch=amd64 {0} {1}'.format(version, dst)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_build_failed(dst, name)
return ret | [
"def",
"_bootstrap_debian",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"version",
"=",
"kwargs",
".",
"get",
"(",
"'version'",
",",
"False",
")",
"if",
"not",
"version",
":",
"if",
"__grains__",
"[",
"'os'",
"]",
".",
"lower",
"(",
")",
"==",
... | Bootstrap a Debian Linux container | [
"Bootstrap",
"a",
"Debian",
"Linux",
"container"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L164-L187 | train |
saltstack/salt | salt/modules/nspawn.py | _bootstrap_fedora | def _bootstrap_fedora(name, **kwargs):
'''
Bootstrap a Fedora container
'''
dst = _make_container_root(name)
if not kwargs.get('version', False):
if __grains__['os'].lower() == 'fedora':
version = __grains__['osrelease']
else:
version = '21'
else:
version = '21'
cmd = ('yum -y --releasever={0} --nogpg --installroot={1} '
'--disablerepo="*" --enablerepo=fedora install systemd passwd yum '
'fedora-release vim-minimal'.format(version, dst))
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_build_failed(dst, name)
return ret | python | def _bootstrap_fedora(name, **kwargs):
'''
Bootstrap a Fedora container
'''
dst = _make_container_root(name)
if not kwargs.get('version', False):
if __grains__['os'].lower() == 'fedora':
version = __grains__['osrelease']
else:
version = '21'
else:
version = '21'
cmd = ('yum -y --releasever={0} --nogpg --installroot={1} '
'--disablerepo="*" --enablerepo=fedora install systemd passwd yum '
'fedora-release vim-minimal'.format(version, dst))
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_build_failed(dst, name)
return ret | [
"def",
"_bootstrap_fedora",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"dst",
"=",
"_make_container_root",
"(",
"name",
")",
"if",
"not",
"kwargs",
".",
"get",
"(",
"'version'",
",",
"False",
")",
":",
"if",
"__grains__",
"[",
"'os'",
"]",
".",
... | Bootstrap a Fedora container | [
"Bootstrap",
"a",
"Fedora",
"container"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L190-L208 | train |
saltstack/salt | salt/modules/nspawn.py | _ensure_systemd | def _ensure_systemd(version):
'''
Raises an exception if the systemd version is not greater than the
passed version.
'''
try:
version = int(version)
except ValueError:
raise CommandExecutionError('Invalid version \'{0}\''.format(version))
try:
installed = _sd_version()
log.debug('nspawn: detected systemd %s', installed)
except (IndexError, ValueError):
raise CommandExecutionError('nspawn: Unable to get systemd version')
if installed < version:
raise CommandExecutionError(
'This function requires systemd >= {0} '
'(Detected version: {1}).'.format(version, installed)
) | python | def _ensure_systemd(version):
'''
Raises an exception if the systemd version is not greater than the
passed version.
'''
try:
version = int(version)
except ValueError:
raise CommandExecutionError('Invalid version \'{0}\''.format(version))
try:
installed = _sd_version()
log.debug('nspawn: detected systemd %s', installed)
except (IndexError, ValueError):
raise CommandExecutionError('nspawn: Unable to get systemd version')
if installed < version:
raise CommandExecutionError(
'This function requires systemd >= {0} '
'(Detected version: {1}).'.format(version, installed)
) | [
"def",
"_ensure_systemd",
"(",
"version",
")",
":",
"try",
":",
"version",
"=",
"int",
"(",
"version",
")",
"except",
"ValueError",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid version \\'{0}\\''",
".",
"format",
"(",
"version",
")",
")",
"try",
":",
... | Raises an exception if the systemd version is not greater than the
passed version. | [
"Raises",
"an",
"exception",
"if",
"the",
"systemd",
"version",
"is",
"not",
"greater",
"than",
"the",
"passed",
"version",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L248-L268 | train |
saltstack/salt | salt/modules/nspawn.py | _machinectl | def _machinectl(cmd,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False):
'''
Helper function to run machinectl
'''
prefix = 'machinectl --no-legend --no-pager'
return __salt__['cmd.run_all']('{0} {1}'.format(prefix, cmd),
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt) | python | def _machinectl(cmd,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False):
'''
Helper function to run machinectl
'''
prefix = 'machinectl --no-legend --no-pager'
return __salt__['cmd.run_all']('{0} {1}'.format(prefix, cmd),
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt) | [
"def",
"_machinectl",
"(",
"cmd",
",",
"output_loglevel",
"=",
"'debug'",
",",
"ignore_retcode",
"=",
"False",
",",
"use_vt",
"=",
"False",
")",
":",
"prefix",
"=",
"'machinectl --no-legend --no-pager'",
"return",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"'{0... | Helper function to run machinectl | [
"Helper",
"function",
"to",
"run",
"machinectl"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L271-L282 | train |
saltstack/salt | salt/modules/nspawn.py | _run | def _run(name,
cmd,
output=None,
no_start=False,
stdin=None,
python_shell=True,
preserve_state=False,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False,
keep_env=None):
'''
Common logic for nspawn.run functions
'''
orig_state = state(name)
exc = None
try:
ret = __salt__['container_resource.run'](
name,
cmd,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
except Exception:
raise
finally:
# Make sure we stop the container if necessary, even if an exception
# was raised.
if preserve_state \
and orig_state == 'stopped' \
and state(name) != 'stopped':
stop(name)
if output in (None, 'all'):
return ret
else:
return ret[output] | python | def _run(name,
cmd,
output=None,
no_start=False,
stdin=None,
python_shell=True,
preserve_state=False,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False,
keep_env=None):
'''
Common logic for nspawn.run functions
'''
orig_state = state(name)
exc = None
try:
ret = __salt__['container_resource.run'](
name,
cmd,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
except Exception:
raise
finally:
# Make sure we stop the container if necessary, even if an exception
# was raised.
if preserve_state \
and orig_state == 'stopped' \
and state(name) != 'stopped':
stop(name)
if output in (None, 'all'):
return ret
else:
return ret[output] | [
"def",
"_run",
"(",
"name",
",",
"cmd",
",",
"output",
"=",
"None",
",",
"no_start",
"=",
"False",
",",
"stdin",
"=",
"None",
",",
"python_shell",
"=",
"True",
",",
"preserve_state",
"=",
"False",
",",
"output_loglevel",
"=",
"'debug'",
",",
"ignore_retc... | Common logic for nspawn.run functions | [
"Common",
"logic",
"for",
"nspawn",
".",
"run",
"functions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L286-L329 | train |
saltstack/salt | salt/modules/nspawn.py | pid | def pid(name):
'''
Returns the PID of a container
name
Container name
CLI Example:
.. code-block:: bash
salt myminion nspawn.pid arch1
'''
try:
return int(info(name).get('PID'))
except (TypeError, ValueError) as exc:
raise CommandExecutionError(
'Unable to get PID for container \'{0}\': {1}'.format(name, exc)
) | python | def pid(name):
'''
Returns the PID of a container
name
Container name
CLI Example:
.. code-block:: bash
salt myminion nspawn.pid arch1
'''
try:
return int(info(name).get('PID'))
except (TypeError, ValueError) as exc:
raise CommandExecutionError(
'Unable to get PID for container \'{0}\': {1}'.format(name, exc)
) | [
"def",
"pid",
"(",
"name",
")",
":",
"try",
":",
"return",
"int",
"(",
"info",
"(",
"name",
")",
".",
"get",
"(",
"'PID'",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
"as",
"exc",
":",
"raise",
"CommandExecutionError",
"(",
"'Unable... | Returns the PID of a container
name
Container name
CLI Example:
.. code-block:: bash
salt myminion nspawn.pid arch1 | [
"Returns",
"the",
"PID",
"of",
"a",
"container"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L333-L351 | train |
saltstack/salt | salt/modules/nspawn.py | bootstrap_container | def bootstrap_container(name, dist=None, version=None):
'''
Bootstrap a container from package servers, if dist is None the os the
minion is running as will be created, otherwise the needed bootstrapping
tools will need to be available on the host.
CLI Example:
.. code-block:: bash
salt myminion nspawn.bootstrap_container <name>
'''
if not dist:
dist = __grains__['os'].lower()
log.debug('nspawn.bootstrap: no dist provided, defaulting to \'%s\'', dist)
try:
return globals()['_bootstrap_{0}'.format(dist)](name, version=version)
except KeyError:
raise CommandExecutionError('Unsupported distribution "{0}"'.format(dist)) | python | def bootstrap_container(name, dist=None, version=None):
'''
Bootstrap a container from package servers, if dist is None the os the
minion is running as will be created, otherwise the needed bootstrapping
tools will need to be available on the host.
CLI Example:
.. code-block:: bash
salt myminion nspawn.bootstrap_container <name>
'''
if not dist:
dist = __grains__['os'].lower()
log.debug('nspawn.bootstrap: no dist provided, defaulting to \'%s\'', dist)
try:
return globals()['_bootstrap_{0}'.format(dist)](name, version=version)
except KeyError:
raise CommandExecutionError('Unsupported distribution "{0}"'.format(dist)) | [
"def",
"bootstrap_container",
"(",
"name",
",",
"dist",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"if",
"not",
"dist",
":",
"dist",
"=",
"__grains__",
"[",
"'os'",
"]",
".",
"lower",
"(",
")",
"log",
".",
"debug",
"(",
"'nspawn.bootstrap: no ... | Bootstrap a container from package servers, if dist is None the os the
minion is running as will be created, otherwise the needed bootstrapping
tools will need to be available on the host.
CLI Example:
.. code-block:: bash
salt myminion nspawn.bootstrap_container <name> | [
"Bootstrap",
"a",
"container",
"from",
"package",
"servers",
"if",
"dist",
"is",
"None",
"the",
"os",
"the",
"minion",
"is",
"running",
"as",
"will",
"be",
"created",
"otherwise",
"the",
"needed",
"bootstrapping",
"tools",
"will",
"need",
"to",
"be",
"availa... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L673-L691 | train |
saltstack/salt | salt/modules/nspawn.py | bootstrap_salt | def bootstrap_salt(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Bootstrap a container from package servers, if dist is None the os the
minion is running as will be created, otherwise the needed bootstrapping
tools will need to be available on the host.
CLI Example::
salt '*' nspawn.bootstrap_salt arch1
'''
if bootstrap_delay is not None:
try:
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name)
else:
needs_install = True
seeded = retcode(name, 'test -e \'{0}\''.format(SEED_MARKER)) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/tmp/.c_{0}'.format(rstr)
run(name,
'install -m 0700 -d {0}'.format(configdir),
python_shell=False)
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
dest_dir = os.path.join('/tmp', rstr)
for cmd in [
'mkdir -p {0}'.format(dest_dir),
'chmod 700 {0}'.format(dest_dir),
]:
if run_stdout(name, cmd):
log.error('tmpdir %s creation failed (%s)', dest_dir, cmd)
return False
copy_to(name,
bs_,
'{0}/bootstrap.sh'.format(dest_dir),
makedirs=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'))
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'))
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'))
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2}/bootstrap.sh {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
dest_dir))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
use_vt=True) == 0
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name, cfg_files['config'], '/etc/salt/minion')
copy_to(name, cfg_files['privkey'], os.path.join(pki_dir, 'minion.pem'))
copy_to(name, cfg_files['pubkey'], os.path.join(pki_dir, 'minion.pub'))
run(name,
'salt-call --local service.enable salt-minion',
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
python_shell=False)
return ret | python | def bootstrap_salt(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Bootstrap a container from package servers, if dist is None the os the
minion is running as will be created, otherwise the needed bootstrapping
tools will need to be available on the host.
CLI Example::
salt '*' nspawn.bootstrap_salt arch1
'''
if bootstrap_delay is not None:
try:
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name)
else:
needs_install = True
seeded = retcode(name, 'test -e \'{0}\''.format(SEED_MARKER)) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/tmp/.c_{0}'.format(rstr)
run(name,
'install -m 0700 -d {0}'.format(configdir),
python_shell=False)
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
dest_dir = os.path.join('/tmp', rstr)
for cmd in [
'mkdir -p {0}'.format(dest_dir),
'chmod 700 {0}'.format(dest_dir),
]:
if run_stdout(name, cmd):
log.error('tmpdir %s creation failed (%s)', dest_dir, cmd)
return False
copy_to(name,
bs_,
'{0}/bootstrap.sh'.format(dest_dir),
makedirs=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'))
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'))
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'))
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2}/bootstrap.sh {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
dest_dir))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
use_vt=True) == 0
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name, cfg_files['config'], '/etc/salt/minion')
copy_to(name, cfg_files['privkey'], os.path.join(pki_dir, 'minion.pem'))
copy_to(name, cfg_files['pubkey'], os.path.join(pki_dir, 'minion.pub'))
run(name,
'salt-call --local service.enable salt-minion',
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
python_shell=False)
return ret | [
"def",
"bootstrap_salt",
"(",
"name",
",",
"config",
"=",
"None",
",",
"approve_key",
"=",
"True",
",",
"install",
"=",
"True",
",",
"pub_key",
"=",
"None",
",",
"priv_key",
"=",
"None",
",",
"bootstrap_url",
"=",
"None",
",",
"force_install",
"=",
"Fals... | Bootstrap a container from package servers, if dist is None the os the
minion is running as will be created, otherwise the needed bootstrapping
tools will need to be available on the host.
CLI Example::
salt '*' nspawn.bootstrap_salt arch1 | [
"Bootstrap",
"a",
"container",
"from",
"package",
"servers",
"if",
"dist",
"is",
"None",
"the",
"os",
"the",
"minion",
"is",
"running",
"as",
"will",
"be",
"created",
"otherwise",
"the",
"needed",
"bootstrapping",
"tools",
"will",
"need",
"to",
"be",
"availa... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L712-L831 | train |
saltstack/salt | salt/modules/nspawn.py | list_all | def list_all():
'''
Lists all nspawn containers
CLI Example:
.. code-block:: bash
salt myminion nspawn.list_all
'''
ret = []
if _sd_version() >= 219:
for line in _machinectl('list-images')['stdout'].splitlines():
try:
ret.append(line.split()[0])
except IndexError:
continue
else:
rootdir = _root()
try:
for dirname in os.listdir(rootdir):
if os.path.isdir(os.path.join(rootdir, dirname)):
ret.append(dirname)
except OSError:
pass
return ret | python | def list_all():
'''
Lists all nspawn containers
CLI Example:
.. code-block:: bash
salt myminion nspawn.list_all
'''
ret = []
if _sd_version() >= 219:
for line in _machinectl('list-images')['stdout'].splitlines():
try:
ret.append(line.split()[0])
except IndexError:
continue
else:
rootdir = _root()
try:
for dirname in os.listdir(rootdir):
if os.path.isdir(os.path.join(rootdir, dirname)):
ret.append(dirname)
except OSError:
pass
return ret | [
"def",
"list_all",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"_sd_version",
"(",
")",
">=",
"219",
":",
"for",
"line",
"in",
"_machinectl",
"(",
"'list-images'",
")",
"[",
"'stdout'",
"]",
".",
"splitlines",
"(",
")",
":",
"try",
":",
"ret",
".",
... | Lists all nspawn containers
CLI Example:
.. code-block:: bash
salt myminion nspawn.list_all | [
"Lists",
"all",
"nspawn",
"containers"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L834-L859 | train |
saltstack/salt | salt/modules/nspawn.py | list_running | def list_running():
'''
Lists running nspawn containers
.. note::
``nspawn.list`` also works to list running containers
CLI Example:
.. code-block:: bash
salt myminion nspawn.list_running
salt myminion nspawn.list
'''
ret = []
for line in _machinectl('list')['stdout'].splitlines():
try:
ret.append(line.split()[0])
except IndexError:
pass
return sorted(ret) | python | def list_running():
'''
Lists running nspawn containers
.. note::
``nspawn.list`` also works to list running containers
CLI Example:
.. code-block:: bash
salt myminion nspawn.list_running
salt myminion nspawn.list
'''
ret = []
for line in _machinectl('list')['stdout'].splitlines():
try:
ret.append(line.split()[0])
except IndexError:
pass
return sorted(ret) | [
"def",
"list_running",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"line",
"in",
"_machinectl",
"(",
"'list'",
")",
"[",
"'stdout'",
"]",
".",
"splitlines",
"(",
")",
":",
"try",
":",
"ret",
".",
"append",
"(",
"line",
".",
"split",
"(",
")",
"["... | Lists running nspawn containers
.. note::
``nspawn.list`` also works to list running containers
CLI Example:
.. code-block:: bash
salt myminion nspawn.list_running
salt myminion nspawn.list | [
"Lists",
"running",
"nspawn",
"containers"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L862-L883 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.