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/launchctl_service.py | get_all | def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
cmd = 'launchctl list'
service_lines = [
line for line in __salt__['cmd.run'](cmd).splitlines()
if not line.startswith('PID')
]
service_labels_from_list = [
line.split("\t")[2] for line in service_lines
]
service_labels_from_services = list(_available_services().keys())
return sorted(set(service_labels_from_list + service_labels_from_services)) | python | def get_all():
'''
Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
cmd = 'launchctl list'
service_lines = [
line for line in __salt__['cmd.run'](cmd).splitlines()
if not line.startswith('PID')
]
service_labels_from_list = [
line.split("\t")[2] for line in service_lines
]
service_labels_from_services = list(_available_services().keys())
return sorted(set(service_labels_from_list + service_labels_from_services)) | [
"def",
"get_all",
"(",
")",
":",
"cmd",
"=",
"'launchctl list'",
"service_lines",
"=",
"[",
"line",
"for",
"line",
"in",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"if",
"not",
"line",
".",
"startswith",
"(",
"'PID... | Return all installed services
CLI Example:
.. code-block:: bash
salt '*' service.get_all | [
"Return",
"all",
"installed",
"services"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/launchctl_service.py#L151-L173 | train |
saltstack/salt | salt/modules/launchctl_service.py | status | def status(name, runas=None):
'''
Return the status for a service via systemd.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
runas (str): User to run launchctl commands
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
service_info = _service_by_name(service)
lookup_name = service_info['plist']['Label'] if service_info else service
launchctl_data = _get_launchctl_data(lookup_name, runas=runas)
if launchctl_data:
if BEFORE_YOSEMITE:
if six.PY3:
results[service] = 'PID' in plistlib.loads(launchctl_data)
else:
results[service] = 'PID' in dict(plistlib.readPlistFromString(launchctl_data))
else:
pattern = '"PID" = [0-9]+;'
results[service] = True if re.search(pattern, launchctl_data) else False
else:
results[service] = False
if contains_globbing:
return results
return results[name] | python | def status(name, runas=None):
'''
Return the status for a service via systemd.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
runas (str): User to run launchctl commands
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name>
'''
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
service_info = _service_by_name(service)
lookup_name = service_info['plist']['Label'] if service_info else service
launchctl_data = _get_launchctl_data(lookup_name, runas=runas)
if launchctl_data:
if BEFORE_YOSEMITE:
if six.PY3:
results[service] = 'PID' in plistlib.loads(launchctl_data)
else:
results[service] = 'PID' in dict(plistlib.readPlistFromString(launchctl_data))
else:
pattern = '"PID" = [0-9]+;'
results[service] = True if re.search(pattern, launchctl_data) else False
else:
results[service] = False
if contains_globbing:
return results
return results[name] | [
"def",
"status",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"contains_globbing",
"=",
"bool",
"(",
"re",
".",
"search",
"(",
"r'\\*|\\?|\\[.+\\]'",
",",
"name",
")",
")",
"if",
"contains_globbing",
":",
"services",
"=",
"fnmatch",
".",
"filter",
"... | Return the status for a service via systemd.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
runas (str): User to run launchctl commands
Returns:
bool: True if running, False otherwise
dict: Maps service name to True if running, False otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name> | [
"Return",
"the",
"status",
"for",
"a",
"service",
"via",
"systemd",
".",
"If",
"the",
"name",
"contains",
"globbing",
"a",
"dict",
"mapping",
"service",
"name",
"to",
"True",
"/",
"False",
"values",
"is",
"returned",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/launchctl_service.py#L222-L271 | train |
saltstack/salt | salt/modules/launchctl_service.py | start | def start(job_label, runas=None):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service label>
salt '*' service.start org.ntp.ntpd
salt '*' service.start /System/Library/LaunchDaemons/org.ntp.ntpd.plist
'''
service = _service_by_name(job_label)
if service:
cmd = 'launchctl load -w {0}'.format(service['file_path'], runas=runas)
return not __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False)
return False | python | def start(job_label, runas=None):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service label>
salt '*' service.start org.ntp.ntpd
salt '*' service.start /System/Library/LaunchDaemons/org.ntp.ntpd.plist
'''
service = _service_by_name(job_label)
if service:
cmd = 'launchctl load -w {0}'.format(service['file_path'], runas=runas)
return not __salt__['cmd.retcode'](cmd, runas=runas, python_shell=False)
return False | [
"def",
"start",
"(",
"job_label",
",",
"runas",
"=",
"None",
")",
":",
"service",
"=",
"_service_by_name",
"(",
"job_label",
")",
"if",
"service",
":",
"cmd",
"=",
"'launchctl load -w {0}'",
".",
"format",
"(",
"service",
"[",
"'file_path'",
"]",
",",
"run... | Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service label>
salt '*' service.start org.ntp.ntpd
salt '*' service.start /System/Library/LaunchDaemons/org.ntp.ntpd.plist | [
"Start",
"the",
"specified",
"service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/launchctl_service.py#L295-L312 | train |
saltstack/salt | salt/modules/launchctl_service.py | restart | def restart(job_label, runas=None):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service label>
'''
stop(job_label, runas=runas)
return start(job_label, runas=runas) | python | def restart(job_label, runas=None):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service label>
'''
stop(job_label, runas=runas)
return start(job_label, runas=runas) | [
"def",
"restart",
"(",
"job_label",
",",
"runas",
"=",
"None",
")",
":",
"stop",
"(",
"job_label",
",",
"runas",
"=",
"runas",
")",
"return",
"start",
"(",
"job_label",
",",
"runas",
"=",
"runas",
")"
] | Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service label> | [
"Restart",
"the",
"named",
"service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/launchctl_service.py#L315-L326 | train |
saltstack/salt | salt/modules/launchctl_service.py | enabled | def enabled(job_label, runas=None):
'''
Return True if the named service is enabled, false otherwise
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service label>
'''
overrides_data = dict(plistlib.readPlist(
'/var/db/launchd.db/com.apple.launchd/overrides.plist'
))
if overrides_data.get(job_label, False):
if overrides_data[job_label]['Disabled']:
return False
else:
return True
else:
return False | python | def enabled(job_label, runas=None):
'''
Return True if the named service is enabled, false otherwise
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service label>
'''
overrides_data = dict(plistlib.readPlist(
'/var/db/launchd.db/com.apple.launchd/overrides.plist'
))
if overrides_data.get(job_label, False):
if overrides_data[job_label]['Disabled']:
return False
else:
return True
else:
return False | [
"def",
"enabled",
"(",
"job_label",
",",
"runas",
"=",
"None",
")",
":",
"overrides_data",
"=",
"dict",
"(",
"plistlib",
".",
"readPlist",
"(",
"'/var/db/launchd.db/com.apple.launchd/overrides.plist'",
")",
")",
"if",
"overrides_data",
".",
"get",
"(",
"job_label"... | Return True if the named service is enabled, false otherwise
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service label> | [
"Return",
"True",
"if",
"the",
"named",
"service",
"is",
"enabled",
"false",
"otherwise"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/launchctl_service.py#L329-L348 | train |
saltstack/salt | salt/modules/mandrill.py | _get_api_params | def _get_api_params(api_url=None,
api_version=None,
api_key=None):
'''
Retrieve the API params from the config file.
'''
mandrill_cfg = __salt__['config.merge']('mandrill')
if not mandrill_cfg:
mandrill_cfg = {}
return {
'api_url': api_url or mandrill_cfg.get('api_url') or BASE_URL, # optional
'api_key': api_key or mandrill_cfg.get('key'), # mandatory
'api_version': api_version or mandrill_cfg.get('api_version') or DEFAULT_VERSION
} | python | def _get_api_params(api_url=None,
api_version=None,
api_key=None):
'''
Retrieve the API params from the config file.
'''
mandrill_cfg = __salt__['config.merge']('mandrill')
if not mandrill_cfg:
mandrill_cfg = {}
return {
'api_url': api_url or mandrill_cfg.get('api_url') or BASE_URL, # optional
'api_key': api_key or mandrill_cfg.get('key'), # mandatory
'api_version': api_version or mandrill_cfg.get('api_version') or DEFAULT_VERSION
} | [
"def",
"_get_api_params",
"(",
"api_url",
"=",
"None",
",",
"api_version",
"=",
"None",
",",
"api_key",
"=",
"None",
")",
":",
"mandrill_cfg",
"=",
"__salt__",
"[",
"'config.merge'",
"]",
"(",
"'mandrill'",
")",
"if",
"not",
"mandrill_cfg",
":",
"mandrill_cf... | Retrieve the API params from the config file. | [
"Retrieve",
"the",
"API",
"params",
"from",
"the",
"config",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mandrill.py#L64-L77 | train |
saltstack/salt | salt/modules/mandrill.py | _get_url | def _get_url(method,
api_url,
api_version):
'''
Build the API URL.
'''
return '{url}/{version}/{method}.json'.format(url=api_url,
version=float(api_version),
method=method) | python | def _get_url(method,
api_url,
api_version):
'''
Build the API URL.
'''
return '{url}/{version}/{method}.json'.format(url=api_url,
version=float(api_version),
method=method) | [
"def",
"_get_url",
"(",
"method",
",",
"api_url",
",",
"api_version",
")",
":",
"return",
"'{url}/{version}/{method}.json'",
".",
"format",
"(",
"url",
"=",
"api_url",
",",
"version",
"=",
"float",
"(",
"api_version",
")",
",",
"method",
"=",
"method",
")"
] | Build the API URL. | [
"Build",
"the",
"API",
"URL",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mandrill.py#L80-L88 | train |
saltstack/salt | salt/modules/mandrill.py | _http_request | def _http_request(url,
headers=None,
data=None):
'''
Make the HTTP request and return the body as python object.
'''
if not headers:
headers = _get_headers()
session = requests.session()
log.debug('Querying %s', url)
req = session.post(url,
headers=headers,
data=salt.utils.json.dumps(data))
req_body = req.json()
ret = _default_ret()
log.debug('Status code: %d', req.status_code)
log.debug('Response body:')
log.debug(req_body)
if req.status_code != 200:
if req.status_code == 500:
ret['comment'] = req_body.pop('message', '')
ret['out'] = req_body
return ret
ret.update({
'comment': req_body.get('error', '')
})
return ret
ret.update({
'result': True,
'out': req.json()
})
return ret | python | def _http_request(url,
headers=None,
data=None):
'''
Make the HTTP request and return the body as python object.
'''
if not headers:
headers = _get_headers()
session = requests.session()
log.debug('Querying %s', url)
req = session.post(url,
headers=headers,
data=salt.utils.json.dumps(data))
req_body = req.json()
ret = _default_ret()
log.debug('Status code: %d', req.status_code)
log.debug('Response body:')
log.debug(req_body)
if req.status_code != 200:
if req.status_code == 500:
ret['comment'] = req_body.pop('message', '')
ret['out'] = req_body
return ret
ret.update({
'comment': req_body.get('error', '')
})
return ret
ret.update({
'result': True,
'out': req.json()
})
return ret | [
"def",
"_http_request",
"(",
"url",
",",
"headers",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"if",
"not",
"headers",
":",
"headers",
"=",
"_get_headers",
"(",
")",
"session",
"=",
"requests",
".",
"session",
"(",
")",
"log",
".",
"debug",
"("... | Make the HTTP request and return the body as python object. | [
"Make",
"the",
"HTTP",
"request",
"and",
"return",
"the",
"body",
"as",
"python",
"object",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mandrill.py#L101-L132 | train |
saltstack/salt | salt/modules/mandrill.py | send | def send(message,
asynchronous=False,
ip_pool=None,
send_at=None,
api_url=None,
api_version=None,
api_key=None,
**kwargs):
'''
Send out the email using the details from the ``message`` argument.
message
The information on the message to send. This argument must be
sent as dictionary with at fields as specified in the Mandrill API
documentation.
asynchronous: ``False``
Enable a background sending mode that is optimized for bulk sending.
In asynchronous mode, messages/send will immediately return a status of
"queued" for every recipient. To handle rejections when sending in asynchronous
mode, set up a webhook for the 'reject' event. Defaults to false for
messages with no more than 10 recipients; messages with more than 10
recipients are always sent asynchronously, regardless of the value of
asynchronous.
ip_pool
The name of the dedicated ip pool that should be used to send the
message. If you do not have any dedicated IPs, this parameter has no
effect. If you specify a pool that does not exist, your default pool
will be used instead.
send_at
When this message should be sent as a UTC timestamp in
``YYYY-MM-DD HH:MM:SS`` format. If you specify a time in the past,
the message will be sent immediately. An additional fee applies for
scheduled email, and this feature is only available to accounts with a
positive balance.
.. note::
Fur further details please consult the `API documentation <https://mandrillapp.com/api/docs/messages.dart.html>`_.
CLI Example:
.. code-block:: bash
$ salt '*' mandrill.send message="{'subject': 'Hi', 'from_email': 'test@example.com', 'to': [{'email': 'recv@example.com', 'type': 'to'}]}"
``message`` structure example (as YAML for readability):
.. code-block:: yaml
message:
text: |
This is the body of the email.
This is the second line.
subject: Email subject
from_name: Test At Example Dot Com
from_email: test@example.com
to:
- email: recv@example.com
type: to
name: Recv At Example Dot Com
- email: cc@example.com
type: cc
name: CC At Example Dot Com
important: true
track_clicks: true
track_opens: true
attachments:
- type: text/x-yaml
name: yaml_file.yml
content: aV9hbV9zdXBlcl9jdXJpb3VzOiB0cnVl
Output example:
.. code-block:: bash
minion:
----------
comment:
out:
|_
----------
_id:
c4353540a3c123eca112bbdd704ab6
email:
recv@example.com
reject_reason:
None
status:
sent
result:
True
'''
if 'async' in kwargs: # Remove this in Sodium
salt.utils.versions.warn_until('Sodium', 'Parameter "async" is renamed to "asynchronous" '
'and will be removed in version {version}.')
asynchronous = bool(kwargs['async'])
params = _get_api_params(api_url=api_url,
api_version=api_version,
api_key=api_key)
url = _get_url('messages/send',
api_url=params['api_url'],
api_version=params['api_version'])
data = {
'key': params['api_key'],
'message': message,
'async': asynchronous,
'ip_pool': ip_pool,
'send_at': send_at
}
return _http_request(url, data=data) | python | def send(message,
asynchronous=False,
ip_pool=None,
send_at=None,
api_url=None,
api_version=None,
api_key=None,
**kwargs):
'''
Send out the email using the details from the ``message`` argument.
message
The information on the message to send. This argument must be
sent as dictionary with at fields as specified in the Mandrill API
documentation.
asynchronous: ``False``
Enable a background sending mode that is optimized for bulk sending.
In asynchronous mode, messages/send will immediately return a status of
"queued" for every recipient. To handle rejections when sending in asynchronous
mode, set up a webhook for the 'reject' event. Defaults to false for
messages with no more than 10 recipients; messages with more than 10
recipients are always sent asynchronously, regardless of the value of
asynchronous.
ip_pool
The name of the dedicated ip pool that should be used to send the
message. If you do not have any dedicated IPs, this parameter has no
effect. If you specify a pool that does not exist, your default pool
will be used instead.
send_at
When this message should be sent as a UTC timestamp in
``YYYY-MM-DD HH:MM:SS`` format. If you specify a time in the past,
the message will be sent immediately. An additional fee applies for
scheduled email, and this feature is only available to accounts with a
positive balance.
.. note::
Fur further details please consult the `API documentation <https://mandrillapp.com/api/docs/messages.dart.html>`_.
CLI Example:
.. code-block:: bash
$ salt '*' mandrill.send message="{'subject': 'Hi', 'from_email': 'test@example.com', 'to': [{'email': 'recv@example.com', 'type': 'to'}]}"
``message`` structure example (as YAML for readability):
.. code-block:: yaml
message:
text: |
This is the body of the email.
This is the second line.
subject: Email subject
from_name: Test At Example Dot Com
from_email: test@example.com
to:
- email: recv@example.com
type: to
name: Recv At Example Dot Com
- email: cc@example.com
type: cc
name: CC At Example Dot Com
important: true
track_clicks: true
track_opens: true
attachments:
- type: text/x-yaml
name: yaml_file.yml
content: aV9hbV9zdXBlcl9jdXJpb3VzOiB0cnVl
Output example:
.. code-block:: bash
minion:
----------
comment:
out:
|_
----------
_id:
c4353540a3c123eca112bbdd704ab6
email:
recv@example.com
reject_reason:
None
status:
sent
result:
True
'''
if 'async' in kwargs: # Remove this in Sodium
salt.utils.versions.warn_until('Sodium', 'Parameter "async" is renamed to "asynchronous" '
'and will be removed in version {version}.')
asynchronous = bool(kwargs['async'])
params = _get_api_params(api_url=api_url,
api_version=api_version,
api_key=api_key)
url = _get_url('messages/send',
api_url=params['api_url'],
api_version=params['api_version'])
data = {
'key': params['api_key'],
'message': message,
'async': asynchronous,
'ip_pool': ip_pool,
'send_at': send_at
}
return _http_request(url, data=data) | [
"def",
"send",
"(",
"message",
",",
"asynchronous",
"=",
"False",
",",
"ip_pool",
"=",
"None",
",",
"send_at",
"=",
"None",
",",
"api_url",
"=",
"None",
",",
"api_version",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
... | Send out the email using the details from the ``message`` argument.
message
The information on the message to send. This argument must be
sent as dictionary with at fields as specified in the Mandrill API
documentation.
asynchronous: ``False``
Enable a background sending mode that is optimized for bulk sending.
In asynchronous mode, messages/send will immediately return a status of
"queued" for every recipient. To handle rejections when sending in asynchronous
mode, set up a webhook for the 'reject' event. Defaults to false for
messages with no more than 10 recipients; messages with more than 10
recipients are always sent asynchronously, regardless of the value of
asynchronous.
ip_pool
The name of the dedicated ip pool that should be used to send the
message. If you do not have any dedicated IPs, this parameter has no
effect. If you specify a pool that does not exist, your default pool
will be used instead.
send_at
When this message should be sent as a UTC timestamp in
``YYYY-MM-DD HH:MM:SS`` format. If you specify a time in the past,
the message will be sent immediately. An additional fee applies for
scheduled email, and this feature is only available to accounts with a
positive balance.
.. note::
Fur further details please consult the `API documentation <https://mandrillapp.com/api/docs/messages.dart.html>`_.
CLI Example:
.. code-block:: bash
$ salt '*' mandrill.send message="{'subject': 'Hi', 'from_email': 'test@example.com', 'to': [{'email': 'recv@example.com', 'type': 'to'}]}"
``message`` structure example (as YAML for readability):
.. code-block:: yaml
message:
text: |
This is the body of the email.
This is the second line.
subject: Email subject
from_name: Test At Example Dot Com
from_email: test@example.com
to:
- email: recv@example.com
type: to
name: Recv At Example Dot Com
- email: cc@example.com
type: cc
name: CC At Example Dot Com
important: true
track_clicks: true
track_opens: true
attachments:
- type: text/x-yaml
name: yaml_file.yml
content: aV9hbV9zdXBlcl9jdXJpb3VzOiB0cnVl
Output example:
.. code-block:: bash
minion:
----------
comment:
out:
|_
----------
_id:
c4353540a3c123eca112bbdd704ab6
email:
recv@example.com
reject_reason:
None
status:
sent
result:
True | [
"Send",
"out",
"the",
"email",
"using",
"the",
"details",
"from",
"the",
"message",
"argument",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mandrill.py#L140-L252 | train |
saltstack/salt | salt/states/modjk_worker.py | _send_command | def _send_command(cmd,
worker,
lbn,
target,
profile='default',
tgt_type='glob'):
'''
Send a command to the modjk loadbalancer
The minion need to be able to publish the commands to the load balancer
cmd:
worker_stop - won't get any traffic from the lbn
worker_activate - activate the worker
worker_disable - will get traffic only for current sessions
'''
ret = {
'code': False,
'msg': 'OK',
'minions': [],
}
# Send the command to target
func = 'modjk.{0}'.format(cmd)
args = [worker, lbn, profile]
response = __salt__['publish.publish'](target, func, args, tgt_type)
# Get errors and list of affeced minions
errors = []
minions = []
for minion in response:
minions.append(minion)
if not response[minion]:
errors.append(minion)
# parse response
if not response:
ret['msg'] = 'no servers answered the published command {0}'.format(
cmd
)
return ret
elif errors:
ret['msg'] = 'the following minions return False'
ret['minions'] = errors
return ret
else:
ret['code'] = True
ret['msg'] = 'the commad was published successfully'
ret['minions'] = minions
return ret | python | def _send_command(cmd,
worker,
lbn,
target,
profile='default',
tgt_type='glob'):
'''
Send a command to the modjk loadbalancer
The minion need to be able to publish the commands to the load balancer
cmd:
worker_stop - won't get any traffic from the lbn
worker_activate - activate the worker
worker_disable - will get traffic only for current sessions
'''
ret = {
'code': False,
'msg': 'OK',
'minions': [],
}
# Send the command to target
func = 'modjk.{0}'.format(cmd)
args = [worker, lbn, profile]
response = __salt__['publish.publish'](target, func, args, tgt_type)
# Get errors and list of affeced minions
errors = []
minions = []
for minion in response:
minions.append(minion)
if not response[minion]:
errors.append(minion)
# parse response
if not response:
ret['msg'] = 'no servers answered the published command {0}'.format(
cmd
)
return ret
elif errors:
ret['msg'] = 'the following minions return False'
ret['minions'] = errors
return ret
else:
ret['code'] = True
ret['msg'] = 'the commad was published successfully'
ret['minions'] = minions
return ret | [
"def",
"_send_command",
"(",
"cmd",
",",
"worker",
",",
"lbn",
",",
"target",
",",
"profile",
"=",
"'default'",
",",
"tgt_type",
"=",
"'glob'",
")",
":",
"ret",
"=",
"{",
"'code'",
":",
"False",
",",
"'msg'",
":",
"'OK'",
",",
"'minions'",
":",
"[",
... | Send a command to the modjk loadbalancer
The minion need to be able to publish the commands to the load balancer
cmd:
worker_stop - won't get any traffic from the lbn
worker_activate - activate the worker
worker_disable - will get traffic only for current sessions | [
"Send",
"a",
"command",
"to",
"the",
"modjk",
"loadbalancer",
"The",
"minion",
"need",
"to",
"be",
"able",
"to",
"publish",
"the",
"commands",
"to",
"the",
"load",
"balancer"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/modjk_worker.py#L31-L80 | train |
saltstack/salt | salt/states/modjk_worker.py | _worker_status | def _worker_status(target,
worker,
activation,
profile='default',
tgt_type='glob'):
'''
Check if the worker is in `activation` state in the targeted load balancers
The function will return the following dictionary:
result - False if no server returned from the published command
errors - list of servers that couldn't find the worker
wrong_state - list of servers that the worker was in the wrong state
(not activation)
'''
ret = {
'result': True,
'errors': [],
'wrong_state': [],
}
args = [worker, profile]
status = __salt__['publish.publish'](
target, 'modjk.worker_status', args, tgt_type
)
# Did we got any respone from someone ?
if not status:
ret['result'] = False
return ret
# Search for errors & status
for balancer in status:
if not status[balancer]:
ret['errors'].append(balancer)
elif status[balancer]['activation'] != activation:
ret['wrong_state'].append(balancer)
return ret | python | def _worker_status(target,
worker,
activation,
profile='default',
tgt_type='glob'):
'''
Check if the worker is in `activation` state in the targeted load balancers
The function will return the following dictionary:
result - False if no server returned from the published command
errors - list of servers that couldn't find the worker
wrong_state - list of servers that the worker was in the wrong state
(not activation)
'''
ret = {
'result': True,
'errors': [],
'wrong_state': [],
}
args = [worker, profile]
status = __salt__['publish.publish'](
target, 'modjk.worker_status', args, tgt_type
)
# Did we got any respone from someone ?
if not status:
ret['result'] = False
return ret
# Search for errors & status
for balancer in status:
if not status[balancer]:
ret['errors'].append(balancer)
elif status[balancer]['activation'] != activation:
ret['wrong_state'].append(balancer)
return ret | [
"def",
"_worker_status",
"(",
"target",
",",
"worker",
",",
"activation",
",",
"profile",
"=",
"'default'",
",",
"tgt_type",
"=",
"'glob'",
")",
":",
"ret",
"=",
"{",
"'result'",
":",
"True",
",",
"'errors'",
":",
"[",
"]",
",",
"'wrong_state'",
":",
"... | Check if the worker is in `activation` state in the targeted load balancers
The function will return the following dictionary:
result - False if no server returned from the published command
errors - list of servers that couldn't find the worker
wrong_state - list of servers that the worker was in the wrong state
(not activation) | [
"Check",
"if",
"the",
"worker",
"is",
"in",
"activation",
"state",
"in",
"the",
"targeted",
"load",
"balancers"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/modjk_worker.py#L83-L121 | train |
saltstack/salt | salt/states/modjk_worker.py | _talk2modjk | def _talk2modjk(name, lbn, target, action, profile='default', tgt_type='glob'):
'''
Wrapper function for the stop/disable/activate functions
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
action_map = {
'worker_stop': 'STP',
'worker_disable': 'DIS',
'worker_activate': 'ACT',
}
# Check what needs to be done
status = _worker_status(
target, name, action_map[action], profile, tgt_type
)
if not status['result']:
ret['result'] = False
ret['comment'] = ('no servers answered the published command '
'modjk.worker_status')
return ret
if status['errors']:
ret['result'] = False
ret['comment'] = ('the following balancers could not find the '
'worker {0}: {1}'.format(name, status['errors']))
return ret
if not status['wrong_state']:
ret['comment'] = ('the worker is in the desired activation state on '
'all the balancers')
return ret
else:
ret['comment'] = ('the action {0} will be sent to the balancers '
'{1}'.format(action, status['wrong_state']))
ret['changes'] = {action: status['wrong_state']}
if __opts__['test']:
ret['result'] = None
return ret
# Send the action command to target
response = _send_command(action, name, lbn, target, profile, tgt_type)
ret['comment'] = response['msg']
ret['result'] = response['code']
return ret | python | def _talk2modjk(name, lbn, target, action, profile='default', tgt_type='glob'):
'''
Wrapper function for the stop/disable/activate functions
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
action_map = {
'worker_stop': 'STP',
'worker_disable': 'DIS',
'worker_activate': 'ACT',
}
# Check what needs to be done
status = _worker_status(
target, name, action_map[action], profile, tgt_type
)
if not status['result']:
ret['result'] = False
ret['comment'] = ('no servers answered the published command '
'modjk.worker_status')
return ret
if status['errors']:
ret['result'] = False
ret['comment'] = ('the following balancers could not find the '
'worker {0}: {1}'.format(name, status['errors']))
return ret
if not status['wrong_state']:
ret['comment'] = ('the worker is in the desired activation state on '
'all the balancers')
return ret
else:
ret['comment'] = ('the action {0} will be sent to the balancers '
'{1}'.format(action, status['wrong_state']))
ret['changes'] = {action: status['wrong_state']}
if __opts__['test']:
ret['result'] = None
return ret
# Send the action command to target
response = _send_command(action, name, lbn, target, profile, tgt_type)
ret['comment'] = response['msg']
ret['result'] = response['code']
return ret | [
"def",
"_talk2modjk",
"(",
"name",
",",
"lbn",
",",
"target",
",",
"action",
",",
"profile",
"=",
"'default'",
",",
"tgt_type",
"=",
"'glob'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",... | Wrapper function for the stop/disable/activate functions | [
"Wrapper",
"function",
"for",
"the",
"stop",
"/",
"disable",
"/",
"activate",
"functions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/modjk_worker.py#L124-L171 | train |
saltstack/salt | salt/states/modjk_worker.py | stop | def stop(name, lbn, target, profile='default', tgt_type='glob'):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Stop the named worker from the lbn load balancers at the targeted minions
The worker won't get any traffic from the lbn
Example:
.. code-block:: yaml
disable-before-deploy:
modjk_worker.stop:
- name: {{ grains['id'] }}
- lbn: application
- target: 'roles:balancer'
- tgt_type: grain
'''
return _talk2modjk(name, lbn, target, 'worker_stop', profile, tgt_type) | python | def stop(name, lbn, target, profile='default', tgt_type='glob'):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Stop the named worker from the lbn load balancers at the targeted minions
The worker won't get any traffic from the lbn
Example:
.. code-block:: yaml
disable-before-deploy:
modjk_worker.stop:
- name: {{ grains['id'] }}
- lbn: application
- target: 'roles:balancer'
- tgt_type: grain
'''
return _talk2modjk(name, lbn, target, 'worker_stop', profile, tgt_type) | [
"def",
"stop",
"(",
"name",
",",
"lbn",
",",
"target",
",",
"profile",
"=",
"'default'",
",",
"tgt_type",
"=",
"'glob'",
")",
":",
"return",
"_talk2modjk",
"(",
"name",
",",
"lbn",
",",
"target",
",",
"'worker_stop'",
",",
"profile",
",",
"tgt_type",
"... | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Stop the named worker from the lbn load balancers at the targeted minions
The worker won't get any traffic from the lbn
Example:
.. code-block:: yaml
disable-before-deploy:
modjk_worker.stop:
- name: {{ grains['id'] }}
- lbn: application
- target: 'roles:balancer'
- tgt_type: grain | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0",
"The",
"expr_form",
"argument",
"has",
"been",
"renamed",
"to",
"tgt_type",
"earlier",
"releases",
"must",
"use",
"expr_form",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/modjk_worker.py#L174-L194 | train |
saltstack/salt | salt/states/modjk_worker.py | activate | def activate(name, lbn, target, profile='default', tgt_type='glob'):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Activate the named worker from the lbn load balancers at the targeted
minions
Example:
.. code-block:: yaml
disable-before-deploy:
modjk_worker.activate:
- name: {{ grains['id'] }}
- lbn: application
- target: 'roles:balancer'
- tgt_type: grain
'''
return _talk2modjk(name, lbn, target, 'worker_activate', profile, tgt_type) | python | def activate(name, lbn, target, profile='default', tgt_type='glob'):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Activate the named worker from the lbn load balancers at the targeted
minions
Example:
.. code-block:: yaml
disable-before-deploy:
modjk_worker.activate:
- name: {{ grains['id'] }}
- lbn: application
- target: 'roles:balancer'
- tgt_type: grain
'''
return _talk2modjk(name, lbn, target, 'worker_activate', profile, tgt_type) | [
"def",
"activate",
"(",
"name",
",",
"lbn",
",",
"target",
",",
"profile",
"=",
"'default'",
",",
"tgt_type",
"=",
"'glob'",
")",
":",
"return",
"_talk2modjk",
"(",
"name",
",",
"lbn",
",",
"target",
",",
"'worker_activate'",
",",
"profile",
",",
"tgt_ty... | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Activate the named worker from the lbn load balancers at the targeted
minions
Example:
.. code-block:: yaml
disable-before-deploy:
modjk_worker.activate:
- name: {{ grains['id'] }}
- lbn: application
- target: 'roles:balancer'
- tgt_type: grain | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0",
"The",
"expr_form",
"argument",
"has",
"been",
"renamed",
"to",
"tgt_type",
"earlier",
"releases",
"must",
"use",
"expr_form",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/modjk_worker.py#L197-L217 | train |
saltstack/salt | salt/states/modjk_worker.py | disable | def disable(name, lbn, target, profile='default', tgt_type='glob'):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Disable the named worker from the lbn load balancers at the targeted
minions. The worker will get traffic only for current sessions and won't
get new ones.
Example:
.. code-block:: yaml
disable-before-deploy:
modjk_worker.disable:
- name: {{ grains['id'] }}
- lbn: application
- target: 'roles:balancer'
- tgt_type: grain
'''
return _talk2modjk(name, lbn, target, 'worker_disable', profile, tgt_type) | python | def disable(name, lbn, target, profile='default', tgt_type='glob'):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Disable the named worker from the lbn load balancers at the targeted
minions. The worker will get traffic only for current sessions and won't
get new ones.
Example:
.. code-block:: yaml
disable-before-deploy:
modjk_worker.disable:
- name: {{ grains['id'] }}
- lbn: application
- target: 'roles:balancer'
- tgt_type: grain
'''
return _talk2modjk(name, lbn, target, 'worker_disable', profile, tgt_type) | [
"def",
"disable",
"(",
"name",
",",
"lbn",
",",
"target",
",",
"profile",
"=",
"'default'",
",",
"tgt_type",
"=",
"'glob'",
")",
":",
"return",
"_talk2modjk",
"(",
"name",
",",
"lbn",
",",
"target",
",",
"'worker_disable'",
",",
"profile",
",",
"tgt_type... | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Disable the named worker from the lbn load balancers at the targeted
minions. The worker will get traffic only for current sessions and won't
get new ones.
Example:
.. code-block:: yaml
disable-before-deploy:
modjk_worker.disable:
- name: {{ grains['id'] }}
- lbn: application
- target: 'roles:balancer'
- tgt_type: grain | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0",
"The",
"expr_form",
"argument",
"has",
"been",
"renamed",
"to",
"tgt_type",
"earlier",
"releases",
"must",
"use",
"expr_form",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/modjk_worker.py#L220-L241 | train |
saltstack/salt | salt/grains/metadata.py | _search | def _search(prefix="latest/"):
'''
Recursively look up all grains in the metadata server
'''
ret = {}
linedata = http.query(os.path.join(HOST, prefix), headers=True)
if 'body' not in linedata:
return ret
body = salt.utils.stringutils.to_unicode(linedata['body'])
if linedata['headers'].get('Content-Type', 'text/plain') == 'application/octet-stream':
return body
for line in body.split('\n'):
if line.endswith('/'):
ret[line[:-1]] = _search(prefix=os.path.join(prefix, line))
elif prefix == 'latest/':
# (gtmanfred) The first level should have a forward slash since
# they have stuff underneath. This will not be doubled up though,
# because lines ending with a slash are checked first.
ret[line] = _search(prefix=os.path.join(prefix, line + '/'))
elif line.endswith(('dynamic', 'meta-data')):
ret[line] = _search(prefix=os.path.join(prefix, line))
elif '=' in line:
key, value = line.split('=')
ret[value] = _search(prefix=os.path.join(prefix, key))
else:
retdata = http.query(os.path.join(HOST, prefix, line)).get('body', None)
# (gtmanfred) This try except block is slightly faster than
# checking if the string starts with a curly brace
if isinstance(retdata, six.binary_type):
try:
ret[line] = salt.utils.json.loads(salt.utils.stringutils.to_unicode(retdata))
except ValueError:
ret[line] = salt.utils.stringutils.to_unicode(retdata)
else:
ret[line] = retdata
return salt.utils.data.decode(ret) | python | def _search(prefix="latest/"):
'''
Recursively look up all grains in the metadata server
'''
ret = {}
linedata = http.query(os.path.join(HOST, prefix), headers=True)
if 'body' not in linedata:
return ret
body = salt.utils.stringutils.to_unicode(linedata['body'])
if linedata['headers'].get('Content-Type', 'text/plain') == 'application/octet-stream':
return body
for line in body.split('\n'):
if line.endswith('/'):
ret[line[:-1]] = _search(prefix=os.path.join(prefix, line))
elif prefix == 'latest/':
# (gtmanfred) The first level should have a forward slash since
# they have stuff underneath. This will not be doubled up though,
# because lines ending with a slash are checked first.
ret[line] = _search(prefix=os.path.join(prefix, line + '/'))
elif line.endswith(('dynamic', 'meta-data')):
ret[line] = _search(prefix=os.path.join(prefix, line))
elif '=' in line:
key, value = line.split('=')
ret[value] = _search(prefix=os.path.join(prefix, key))
else:
retdata = http.query(os.path.join(HOST, prefix, line)).get('body', None)
# (gtmanfred) This try except block is slightly faster than
# checking if the string starts with a curly brace
if isinstance(retdata, six.binary_type):
try:
ret[line] = salt.utils.json.loads(salt.utils.stringutils.to_unicode(retdata))
except ValueError:
ret[line] = salt.utils.stringutils.to_unicode(retdata)
else:
ret[line] = retdata
return salt.utils.data.decode(ret) | [
"def",
"_search",
"(",
"prefix",
"=",
"\"latest/\"",
")",
":",
"ret",
"=",
"{",
"}",
"linedata",
"=",
"http",
".",
"query",
"(",
"os",
".",
"path",
".",
"join",
"(",
"HOST",
",",
"prefix",
")",
",",
"headers",
"=",
"True",
")",
"if",
"'body'",
"n... | Recursively look up all grains in the metadata server | [
"Recursively",
"look",
"up",
"all",
"grains",
"in",
"the",
"metadata",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/metadata.py#L49-L84 | train |
saltstack/salt | salt/client/ssh/wrapper/grains.py | has_value | def has_value(key):
'''
Determine whether a named value exists in the grains dictionary.
Given a grains dictionary that contains the following structure::
{'pkg': {'apache': 'httpd'}}
One would determine if the apache key in the pkg dict exists by::
pkg:apache
CLI Example:
.. code-block:: bash
salt '*' grains.has_value pkg:apache
'''
return True \
if salt.utils.data.traverse_dict_and_list(__grains__, key, False) \
else False | python | def has_value(key):
'''
Determine whether a named value exists in the grains dictionary.
Given a grains dictionary that contains the following structure::
{'pkg': {'apache': 'httpd'}}
One would determine if the apache key in the pkg dict exists by::
pkg:apache
CLI Example:
.. code-block:: bash
salt '*' grains.has_value pkg:apache
'''
return True \
if salt.utils.data.traverse_dict_and_list(__grains__, key, False) \
else False | [
"def",
"has_value",
"(",
"key",
")",
":",
"return",
"True",
"if",
"salt",
".",
"utils",
".",
"data",
".",
"traverse_dict_and_list",
"(",
"__grains__",
",",
"key",
",",
"False",
")",
"else",
"False"
] | Determine whether a named value exists in the grains dictionary.
Given a grains dictionary that contains the following structure::
{'pkg': {'apache': 'httpd'}}
One would determine if the apache key in the pkg dict exists by::
pkg:apache
CLI Example:
.. code-block:: bash
salt '*' grains.has_value pkg:apache | [
"Determine",
"whether",
"a",
"named",
"value",
"exists",
"in",
"the",
"grains",
"dictionary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/grains.py#L85-L105 | train |
saltstack/salt | salt/client/ssh/wrapper/grains.py | item | def item(*args, **kwargs):
'''
Return one or more grains
CLI Example:
.. code-block:: bash
salt '*' grains.item os
salt '*' grains.item os osrelease oscodename
Sanitized CLI Example:
.. code-block:: bash
salt '*' grains.item host sanitize=True
'''
ret = {}
for arg in args:
try:
ret[arg] = __grains__[arg]
except KeyError:
pass
if salt.utils.data.is_true(kwargs.get('sanitize')):
for arg, func in six.iteritems(_SANITIZERS):
if arg in ret:
ret[arg] = func(ret[arg])
return ret | python | def item(*args, **kwargs):
'''
Return one or more grains
CLI Example:
.. code-block:: bash
salt '*' grains.item os
salt '*' grains.item os osrelease oscodename
Sanitized CLI Example:
.. code-block:: bash
salt '*' grains.item host sanitize=True
'''
ret = {}
for arg in args:
try:
ret[arg] = __grains__[arg]
except KeyError:
pass
if salt.utils.data.is_true(kwargs.get('sanitize')):
for arg, func in six.iteritems(_SANITIZERS):
if arg in ret:
ret[arg] = func(ret[arg])
return ret | [
"def",
"item",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"arg",
"in",
"args",
":",
"try",
":",
"ret",
"[",
"arg",
"]",
"=",
"__grains__",
"[",
"arg",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"salt",
... | Return one or more grains
CLI Example:
.. code-block:: bash
salt '*' grains.item os
salt '*' grains.item os osrelease oscodename
Sanitized CLI Example:
.. code-block:: bash
salt '*' grains.item host sanitize=True | [
"Return",
"one",
"or",
"more",
"grains"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/grains.py#L134-L161 | train |
saltstack/salt | salt/client/ssh/wrapper/grains.py | filter_by | def filter_by(lookup_dict,
grain='os_family',
merge=None,
default='default',
base=None):
'''
.. versionadded:: 0.17.0
Look up the given grain in a given dictionary for the current OS and return
the result
Although this may occasionally be useful at the CLI, the primary intent of
this function is for use in Jinja to make short work of creating lookup
tables for OS-specific data. For example:
.. code-block:: jinja
{% set apache = salt['grains.filter_by']({
'Debian': {'pkg': 'apache2', 'srv': 'apache2'},
'RedHat': {'pkg': 'httpd', 'srv': 'httpd'},
}), default='Debian' %}
myapache:
pkg.installed:
- name: {{ apache.pkg }}
service.running:
- name: {{ apache.srv }}
Values in the lookup table may be overridden by values in Pillar. An
example Pillar to override values in the example above could be as follows:
.. code-block:: yaml
apache:
lookup:
pkg: apache_13
srv: apache
The call to ``filter_by()`` would be modified as follows to reference those
Pillar values:
.. code-block:: jinja
{% set apache = salt['grains.filter_by']({
...
}, merge=salt['pillar.get']('apache:lookup')) %}
:param lookup_dict: A dictionary, keyed by a grain, containing a value or
values relevant to systems matching that grain. For example, a key
could be the grain for an OS and the value could the name of a package
on that particular OS.
:param grain: The name of a grain to match with the current system's
grains. For example, the value of the "os_family" grain for the current
system could be used to pull values from the ``lookup_dict``
dictionary.
:param merge: A dictionary to merge with the ``lookup_dict`` before doing
the lookup. This allows Pillar to override the values in the
``lookup_dict``. This could be useful, for example, to override the
values for non-standard package names such as when using a different
Python version from the default Python version provided by the OS
(e.g., ``python26-mysql`` instead of ``python-mysql``).
:param default: default lookup_dict's key used if the grain does not exists
or if the grain value has no match on lookup_dict.
.. versionadded:: 2014.1.0
:param base: A lookup_dict key to use for a base dictionary. The
grain-selected ``lookup_dict`` is merged over this and then finally
the ``merge`` dictionary is merged. This allows common values for
each case to be collected in the base and overridden by the grain
selection dictionary and the merge dictionary. Default is None.
.. versionadded:: 2015.8.11,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' grains.filter_by '{Debian: Debheads rule, RedHat: I love my hat}'
# this one will render {D: {E: I, G: H}, J: K}
salt '*' grains.filter_by '{A: B, C: {D: {E: F,G: H}}}' 'xxx' '{D: {E: I},J: K}' 'C'
'''
ret = lookup_dict.get(
__grains__.get(
grain, default),
lookup_dict.get(
default, None)
)
if base and base in lookup_dict:
base_values = lookup_dict[base]
if ret is None:
ret = base_values
elif isinstance(base_values, collections.Mapping):
if not isinstance(ret, collections.Mapping):
raise SaltException('filter_by default and look-up values must both be dictionaries.')
ret = salt.utils.dictupdate.update(copy.deepcopy(base_values), ret)
if merge:
if not isinstance(merge, collections.Mapping):
raise SaltException('filter_by merge argument must be a dictionary.')
else:
if ret is None:
ret = merge
else:
salt.utils.dictupdate.update(ret, merge)
return ret | python | def filter_by(lookup_dict,
grain='os_family',
merge=None,
default='default',
base=None):
'''
.. versionadded:: 0.17.0
Look up the given grain in a given dictionary for the current OS and return
the result
Although this may occasionally be useful at the CLI, the primary intent of
this function is for use in Jinja to make short work of creating lookup
tables for OS-specific data. For example:
.. code-block:: jinja
{% set apache = salt['grains.filter_by']({
'Debian': {'pkg': 'apache2', 'srv': 'apache2'},
'RedHat': {'pkg': 'httpd', 'srv': 'httpd'},
}), default='Debian' %}
myapache:
pkg.installed:
- name: {{ apache.pkg }}
service.running:
- name: {{ apache.srv }}
Values in the lookup table may be overridden by values in Pillar. An
example Pillar to override values in the example above could be as follows:
.. code-block:: yaml
apache:
lookup:
pkg: apache_13
srv: apache
The call to ``filter_by()`` would be modified as follows to reference those
Pillar values:
.. code-block:: jinja
{% set apache = salt['grains.filter_by']({
...
}, merge=salt['pillar.get']('apache:lookup')) %}
:param lookup_dict: A dictionary, keyed by a grain, containing a value or
values relevant to systems matching that grain. For example, a key
could be the grain for an OS and the value could the name of a package
on that particular OS.
:param grain: The name of a grain to match with the current system's
grains. For example, the value of the "os_family" grain for the current
system could be used to pull values from the ``lookup_dict``
dictionary.
:param merge: A dictionary to merge with the ``lookup_dict`` before doing
the lookup. This allows Pillar to override the values in the
``lookup_dict``. This could be useful, for example, to override the
values for non-standard package names such as when using a different
Python version from the default Python version provided by the OS
(e.g., ``python26-mysql`` instead of ``python-mysql``).
:param default: default lookup_dict's key used if the grain does not exists
or if the grain value has no match on lookup_dict.
.. versionadded:: 2014.1.0
:param base: A lookup_dict key to use for a base dictionary. The
grain-selected ``lookup_dict`` is merged over this and then finally
the ``merge`` dictionary is merged. This allows common values for
each case to be collected in the base and overridden by the grain
selection dictionary and the merge dictionary. Default is None.
.. versionadded:: 2015.8.11,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' grains.filter_by '{Debian: Debheads rule, RedHat: I love my hat}'
# this one will render {D: {E: I, G: H}, J: K}
salt '*' grains.filter_by '{A: B, C: {D: {E: F,G: H}}}' 'xxx' '{D: {E: I},J: K}' 'C'
'''
ret = lookup_dict.get(
__grains__.get(
grain, default),
lookup_dict.get(
default, None)
)
if base and base in lookup_dict:
base_values = lookup_dict[base]
if ret is None:
ret = base_values
elif isinstance(base_values, collections.Mapping):
if not isinstance(ret, collections.Mapping):
raise SaltException('filter_by default and look-up values must both be dictionaries.')
ret = salt.utils.dictupdate.update(copy.deepcopy(base_values), ret)
if merge:
if not isinstance(merge, collections.Mapping):
raise SaltException('filter_by merge argument must be a dictionary.')
else:
if ret is None:
ret = merge
else:
salt.utils.dictupdate.update(ret, merge)
return ret | [
"def",
"filter_by",
"(",
"lookup_dict",
",",
"grain",
"=",
"'os_family'",
",",
"merge",
"=",
"None",
",",
"default",
"=",
"'default'",
",",
"base",
"=",
"None",
")",
":",
"ret",
"=",
"lookup_dict",
".",
"get",
"(",
"__grains__",
".",
"get",
"(",
"grain... | .. versionadded:: 0.17.0
Look up the given grain in a given dictionary for the current OS and return
the result
Although this may occasionally be useful at the CLI, the primary intent of
this function is for use in Jinja to make short work of creating lookup
tables for OS-specific data. For example:
.. code-block:: jinja
{% set apache = salt['grains.filter_by']({
'Debian': {'pkg': 'apache2', 'srv': 'apache2'},
'RedHat': {'pkg': 'httpd', 'srv': 'httpd'},
}), default='Debian' %}
myapache:
pkg.installed:
- name: {{ apache.pkg }}
service.running:
- name: {{ apache.srv }}
Values in the lookup table may be overridden by values in Pillar. An
example Pillar to override values in the example above could be as follows:
.. code-block:: yaml
apache:
lookup:
pkg: apache_13
srv: apache
The call to ``filter_by()`` would be modified as follows to reference those
Pillar values:
.. code-block:: jinja
{% set apache = salt['grains.filter_by']({
...
}, merge=salt['pillar.get']('apache:lookup')) %}
:param lookup_dict: A dictionary, keyed by a grain, containing a value or
values relevant to systems matching that grain. For example, a key
could be the grain for an OS and the value could the name of a package
on that particular OS.
:param grain: The name of a grain to match with the current system's
grains. For example, the value of the "os_family" grain for the current
system could be used to pull values from the ``lookup_dict``
dictionary.
:param merge: A dictionary to merge with the ``lookup_dict`` before doing
the lookup. This allows Pillar to override the values in the
``lookup_dict``. This could be useful, for example, to override the
values for non-standard package names such as when using a different
Python version from the default Python version provided by the OS
(e.g., ``python26-mysql`` instead of ``python-mysql``).
:param default: default lookup_dict's key used if the grain does not exists
or if the grain value has no match on lookup_dict.
.. versionadded:: 2014.1.0
:param base: A lookup_dict key to use for a base dictionary. The
grain-selected ``lookup_dict`` is merged over this and then finally
the ``merge`` dictionary is merged. This allows common values for
each case to be collected in the base and overridden by the grain
selection dictionary and the merge dictionary. Default is None.
.. versionadded:: 2015.8.11,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' grains.filter_by '{Debian: Debheads rule, RedHat: I love my hat}'
# this one will render {D: {E: I, G: H}, J: K}
salt '*' grains.filter_by '{A: B, C: {D: {E: F,G: H}}}' 'xxx' '{D: {E: I},J: K}' 'C' | [
"..",
"versionadded",
"::",
"0",
".",
"17",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/grains.py#L177-L286 | train |
saltstack/salt | salt/states/boto_vpc.py | present | def present(name, cidr_block, instance_tenancy=None, dns_support=None,
dns_hostnames=None, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Ensure VPC exists.
name
Name of the VPC.
cidr_block
The range of IPs in CIDR format, for example: 10.0.0.0/24. Block
size must be between /16 and /28 netmask.
instance_tenancy
Instances launched in this VPC will be ingle-tenant or dedicated
hardware.
dns_support
Indicates whether the DNS resolution is supported for the VPC.
dns_hostnames
Indicates whether the instances launched in the VPC get DNS hostnames.
tags
A list of tags.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.exists'](name=name, tags=tags, region=region,
key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to create VPC: {0}.'.format(r['error']['message'])
return ret
if not r.get('exists'):
if __opts__['test']:
ret['comment'] = 'VPC {0} is set to be created.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.create'](cidr_block, instance_tenancy=instance_tenancy, vpc_name=name,
enable_dns_support=dns_support, enable_dns_hostnames=dns_hostnames,
tags=tags, region=region, key=key, keyid=keyid,
profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Error in creating VPC: {0}.'.format(r['error']['message'])
return ret
_describe = __salt__['boto_vpc.describe'](vpc_id=r['id'], region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['old'] = {'vpc': None}
ret['changes']['new'] = _describe
ret['comment'] = 'VPC {0} created.'.format(name)
return ret
ret['comment'] = 'VPC present.'
return ret | python | def present(name, cidr_block, instance_tenancy=None, dns_support=None,
dns_hostnames=None, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Ensure VPC exists.
name
Name of the VPC.
cidr_block
The range of IPs in CIDR format, for example: 10.0.0.0/24. Block
size must be between /16 and /28 netmask.
instance_tenancy
Instances launched in this VPC will be ingle-tenant or dedicated
hardware.
dns_support
Indicates whether the DNS resolution is supported for the VPC.
dns_hostnames
Indicates whether the instances launched in the VPC get DNS hostnames.
tags
A list of tags.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.exists'](name=name, tags=tags, region=region,
key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to create VPC: {0}.'.format(r['error']['message'])
return ret
if not r.get('exists'):
if __opts__['test']:
ret['comment'] = 'VPC {0} is set to be created.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.create'](cidr_block, instance_tenancy=instance_tenancy, vpc_name=name,
enable_dns_support=dns_support, enable_dns_hostnames=dns_hostnames,
tags=tags, region=region, key=key, keyid=keyid,
profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Error in creating VPC: {0}.'.format(r['error']['message'])
return ret
_describe = __salt__['boto_vpc.describe'](vpc_id=r['id'], region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['old'] = {'vpc': None}
ret['changes']['new'] = _describe
ret['comment'] = 'VPC {0} created.'.format(name)
return ret
ret['comment'] = 'VPC present.'
return ret | [
"def",
"present",
"(",
"name",
",",
"cidr_block",
",",
"instance_tenancy",
"=",
"None",
",",
"dns_support",
"=",
"None",
",",
"dns_hostnames",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"="... | Ensure VPC exists.
name
Name of the VPC.
cidr_block
The range of IPs in CIDR format, for example: 10.0.0.0/24. Block
size must be between /16 and /28 netmask.
instance_tenancy
Instances launched in this VPC will be ingle-tenant or dedicated
hardware.
dns_support
Indicates whether the DNS resolution is supported for the VPC.
dns_hostnames
Indicates whether the instances launched in the VPC get DNS hostnames.
tags
A list of tags.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"VPC",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L172-L245 | train |
saltstack/salt | salt/states/boto_vpc.py | absent | def absent(name, tags=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure VPC with passed properties is absent.
name
Name of the VPC.
tags
A list of tags. All tags must match.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.get_id'](name=name, tags=tags, region=region,
key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete VPC: {0}.'.format(r['error']['message'])
return ret
_id = r.get('id')
if not _id:
ret['comment'] = '{0} VPC does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'VPC {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.delete'](vpc_name=name, tags=tags,
region=region, key=key,
keyid=keyid, profile=profile)
if not r['deleted']:
ret['result'] = False
ret['comment'] = 'Failed to delete VPC: {0}.'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'vpc': _id}
ret['changes']['new'] = {'vpc': None}
ret['comment'] = 'VPC {0} deleted.'.format(name)
return ret | python | def absent(name, tags=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure VPC with passed properties is absent.
name
Name of the VPC.
tags
A list of tags. All tags must match.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.get_id'](name=name, tags=tags, region=region,
key=key, keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete VPC: {0}.'.format(r['error']['message'])
return ret
_id = r.get('id')
if not _id:
ret['comment'] = '{0} VPC does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'VPC {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.delete'](vpc_name=name, tags=tags,
region=region, key=key,
keyid=keyid, profile=profile)
if not r['deleted']:
ret['result'] = False
ret['comment'] = 'Failed to delete VPC: {0}.'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'vpc': _id}
ret['changes']['new'] = {'vpc': None}
ret['comment'] = 'VPC {0} deleted.'.format(name)
return ret | [
"def",
"absent",
"(",
"name",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
... | Ensure VPC with passed properties is absent.
name
Name of the VPC.
tags
A list of tags. All tags must match.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"VPC",
"with",
"passed",
"properties",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L248-L304 | train |
saltstack/salt | salt/states/boto_vpc.py | dhcp_options_present | def dhcp_options_present(name, dhcp_options_id=None, vpc_name=None, vpc_id=None,
domain_name=None, domain_name_servers=None, ntp_servers=None,
netbios_name_servers=None, netbios_node_type=None,
tags=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure a set of DHCP options with the given settings exist.
Note that the current implementation only SETS values during option set
creation. It is unable to update option sets in place, and thus merely
verifies the set exists via the given name and/or dhcp_options_id param.
name
(string)
Name of the DHCP options.
vpc_name
(string)
Name of a VPC to which the options should be associated. Either
vpc_name or vpc_id must be provided.
vpc_id
(string)
Id of a VPC to which the options should be associated. Either
vpc_name or vpc_id must be provided.
domain_name
(string)
Domain name to be assiciated with this option set.
domain_name_servers
(list of strings)
The IP address(es) of up to four domain name servers.
ntp_servers
(list of strings)
The IP address(es) of up to four desired NTP servers.
netbios_name_servers
(list of strings)
The IP address(es) of up to four NetBIOS name servers.
netbios_node_type
(string)
The NetBIOS node type (1, 2, 4, or 8). For more information about
the allowed values, see RFC 2132. The recommended is 2 at this
time (broadcast and multicast are currently not supported).
tags
(dict of key:value pairs)
A set of tags to be added.
region
(string)
Region to connect to.
key
(string)
Secret key to be used.
keyid
(string)
Access key to be used.
profile
(various)
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
_new = {'domain_name': domain_name,
'domain_name_servers': domain_name_servers,
'ntp_servers': ntp_servers,
'netbios_name_servers': netbios_name_servers,
'netbios_node_type': netbios_node_type
}
# boto provides no "update_dhcp_options()" functionality, and you can't delete it if
# it's attached, and you can't detach it if it's the only one, so just check if it's
# there or not, and make no effort to validate it's actual settings... :(
### TODO - add support for multiple sets of DHCP options, and then for "swapping out"
### sets by creating new, mapping, then deleting the old.
r = __salt__['boto_vpc.dhcp_options_exists'](dhcp_options_id=dhcp_options_id,
dhcp_options_name=name,
region=region, key=key, keyid=keyid,
profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to validate DHCP options: {0}.'.format(r['error']['message'])
return ret
if r.get('exists'):
ret['comment'] = 'DHCP options already present.'
return ret
else:
if __opts__['test']:
ret['comment'] = 'DHCP options {0} are set to be created.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.create_dhcp_options'](domain_name=domain_name,
domain_name_servers=domain_name_servers,
ntp_servers=ntp_servers,
netbios_name_servers=netbios_name_servers,
netbios_node_type=netbios_node_type,
dhcp_options_name=name, tags=tags,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to create DHCP options: {0}'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'dhcp_options': None}
ret['changes']['new'] = {'dhcp_options': _new}
ret['comment'] = 'DHCP options {0} created.'.format(name)
return ret | python | def dhcp_options_present(name, dhcp_options_id=None, vpc_name=None, vpc_id=None,
domain_name=None, domain_name_servers=None, ntp_servers=None,
netbios_name_servers=None, netbios_node_type=None,
tags=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure a set of DHCP options with the given settings exist.
Note that the current implementation only SETS values during option set
creation. It is unable to update option sets in place, and thus merely
verifies the set exists via the given name and/or dhcp_options_id param.
name
(string)
Name of the DHCP options.
vpc_name
(string)
Name of a VPC to which the options should be associated. Either
vpc_name or vpc_id must be provided.
vpc_id
(string)
Id of a VPC to which the options should be associated. Either
vpc_name or vpc_id must be provided.
domain_name
(string)
Domain name to be assiciated with this option set.
domain_name_servers
(list of strings)
The IP address(es) of up to four domain name servers.
ntp_servers
(list of strings)
The IP address(es) of up to four desired NTP servers.
netbios_name_servers
(list of strings)
The IP address(es) of up to four NetBIOS name servers.
netbios_node_type
(string)
The NetBIOS node type (1, 2, 4, or 8). For more information about
the allowed values, see RFC 2132. The recommended is 2 at this
time (broadcast and multicast are currently not supported).
tags
(dict of key:value pairs)
A set of tags to be added.
region
(string)
Region to connect to.
key
(string)
Secret key to be used.
keyid
(string)
Access key to be used.
profile
(various)
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
_new = {'domain_name': domain_name,
'domain_name_servers': domain_name_servers,
'ntp_servers': ntp_servers,
'netbios_name_servers': netbios_name_servers,
'netbios_node_type': netbios_node_type
}
# boto provides no "update_dhcp_options()" functionality, and you can't delete it if
# it's attached, and you can't detach it if it's the only one, so just check if it's
# there or not, and make no effort to validate it's actual settings... :(
### TODO - add support for multiple sets of DHCP options, and then for "swapping out"
### sets by creating new, mapping, then deleting the old.
r = __salt__['boto_vpc.dhcp_options_exists'](dhcp_options_id=dhcp_options_id,
dhcp_options_name=name,
region=region, key=key, keyid=keyid,
profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to validate DHCP options: {0}.'.format(r['error']['message'])
return ret
if r.get('exists'):
ret['comment'] = 'DHCP options already present.'
return ret
else:
if __opts__['test']:
ret['comment'] = 'DHCP options {0} are set to be created.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.create_dhcp_options'](domain_name=domain_name,
domain_name_servers=domain_name_servers,
ntp_servers=ntp_servers,
netbios_name_servers=netbios_name_servers,
netbios_node_type=netbios_node_type,
dhcp_options_name=name, tags=tags,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to create DHCP options: {0}'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'dhcp_options': None}
ret['changes']['new'] = {'dhcp_options': _new}
ret['comment'] = 'DHCP options {0} created.'.format(name)
return ret | [
"def",
"dhcp_options_present",
"(",
"name",
",",
"dhcp_options_id",
"=",
"None",
",",
"vpc_name",
"=",
"None",
",",
"vpc_id",
"=",
"None",
",",
"domain_name",
"=",
"None",
",",
"domain_name_servers",
"=",
"None",
",",
"ntp_servers",
"=",
"None",
",",
"netbio... | Ensure a set of DHCP options with the given settings exist.
Note that the current implementation only SETS values during option set
creation. It is unable to update option sets in place, and thus merely
verifies the set exists via the given name and/or dhcp_options_id param.
name
(string)
Name of the DHCP options.
vpc_name
(string)
Name of a VPC to which the options should be associated. Either
vpc_name or vpc_id must be provided.
vpc_id
(string)
Id of a VPC to which the options should be associated. Either
vpc_name or vpc_id must be provided.
domain_name
(string)
Domain name to be assiciated with this option set.
domain_name_servers
(list of strings)
The IP address(es) of up to four domain name servers.
ntp_servers
(list of strings)
The IP address(es) of up to four desired NTP servers.
netbios_name_servers
(list of strings)
The IP address(es) of up to four NetBIOS name servers.
netbios_node_type
(string)
The NetBIOS node type (1, 2, 4, or 8). For more information about
the allowed values, see RFC 2132. The recommended is 2 at this
time (broadcast and multicast are currently not supported).
tags
(dict of key:value pairs)
A set of tags to be added.
region
(string)
Region to connect to.
key
(string)
Secret key to be used.
keyid
(string)
Access key to be used.
profile
(various)
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0 | [
"Ensure",
"a",
"set",
"of",
"DHCP",
"options",
"with",
"the",
"given",
"settings",
"exist",
".",
"Note",
"that",
"the",
"current",
"implementation",
"only",
"SETS",
"values",
"during",
"option",
"set",
"creation",
".",
"It",
"is",
"unable",
"to",
"update",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L307-L428 | train |
saltstack/salt | salt/states/boto_vpc.py | dhcp_options_absent | def dhcp_options_absent(name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure a set of DHCP options with the given settings exist.
name
(string)
Name of the DHCP options set.
dhcp_options_id
(string)
Id of the DHCP options set.
region
(string)
Region to connect to.
key
(string)
Secret key to be used.
keyid
(string)
Access key to be used.
profile
(various)
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.get_resource_id']('dhcp_options', name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete DHCP options: {0}.'.format(r['error']['message'])
return ret
_id = r.get('id')
if not _id:
ret['comment'] = 'DHCP options {0} do not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'DHCP options {0} are set to be deleted.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.delete_dhcp_options'](dhcp_options_id=r['id'], region=region,
key=key, keyid=keyid, profile=profile)
if not r.get('deleted'):
ret['result'] = False
ret['comment'] = 'Failed to delete DHCP options: {0}'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'dhcp_options': _id}
ret['changes']['new'] = {'dhcp_options': None}
ret['comment'] = 'DHCP options {0} deleted.'.format(name)
return ret | python | def dhcp_options_absent(name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure a set of DHCP options with the given settings exist.
name
(string)
Name of the DHCP options set.
dhcp_options_id
(string)
Id of the DHCP options set.
region
(string)
Region to connect to.
key
(string)
Secret key to be used.
keyid
(string)
Access key to be used.
profile
(various)
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.get_resource_id']('dhcp_options', name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete DHCP options: {0}.'.format(r['error']['message'])
return ret
_id = r.get('id')
if not _id:
ret['comment'] = 'DHCP options {0} do not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'DHCP options {0} are set to be deleted.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.delete_dhcp_options'](dhcp_options_id=r['id'], region=region,
key=key, keyid=keyid, profile=profile)
if not r.get('deleted'):
ret['result'] = False
ret['comment'] = 'Failed to delete DHCP options: {0}'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'dhcp_options': _id}
ret['changes']['new'] = {'dhcp_options': None}
ret['comment'] = 'DHCP options {0} deleted.'.format(name)
return ret | [
"def",
"dhcp_options_absent",
"(",
"name",
"=",
"None",
",",
"dhcp_options_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name"... | Ensure a set of DHCP options with the given settings exist.
name
(string)
Name of the DHCP options set.
dhcp_options_id
(string)
Id of the DHCP options set.
region
(string)
Region to connect to.
key
(string)
Secret key to be used.
keyid
(string)
Access key to be used.
profile
(various)
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0 | [
"Ensure",
"a",
"set",
"of",
"DHCP",
"options",
"with",
"the",
"given",
"settings",
"exist",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L431-L497 | train |
saltstack/salt | salt/states/boto_vpc.py | subnet_present | def subnet_present(name, cidr_block, vpc_name=None, vpc_id=None,
availability_zone=None, tags=None,
region=None, key=None,
keyid=None, profile=None,
route_table_id=None, route_table_name=None, auto_assign_public_ipv4=False):
'''
Ensure a subnet exists.
name
Name of the subnet.
cidr_block
The range if IPs for the subnet, in CIDR format. For example:
10.0.0.0/24. Block size must be between /16 and /28 netmask.
vpc_name
Name of the VPC in which the subnet should be placed. Either
vpc_name or vpc_id must be provided.
vpc_id
Id of the VPC in which the subnet should be placed. Either vpc_name
or vpc_id must be provided.
availability_zone
AZ in which the subnet should be placed.
tags
A list of tags.
route_table_id
A route table ID to explicitly associate the subnet with. If both route_table_id
and route_table_name are specified, route_table_id will take precedence.
.. versionadded:: 2016.11.0
route_table_name
A route table name to explicitly associate the subnet with. If both route_table_id
and route_table_name are specified, route_table_id will take precedence.
.. versionadded:: 2016.11.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.subnet_exists'](subnet_name=name, tags=tags,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to create subnet: {0}.'.format(r['error']['message'])
return ret
route_table_desc = None
_describe = None
rtid = None
if route_table_id or route_table_name:
rt = None
route_table_found = False
if route_table_id:
rtid = route_table_id
rt = __salt__['boto_vpc.route_table_exists'](route_table_id=route_table_id,
region=region, key=key, keyid=keyid,
profile=profile)
elif route_table_name:
rtid = route_table_name
rt = __salt__['boto_vpc.route_table_exists'](route_table_name=route_table_name,
region=region, key=key, keyid=keyid,
profile=profile)
if rt:
if 'exists' in rt:
if rt['exists']:
if route_table_id:
route_table_found = True
route_table_desc = __salt__['boto_vpc.describe_route_table'](route_table_id=route_table_id,
region=region, key=key, keyid=keyid,
profile=profile)
elif route_table_name:
route_table_found = True
route_table_desc = __salt__['boto_vpc.describe_route_table'](route_table_name=route_table_name,
region=region, key=key, keyid=keyid,
profile=profile)
if not route_table_found:
ret['result'] = False
ret['comment'] = 'The specified route table {0} could not be found.'.format(rtid)
return ret
if not r.get('exists'):
if __opts__['test']:
ret['comment'] = 'Subnet {0} is set to be created.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.create_subnet'](subnet_name=name,
cidr_block=cidr_block,
availability_zone=availability_zone,
auto_assign_public_ipv4=auto_assign_public_ipv4,
vpc_name=vpc_name, vpc_id=vpc_id,
tags=tags, region=region,
key=key, keyid=keyid,
profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to create subnet: {0}'.format(r['error']['message'])
return ret
_describe = __salt__['boto_vpc.describe_subnet'](subnet_id=r['id'], region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['old'] = {'subnet': None}
ret['changes']['new'] = _describe
ret['comment'] = 'Subnet {0} created.'.format(name)
else:
ret['comment'] = 'Subnet present.'
if route_table_desc:
if not _describe:
_describe = __salt__['boto_vpc.describe_subnet'](subnet_name=name, region=region,
key=key, keyid=keyid, profile=profile)
if not _verify_subnet_association(route_table_desc, _describe['subnet']['id']):
if __opts__['test']:
msg = 'Subnet is set to be associated with route table {0}'.format(rtid)
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
return ret
if 'explicit_route_table_association_id' in _describe['subnet']:
log.debug('Need to disassociate from existing route table')
drt_ret = __salt__['boto_vpc.disassociate_route_table'](_describe['subnet']['explicit_route_table_association_id'],
region=region, key=key, keyid=keyid, profile=profile)
if not drt_ret['disassociated']:
msg = 'Unable to disassociate subnet {0} with its current route table.'.format(name)
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = False
return ret
if 'old' not in ret['changes']:
ret['changes']['old'] = _describe
art_ret = __salt__['boto_vpc.associate_route_table'](route_table_id=route_table_desc['id'],
subnet_name=name, region=region,
key=key, keyid=keyid, profile=profile)
if 'error' in art_ret:
msg = 'Failed to associate subnet {0} with route table {1}: {2}.'.format(name, rtid,
art_ret['error']['message'])
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = False
return ret
else:
msg = 'Subnet successfully associated with route table {0}.'.format(rtid)
ret['comment'] = ' '.join([ret['comment'], msg])
if 'new' not in ret['changes']:
ret['changes']['new'] = __salt__['boto_vpc.describe_subnet'](subnet_name=name, region=region,
key=key, keyid=keyid, profile=profile)
else:
ret['changes']['new']['subnet']['explicit_route_table_association_id'] = art_ret['association_id']
else:
ret['comment'] = ' '.join([ret['comment'],
'Subnet is already associated with route table {0}'.format(rtid)])
return ret | python | def subnet_present(name, cidr_block, vpc_name=None, vpc_id=None,
availability_zone=None, tags=None,
region=None, key=None,
keyid=None, profile=None,
route_table_id=None, route_table_name=None, auto_assign_public_ipv4=False):
'''
Ensure a subnet exists.
name
Name of the subnet.
cidr_block
The range if IPs for the subnet, in CIDR format. For example:
10.0.0.0/24. Block size must be between /16 and /28 netmask.
vpc_name
Name of the VPC in which the subnet should be placed. Either
vpc_name or vpc_id must be provided.
vpc_id
Id of the VPC in which the subnet should be placed. Either vpc_name
or vpc_id must be provided.
availability_zone
AZ in which the subnet should be placed.
tags
A list of tags.
route_table_id
A route table ID to explicitly associate the subnet with. If both route_table_id
and route_table_name are specified, route_table_id will take precedence.
.. versionadded:: 2016.11.0
route_table_name
A route table name to explicitly associate the subnet with. If both route_table_id
and route_table_name are specified, route_table_id will take precedence.
.. versionadded:: 2016.11.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.subnet_exists'](subnet_name=name, tags=tags,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to create subnet: {0}.'.format(r['error']['message'])
return ret
route_table_desc = None
_describe = None
rtid = None
if route_table_id or route_table_name:
rt = None
route_table_found = False
if route_table_id:
rtid = route_table_id
rt = __salt__['boto_vpc.route_table_exists'](route_table_id=route_table_id,
region=region, key=key, keyid=keyid,
profile=profile)
elif route_table_name:
rtid = route_table_name
rt = __salt__['boto_vpc.route_table_exists'](route_table_name=route_table_name,
region=region, key=key, keyid=keyid,
profile=profile)
if rt:
if 'exists' in rt:
if rt['exists']:
if route_table_id:
route_table_found = True
route_table_desc = __salt__['boto_vpc.describe_route_table'](route_table_id=route_table_id,
region=region, key=key, keyid=keyid,
profile=profile)
elif route_table_name:
route_table_found = True
route_table_desc = __salt__['boto_vpc.describe_route_table'](route_table_name=route_table_name,
region=region, key=key, keyid=keyid,
profile=profile)
if not route_table_found:
ret['result'] = False
ret['comment'] = 'The specified route table {0} could not be found.'.format(rtid)
return ret
if not r.get('exists'):
if __opts__['test']:
ret['comment'] = 'Subnet {0} is set to be created.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.create_subnet'](subnet_name=name,
cidr_block=cidr_block,
availability_zone=availability_zone,
auto_assign_public_ipv4=auto_assign_public_ipv4,
vpc_name=vpc_name, vpc_id=vpc_id,
tags=tags, region=region,
key=key, keyid=keyid,
profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to create subnet: {0}'.format(r['error']['message'])
return ret
_describe = __salt__['boto_vpc.describe_subnet'](subnet_id=r['id'], region=region, key=key,
keyid=keyid, profile=profile)
ret['changes']['old'] = {'subnet': None}
ret['changes']['new'] = _describe
ret['comment'] = 'Subnet {0} created.'.format(name)
else:
ret['comment'] = 'Subnet present.'
if route_table_desc:
if not _describe:
_describe = __salt__['boto_vpc.describe_subnet'](subnet_name=name, region=region,
key=key, keyid=keyid, profile=profile)
if not _verify_subnet_association(route_table_desc, _describe['subnet']['id']):
if __opts__['test']:
msg = 'Subnet is set to be associated with route table {0}'.format(rtid)
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
return ret
if 'explicit_route_table_association_id' in _describe['subnet']:
log.debug('Need to disassociate from existing route table')
drt_ret = __salt__['boto_vpc.disassociate_route_table'](_describe['subnet']['explicit_route_table_association_id'],
region=region, key=key, keyid=keyid, profile=profile)
if not drt_ret['disassociated']:
msg = 'Unable to disassociate subnet {0} with its current route table.'.format(name)
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = False
return ret
if 'old' not in ret['changes']:
ret['changes']['old'] = _describe
art_ret = __salt__['boto_vpc.associate_route_table'](route_table_id=route_table_desc['id'],
subnet_name=name, region=region,
key=key, keyid=keyid, profile=profile)
if 'error' in art_ret:
msg = 'Failed to associate subnet {0} with route table {1}: {2}.'.format(name, rtid,
art_ret['error']['message'])
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = False
return ret
else:
msg = 'Subnet successfully associated with route table {0}.'.format(rtid)
ret['comment'] = ' '.join([ret['comment'], msg])
if 'new' not in ret['changes']:
ret['changes']['new'] = __salt__['boto_vpc.describe_subnet'](subnet_name=name, region=region,
key=key, keyid=keyid, profile=profile)
else:
ret['changes']['new']['subnet']['explicit_route_table_association_id'] = art_ret['association_id']
else:
ret['comment'] = ' '.join([ret['comment'],
'Subnet is already associated with route table {0}'.format(rtid)])
return ret | [
"def",
"subnet_present",
"(",
"name",
",",
"cidr_block",
",",
"vpc_name",
"=",
"None",
",",
"vpc_id",
"=",
"None",
",",
"availability_zone",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
... | Ensure a subnet exists.
name
Name of the subnet.
cidr_block
The range if IPs for the subnet, in CIDR format. For example:
10.0.0.0/24. Block size must be between /16 and /28 netmask.
vpc_name
Name of the VPC in which the subnet should be placed. Either
vpc_name or vpc_id must be provided.
vpc_id
Id of the VPC in which the subnet should be placed. Either vpc_name
or vpc_id must be provided.
availability_zone
AZ in which the subnet should be placed.
tags
A list of tags.
route_table_id
A route table ID to explicitly associate the subnet with. If both route_table_id
and route_table_name are specified, route_table_id will take precedence.
.. versionadded:: 2016.11.0
route_table_name
A route table name to explicitly associate the subnet with. If both route_table_id
and route_table_name are specified, route_table_id will take precedence.
.. versionadded:: 2016.11.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"a",
"subnet",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L500-L671 | train |
saltstack/salt | salt/states/boto_vpc.py | _verify_subnet_association | def _verify_subnet_association(route_table_desc, subnet_id):
'''
Helper function verify a subnet's route table association
route_table_desc
the description of a route table, as returned from boto_vpc.describe_route_table
subnet_id
the subnet id to verify
.. versionadded:: 2016.11.0
'''
if route_table_desc:
if 'associations' in route_table_desc:
for association in route_table_desc['associations']:
if association['subnet_id'] == subnet_id:
return True
return False | python | def _verify_subnet_association(route_table_desc, subnet_id):
'''
Helper function verify a subnet's route table association
route_table_desc
the description of a route table, as returned from boto_vpc.describe_route_table
subnet_id
the subnet id to verify
.. versionadded:: 2016.11.0
'''
if route_table_desc:
if 'associations' in route_table_desc:
for association in route_table_desc['associations']:
if association['subnet_id'] == subnet_id:
return True
return False | [
"def",
"_verify_subnet_association",
"(",
"route_table_desc",
",",
"subnet_id",
")",
":",
"if",
"route_table_desc",
":",
"if",
"'associations'",
"in",
"route_table_desc",
":",
"for",
"association",
"in",
"route_table_desc",
"[",
"'associations'",
"]",
":",
"if",
"as... | Helper function verify a subnet's route table association
route_table_desc
the description of a route table, as returned from boto_vpc.describe_route_table
subnet_id
the subnet id to verify
.. versionadded:: 2016.11.0 | [
"Helper",
"function",
"verify",
"a",
"subnet",
"s",
"route",
"table",
"association"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L674-L691 | train |
saltstack/salt | salt/states/boto_vpc.py | subnet_absent | def subnet_absent(name=None, subnet_id=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure subnet with passed properties is absent.
name
Name of the subnet.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.get_resource_id']('subnet', name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete subnet: {0}.'.format(r['error']['message'])
return ret
_id = r.get('id')
if not _id:
ret['comment'] = '{0} subnet does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Subnet {0} ({1}) is set to be removed.'.format(name, r['id'])
ret['result'] = None
return ret
r = __salt__['boto_vpc.delete_subnet'](subnet_name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if not r.get('deleted'):
ret['result'] = False
ret['comment'] = 'Failed to delete subnet: {0}'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'subnet': _id}
ret['changes']['new'] = {'subnet': None}
ret['comment'] = 'Subnet {0} deleted.'.format(name)
return ret | python | def subnet_absent(name=None, subnet_id=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure subnet with passed properties is absent.
name
Name of the subnet.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.get_resource_id']('subnet', name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete subnet: {0}.'.format(r['error']['message'])
return ret
_id = r.get('id')
if not _id:
ret['comment'] = '{0} subnet does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Subnet {0} ({1}) is set to be removed.'.format(name, r['id'])
ret['result'] = None
return ret
r = __salt__['boto_vpc.delete_subnet'](subnet_name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if not r.get('deleted'):
ret['result'] = False
ret['comment'] = 'Failed to delete subnet: {0}'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'subnet': _id}
ret['changes']['new'] = {'subnet': None}
ret['comment'] = 'Subnet {0} deleted.'.format(name)
return ret | [
"def",
"subnet_absent",
"(",
"name",
"=",
"None",
",",
"subnet_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"... | Ensure subnet with passed properties is absent.
name
Name of the subnet.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"subnet",
"with",
"passed",
"properties",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L694-L751 | train |
saltstack/salt | salt/states/boto_vpc.py | internet_gateway_present | def internet_gateway_present(name, vpc_name=None, vpc_id=None,
tags=None, region=None, key=None,
keyid=None, profile=None):
'''
Ensure an internet gateway exists.
name
Name of the internet gateway.
vpc_name
Name of the VPC to which the internet gateway should be attached.
vpc_id
Id of the VPC to which the internet_gateway should be attached.
Only one of vpc_name or vpc_id may be provided.
tags
A list of tags.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.resource_exists']('internet_gateway', name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to create internet gateway: {0}.'.format(r['error']['message'])
return ret
if not r.get('exists'):
if __opts__['test']:
ret['comment'] = 'Internet gateway {0} is set to be created.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.create_internet_gateway'](internet_gateway_name=name,
vpc_name=vpc_name, vpc_id=vpc_id,
tags=tags, region=region,
key=key, keyid=keyid,
profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to create internet gateway: {0}'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'internet_gateway': None}
ret['changes']['new'] = {'internet_gateway': r['id']}
ret['comment'] = 'Internet gateway {0} created.'.format(name)
return ret
ret['comment'] = 'Internet gateway {0} present.'.format(name)
return ret | python | def internet_gateway_present(name, vpc_name=None, vpc_id=None,
tags=None, region=None, key=None,
keyid=None, profile=None):
'''
Ensure an internet gateway exists.
name
Name of the internet gateway.
vpc_name
Name of the VPC to which the internet gateway should be attached.
vpc_id
Id of the VPC to which the internet_gateway should be attached.
Only one of vpc_name or vpc_id may be provided.
tags
A list of tags.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.resource_exists']('internet_gateway', name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to create internet gateway: {0}.'.format(r['error']['message'])
return ret
if not r.get('exists'):
if __opts__['test']:
ret['comment'] = 'Internet gateway {0} is set to be created.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.create_internet_gateway'](internet_gateway_name=name,
vpc_name=vpc_name, vpc_id=vpc_id,
tags=tags, region=region,
key=key, keyid=keyid,
profile=profile)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to create internet gateway: {0}'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'internet_gateway': None}
ret['changes']['new'] = {'internet_gateway': r['id']}
ret['comment'] = 'Internet gateway {0} created.'.format(name)
return ret
ret['comment'] = 'Internet gateway {0} present.'.format(name)
return ret | [
"def",
"internet_gateway_present",
"(",
"name",
",",
"vpc_name",
"=",
"None",
",",
"vpc_id",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",... | Ensure an internet gateway exists.
name
Name of the internet gateway.
vpc_name
Name of the VPC to which the internet gateway should be attached.
vpc_id
Id of the VPC to which the internet_gateway should be attached.
Only one of vpc_name or vpc_id may be provided.
tags
A list of tags.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"an",
"internet",
"gateway",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L754-L821 | train |
saltstack/salt | salt/states/boto_vpc.py | internet_gateway_absent | def internet_gateway_absent(name, detach=False, region=None,
key=None, keyid=None, profile=None):
'''
Ensure the named internet gateway is absent.
name
Name of the internet gateway.
detach
First detach the internet gateway from a VPC, if attached.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.get_resource_id']('internet_gateway', name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete internet gateway: {0}.'.format(r['error']['message'])
return ret
igw_id = r['id']
if not igw_id:
ret['comment'] = 'Internet gateway {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Internet gateway {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.delete_internet_gateway'](internet_gateway_name=name,
detach=detach, region=region,
key=key, keyid=keyid,
profile=profile)
if not r.get('deleted'):
ret['result'] = False
ret['comment'] = 'Failed to delete internet gateway: {0}.'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'internet_gateway': igw_id}
ret['changes']['new'] = {'internet_gateway': None}
ret['comment'] = 'Internet gateway {0} deleted.'.format(name)
return ret | python | def internet_gateway_absent(name, detach=False, region=None,
key=None, keyid=None, profile=None):
'''
Ensure the named internet gateway is absent.
name
Name of the internet gateway.
detach
First detach the internet gateway from a VPC, if attached.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.get_resource_id']('internet_gateway', name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete internet gateway: {0}.'.format(r['error']['message'])
return ret
igw_id = r['id']
if not igw_id:
ret['comment'] = 'Internet gateway {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Internet gateway {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.delete_internet_gateway'](internet_gateway_name=name,
detach=detach, region=region,
key=key, keyid=keyid,
profile=profile)
if not r.get('deleted'):
ret['result'] = False
ret['comment'] = 'Failed to delete internet gateway: {0}.'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'internet_gateway': igw_id}
ret['changes']['new'] = {'internet_gateway': None}
ret['comment'] = 'Internet gateway {0} deleted.'.format(name)
return ret | [
"def",
"internet_gateway_absent",
"(",
"name",
",",
"detach",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'"... | Ensure the named internet gateway is absent.
name
Name of the internet gateway.
detach
First detach the internet gateway from a VPC, if attached.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"the",
"named",
"internet",
"gateway",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L824-L883 | train |
saltstack/salt | salt/states/boto_vpc.py | route_table_present | def route_table_present(name, vpc_name=None, vpc_id=None, routes=None,
subnet_ids=None, subnet_names=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Ensure route table with routes exists and is associated to a VPC.
This function requires boto3 to be installed if nat gatewyas are specified.
Example:
.. code-block:: yaml
boto_vpc.route_table_present:
- name: my_route_table
- vpc_id: vpc-123456
- routes:
- destination_cidr_block: 0.0.0.0/0
internet_gateway_name: InternetGateway
- destination_cidr_block: 10.10.11.0/24
instance_id: i-123456
- destination_cidr_block: 10.10.12.0/24
interface_id: eni-123456
- destination_cidr_block: 10.10.13.0/24
instance_name: mygatewayserver
- subnet_names:
- subnet1
- subnet2
name
Name of the route table.
vpc_name
Name of the VPC with which the route table should be associated.
vpc_id
Id of the VPC with which the route table should be associated.
Either vpc_name or vpc_id must be provided.
routes
A list of routes. Each route has a cidr and a target.
subnet_ids
A list of subnet ids to associate
subnet_names
A list of subnet names to associate
tags
A list of tags.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
_ret = _route_table_present(name=name, vpc_name=vpc_name, vpc_id=vpc_id,
tags=tags, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if ret['result'] is None and __opts__['test']:
return ret
_ret = _routes_present(route_table_name=name, routes=routes, tags=tags,
region=region, key=key, keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _subnets_present(route_table_name=name, subnet_ids=subnet_ids,
subnet_names=subnet_names, tags=tags, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
return ret | python | def route_table_present(name, vpc_name=None, vpc_id=None, routes=None,
subnet_ids=None, subnet_names=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Ensure route table with routes exists and is associated to a VPC.
This function requires boto3 to be installed if nat gatewyas are specified.
Example:
.. code-block:: yaml
boto_vpc.route_table_present:
- name: my_route_table
- vpc_id: vpc-123456
- routes:
- destination_cidr_block: 0.0.0.0/0
internet_gateway_name: InternetGateway
- destination_cidr_block: 10.10.11.0/24
instance_id: i-123456
- destination_cidr_block: 10.10.12.0/24
interface_id: eni-123456
- destination_cidr_block: 10.10.13.0/24
instance_name: mygatewayserver
- subnet_names:
- subnet1
- subnet2
name
Name of the route table.
vpc_name
Name of the VPC with which the route table should be associated.
vpc_id
Id of the VPC with which the route table should be associated.
Either vpc_name or vpc_id must be provided.
routes
A list of routes. Each route has a cidr and a target.
subnet_ids
A list of subnet ids to associate
subnet_names
A list of subnet names to associate
tags
A list of tags.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
_ret = _route_table_present(name=name, vpc_name=vpc_name, vpc_id=vpc_id,
tags=tags, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if ret['result'] is None and __opts__['test']:
return ret
_ret = _routes_present(route_table_name=name, routes=routes, tags=tags,
region=region, key=key, keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _subnets_present(route_table_name=name, subnet_ids=subnet_ids,
subnet_names=subnet_names, tags=tags, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
return ret | [
"def",
"route_table_present",
"(",
"name",
",",
"vpc_name",
"=",
"None",
",",
"vpc_id",
"=",
"None",
",",
"routes",
"=",
"None",
",",
"subnet_ids",
"=",
"None",
",",
"subnet_names",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
","... | Ensure route table with routes exists and is associated to a VPC.
This function requires boto3 to be installed if nat gatewyas are specified.
Example:
.. code-block:: yaml
boto_vpc.route_table_present:
- name: my_route_table
- vpc_id: vpc-123456
- routes:
- destination_cidr_block: 0.0.0.0/0
internet_gateway_name: InternetGateway
- destination_cidr_block: 10.10.11.0/24
instance_id: i-123456
- destination_cidr_block: 10.10.12.0/24
interface_id: eni-123456
- destination_cidr_block: 10.10.13.0/24
instance_name: mygatewayserver
- subnet_names:
- subnet1
- subnet2
name
Name of the route table.
vpc_name
Name of the VPC with which the route table should be associated.
vpc_id
Id of the VPC with which the route table should be associated.
Either vpc_name or vpc_id must be provided.
routes
A list of routes. Each route has a cidr and a target.
subnet_ids
A list of subnet ids to associate
subnet_names
A list of subnet names to associate
tags
A list of tags.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"route",
"table",
"with",
"routes",
"exists",
"and",
"is",
"associated",
"to",
"a",
"VPC",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L886-L983 | train |
saltstack/salt | salt/states/boto_vpc.py | route_table_absent | def route_table_absent(name, region=None,
key=None, keyid=None, profile=None):
'''
Ensure the named route table is absent.
name
Name of the route table.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.get_resource_id']('route_table', name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = r['error']['message']
return ret
rtbl_id = r['id']
if not rtbl_id:
ret['comment'] = 'Route table {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Route table {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.delete_route_table'](route_table_name=name,
region=region,
key=key, keyid=keyid,
profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete route table: {0}'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'route_table': rtbl_id}
ret['changes']['new'] = {'route_table': None}
ret['comment'] = 'Route table {0} deleted.'.format(name)
return ret | python | def route_table_absent(name, region=None,
key=None, keyid=None, profile=None):
'''
Ensure the named route table is absent.
name
Name of the route table.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.get_resource_id']('route_table', name=name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = r['error']['message']
return ret
rtbl_id = r['id']
if not rtbl_id:
ret['comment'] = 'Route table {0} does not exist.'.format(name)
return ret
if __opts__['test']:
ret['comment'] = 'Route table {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
r = __salt__['boto_vpc.delete_route_table'](route_table_name=name,
region=region,
key=key, keyid=keyid,
profile=profile)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete route table: {0}'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'route_table': rtbl_id}
ret['changes']['new'] = {'route_table': None}
ret['comment'] = 'Route table {0} deleted.'.format(name)
return ret | [
"def",
"route_table_absent",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
... | Ensure the named route table is absent.
name
Name of the route table.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"the",
"named",
"route",
"table",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L1235-L1293 | train |
saltstack/salt | salt/states/boto_vpc.py | nat_gateway_present | def nat_gateway_present(name, subnet_name=None, subnet_id=None,
region=None, key=None, keyid=None, profile=None, allocation_id=None):
'''
Ensure a nat gateway exists within the specified subnet
This function requires boto3.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
boto_vpc.nat_gateway_present:
- subnet_name: my-subnet
name
Name of the state
subnet_name
Name of the subnet within which the nat gateway should exist
subnet_id
Id of the subnet within which the nat gateway should exist.
Either subnet_name or subnet_id must be provided.
allocation_id
If specified, the elastic IP address referenced by the ID is
associated with the gateway. Otherwise, a new allocation_id is created and used.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.describe_nat_gateways'](subnet_name=subnet_name,
subnet_id=subnet_id,
region=region, key=key, keyid=keyid,
profile=profile)
if not r:
if __opts__['test']:
msg = 'Nat gateway is set to be created.'
ret['comment'] = msg
ret['result'] = None
return ret
r = __salt__['boto_vpc.create_nat_gateway'](subnet_name=subnet_name,
subnet_id=subnet_id,
region=region, key=key,
keyid=keyid, profile=profile,
allocation_id=allocation_id)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to create nat gateway: {0}.'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'nat_gateway': None}
ret['changes']['new'] = {'nat_gateway': r['id']}
ret['comment'] = 'Nat gateway created.'
return ret
inst = r[0]
_id = inst.get('NatGatewayId')
ret['comment'] = 'Nat gateway {0} present.'.format(_id)
return ret | python | def nat_gateway_present(name, subnet_name=None, subnet_id=None,
region=None, key=None, keyid=None, profile=None, allocation_id=None):
'''
Ensure a nat gateway exists within the specified subnet
This function requires boto3.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
boto_vpc.nat_gateway_present:
- subnet_name: my-subnet
name
Name of the state
subnet_name
Name of the subnet within which the nat gateway should exist
subnet_id
Id of the subnet within which the nat gateway should exist.
Either subnet_name or subnet_id must be provided.
allocation_id
If specified, the elastic IP address referenced by the ID is
associated with the gateway. Otherwise, a new allocation_id is created and used.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.describe_nat_gateways'](subnet_name=subnet_name,
subnet_id=subnet_id,
region=region, key=key, keyid=keyid,
profile=profile)
if not r:
if __opts__['test']:
msg = 'Nat gateway is set to be created.'
ret['comment'] = msg
ret['result'] = None
return ret
r = __salt__['boto_vpc.create_nat_gateway'](subnet_name=subnet_name,
subnet_id=subnet_id,
region=region, key=key,
keyid=keyid, profile=profile,
allocation_id=allocation_id)
if not r.get('created'):
ret['result'] = False
ret['comment'] = 'Failed to create nat gateway: {0}.'.format(r['error']['message'])
return ret
ret['changes']['old'] = {'nat_gateway': None}
ret['changes']['new'] = {'nat_gateway': r['id']}
ret['comment'] = 'Nat gateway created.'
return ret
inst = r[0]
_id = inst.get('NatGatewayId')
ret['comment'] = 'Nat gateway {0} present.'.format(_id)
return ret | [
"def",
"nat_gateway_present",
"(",
"name",
",",
"subnet_name",
"=",
"None",
",",
"subnet_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"allocation_id",
"=",
"None",
"... | Ensure a nat gateway exists within the specified subnet
This function requires boto3.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
boto_vpc.nat_gateway_present:
- subnet_name: my-subnet
name
Name of the state
subnet_name
Name of the subnet within which the nat gateway should exist
subnet_id
Id of the subnet within which the nat gateway should exist.
Either subnet_name or subnet_id must be provided.
allocation_id
If specified, the elastic IP address referenced by the ID is
associated with the gateway. Otherwise, a new allocation_id is created and used.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"a",
"nat",
"gateway",
"exists",
"within",
"the",
"specified",
"subnet"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L1296-L1374 | train |
saltstack/salt | salt/states/boto_vpc.py | nat_gateway_absent | def nat_gateway_absent(name=None, subnet_name=None, subnet_id=None,
region=None, key=None, keyid=None, profile=None,
wait_for_delete_retries=0):
'''
Ensure the nat gateway in the named subnet is absent.
This function requires boto3.
.. versionadded:: 2016.11.0
name
Name of the state.
subnet_name
Name of the subnet within which the nat gateway should exist
subnet_id
Id of the subnet within which the nat gateway should exist.
Either subnet_name or subnet_id must be provided.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
wait_for_delete_retries
NAT gateway may take some time to be go into deleted or failed state.
During the deletion process, subsequent release of elastic IPs may fail;
this state will automatically retry this number of times to ensure
the NAT gateway is in deleted or failed state before proceeding.
Default is set to 0 for backward compatibility.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.describe_nat_gateways'](subnet_name=subnet_name,
subnet_id=subnet_id,
region=region, key=key, keyid=keyid,
profile=profile)
if not r:
ret['comment'] = 'Nat gateway does not exist.'
return ret
if __opts__['test']:
ret['comment'] = 'Nat gateway is set to be removed.'
ret['result'] = None
return ret
for gw in r:
rtbl_id = gw.get('NatGatewayId')
r = __salt__['boto_vpc.delete_nat_gateway'](nat_gateway_id=rtbl_id,
release_eips=True,
region=region,
key=key, keyid=keyid,
profile=profile,
wait_for_delete=True,
wait_for_delete_retries=wait_for_delete_retries)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete nat gateway: {0}'.format(r['error']['message'])
return ret
ret['comment'] = ', '.join((ret['comment'], 'Nat gateway {0} deleted.'.format(rtbl_id)))
ret['changes']['old'] = {'nat_gateway': rtbl_id}
ret['changes']['new'] = {'nat_gateway': None}
return ret | python | def nat_gateway_absent(name=None, subnet_name=None, subnet_id=None,
region=None, key=None, keyid=None, profile=None,
wait_for_delete_retries=0):
'''
Ensure the nat gateway in the named subnet is absent.
This function requires boto3.
.. versionadded:: 2016.11.0
name
Name of the state.
subnet_name
Name of the subnet within which the nat gateway should exist
subnet_id
Id of the subnet within which the nat gateway should exist.
Either subnet_name or subnet_id must be provided.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
wait_for_delete_retries
NAT gateway may take some time to be go into deleted or failed state.
During the deletion process, subsequent release of elastic IPs may fail;
this state will automatically retry this number of times to ensure
the NAT gateway is in deleted or failed state before proceeding.
Default is set to 0 for backward compatibility.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
r = __salt__['boto_vpc.describe_nat_gateways'](subnet_name=subnet_name,
subnet_id=subnet_id,
region=region, key=key, keyid=keyid,
profile=profile)
if not r:
ret['comment'] = 'Nat gateway does not exist.'
return ret
if __opts__['test']:
ret['comment'] = 'Nat gateway is set to be removed.'
ret['result'] = None
return ret
for gw in r:
rtbl_id = gw.get('NatGatewayId')
r = __salt__['boto_vpc.delete_nat_gateway'](nat_gateway_id=rtbl_id,
release_eips=True,
region=region,
key=key, keyid=keyid,
profile=profile,
wait_for_delete=True,
wait_for_delete_retries=wait_for_delete_retries)
if 'error' in r:
ret['result'] = False
ret['comment'] = 'Failed to delete nat gateway: {0}'.format(r['error']['message'])
return ret
ret['comment'] = ', '.join((ret['comment'], 'Nat gateway {0} deleted.'.format(rtbl_id)))
ret['changes']['old'] = {'nat_gateway': rtbl_id}
ret['changes']['new'] = {'nat_gateway': None}
return ret | [
"def",
"nat_gateway_absent",
"(",
"name",
"=",
"None",
",",
"subnet_name",
"=",
"None",
",",
"subnet_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"wait_for_delete_retr... | Ensure the nat gateway in the named subnet is absent.
This function requires boto3.
.. versionadded:: 2016.11.0
name
Name of the state.
subnet_name
Name of the subnet within which the nat gateway should exist
subnet_id
Id of the subnet within which the nat gateway should exist.
Either subnet_name or subnet_id must be provided.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
wait_for_delete_retries
NAT gateway may take some time to be go into deleted or failed state.
During the deletion process, subsequent release of elastic IPs may fail;
this state will automatically retry this number of times to ensure
the NAT gateway is in deleted or failed state before proceeding.
Default is set to 0 for backward compatibility. | [
"Ensure",
"the",
"nat",
"gateway",
"in",
"the",
"named",
"subnet",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L1377-L1454 | train |
saltstack/salt | salt/states/boto_vpc.py | accept_vpc_peering_connection | def accept_vpc_peering_connection(name=None, conn_id=None, conn_name=None,
region=None, key=None, keyid=None, profile=None):
'''
Accept a VPC pending requested peering connection between two VPCs.
name
Name of this state
conn_id
The connection ID to accept. Exclusive with conn_name. String type.
conn_name
The name of the VPC peering connection to accept. Exclusive with conn_id. String type.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
boto_vpc.accept_vpc_peering_connection:
- conn_name: salt_peering_connection
# usage with vpc peering connection id and region
boto_vpc.accept_vpc_peering_connection:
- conn_id: pbx-1873d472
- region: us-west-2
'''
log.debug('Called state to accept VPC peering connection')
pending = __salt__['boto_vpc.is_peering_connection_pending'](
conn_id=conn_id, conn_name=conn_name, region=region, key=key,
keyid=keyid, profile=profile)
ret = {
'name': name,
'result': True,
'changes': {},
'comment': 'Boto VPC peering state'
}
if not pending:
ret['result'] = True
ret['changes'].update({'old':
'No pending VPC peering connection found. Nothing to be done.'})
return ret
if __opts__['test']:
ret['changes'].update({'old':
'Pending VPC peering connection found and can be accepted'})
return ret
fun = 'boto_vpc.accept_vpc_peering_connection'
log.debug('Calling `%s()` to accept this VPC peering connection', fun)
result = __salt__[fun](conn_id=conn_id, name=conn_name, region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in result:
ret['comment'] = "Failed to accept VPC peering: {0}".format(result['error'])
ret['result'] = False
return ret
ret['changes'].update({'old': '', 'new': result['msg']})
return ret | python | def accept_vpc_peering_connection(name=None, conn_id=None, conn_name=None,
region=None, key=None, keyid=None, profile=None):
'''
Accept a VPC pending requested peering connection between two VPCs.
name
Name of this state
conn_id
The connection ID to accept. Exclusive with conn_name. String type.
conn_name
The name of the VPC peering connection to accept. Exclusive with conn_id. String type.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
boto_vpc.accept_vpc_peering_connection:
- conn_name: salt_peering_connection
# usage with vpc peering connection id and region
boto_vpc.accept_vpc_peering_connection:
- conn_id: pbx-1873d472
- region: us-west-2
'''
log.debug('Called state to accept VPC peering connection')
pending = __salt__['boto_vpc.is_peering_connection_pending'](
conn_id=conn_id, conn_name=conn_name, region=region, key=key,
keyid=keyid, profile=profile)
ret = {
'name': name,
'result': True,
'changes': {},
'comment': 'Boto VPC peering state'
}
if not pending:
ret['result'] = True
ret['changes'].update({'old':
'No pending VPC peering connection found. Nothing to be done.'})
return ret
if __opts__['test']:
ret['changes'].update({'old':
'Pending VPC peering connection found and can be accepted'})
return ret
fun = 'boto_vpc.accept_vpc_peering_connection'
log.debug('Calling `%s()` to accept this VPC peering connection', fun)
result = __salt__[fun](conn_id=conn_id, name=conn_name, region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in result:
ret['comment'] = "Failed to accept VPC peering: {0}".format(result['error'])
ret['result'] = False
return ret
ret['changes'].update({'old': '', 'new': result['msg']})
return ret | [
"def",
"accept_vpc_peering_connection",
"(",
"name",
"=",
"None",
",",
"conn_id",
"=",
"None",
",",
"conn_name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"log",
... | Accept a VPC pending requested peering connection between two VPCs.
name
Name of this state
conn_id
The connection ID to accept. Exclusive with conn_name. String type.
conn_name
The name of the VPC peering connection to accept. Exclusive with conn_id. String type.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
boto_vpc.accept_vpc_peering_connection:
- conn_name: salt_peering_connection
# usage with vpc peering connection id and region
boto_vpc.accept_vpc_peering_connection:
- conn_id: pbx-1873d472
- region: us-west-2 | [
"Accept",
"a",
"VPC",
"pending",
"requested",
"peering",
"connection",
"between",
"two",
"VPCs",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L1458-L1534 | train |
saltstack/salt | salt/states/boto_vpc.py | request_vpc_peering_connection | def request_vpc_peering_connection(name, requester_vpc_id=None, requester_vpc_name=None,
peer_vpc_id=None, peer_vpc_name=None, conn_name=None,
peer_owner_id=None, peer_region=None, region=None,
key=None, keyid=None, profile=None):
'''
name
Name of the state
requester_vpc_id
ID of the requesting VPC. Exclusive with requester_vpc_name. String type.
requester_vpc_name
Name tag of the requesting VPC. Exclusive with requester_vpc_id. String type.
peer_vpc_id
ID of the VPC tp crete VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. String type.
peer_vpc_name
Name tag of the VPC tp crete VPC peering connection with. This can only be a VPC the same account and region. Exclusive with peer_vpc_id. String type.
conn_name
The (optional) name to use for this VPC peering connection. String type.
peer_owner_id
ID of the owner of the peer VPC. String type. If this isn't supplied AWS uses your account ID. Required if peering to a different account.
peer_region
Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
request a vpc peering connection:
boto_vpc.request_vpc_peering_connection:
- requester_vpc_id: vpc-4b3522e
- peer_vpc_id: vpc-ae83f9ca
- conn_name: salt_peering_connection
'''
log.debug('Called state to request VPC peering connection')
ret = {
'name': name,
'result': True,
'changes': {},
'comment': 'Boto VPC peering state'
}
if conn_name:
vpc_ids = __salt__['boto_vpc.describe_vpc_peering_connection'](
conn_name,
region=region,
key=key,
keyid=keyid,
profile=profile
).get('VPC-Peerings', [])
else:
vpc_ids = []
if vpc_ids:
ret['comment'] = ('VPC peering connection already exists, '
'nothing to be done.')
return ret
if __opts__['test']:
if not vpc_ids:
ret['comment'] = 'VPC peering connection will be created'
return ret
log.debug('Called module to create VPC peering connection')
result = __salt__['boto_vpc.request_vpc_peering_connection'](
requester_vpc_id,
requester_vpc_name,
peer_vpc_id,
peer_vpc_name,
name=conn_name,
peer_owner_id=peer_owner_id,
peer_region=peer_region,
region=region,
key=key,
keyid=keyid,
profile=profile
)
if 'error' in result:
ret['comment'] = "Failed to request VPC peering: {0}".format(result['error'])
ret['result'] = False
return ret
ret['changes'].update({
'old': '',
'new': result['msg']
})
return ret | python | def request_vpc_peering_connection(name, requester_vpc_id=None, requester_vpc_name=None,
peer_vpc_id=None, peer_vpc_name=None, conn_name=None,
peer_owner_id=None, peer_region=None, region=None,
key=None, keyid=None, profile=None):
'''
name
Name of the state
requester_vpc_id
ID of the requesting VPC. Exclusive with requester_vpc_name. String type.
requester_vpc_name
Name tag of the requesting VPC. Exclusive with requester_vpc_id. String type.
peer_vpc_id
ID of the VPC tp crete VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. String type.
peer_vpc_name
Name tag of the VPC tp crete VPC peering connection with. This can only be a VPC the same account and region. Exclusive with peer_vpc_id. String type.
conn_name
The (optional) name to use for this VPC peering connection. String type.
peer_owner_id
ID of the owner of the peer VPC. String type. If this isn't supplied AWS uses your account ID. Required if peering to a different account.
peer_region
Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
request a vpc peering connection:
boto_vpc.request_vpc_peering_connection:
- requester_vpc_id: vpc-4b3522e
- peer_vpc_id: vpc-ae83f9ca
- conn_name: salt_peering_connection
'''
log.debug('Called state to request VPC peering connection')
ret = {
'name': name,
'result': True,
'changes': {},
'comment': 'Boto VPC peering state'
}
if conn_name:
vpc_ids = __salt__['boto_vpc.describe_vpc_peering_connection'](
conn_name,
region=region,
key=key,
keyid=keyid,
profile=profile
).get('VPC-Peerings', [])
else:
vpc_ids = []
if vpc_ids:
ret['comment'] = ('VPC peering connection already exists, '
'nothing to be done.')
return ret
if __opts__['test']:
if not vpc_ids:
ret['comment'] = 'VPC peering connection will be created'
return ret
log.debug('Called module to create VPC peering connection')
result = __salt__['boto_vpc.request_vpc_peering_connection'](
requester_vpc_id,
requester_vpc_name,
peer_vpc_id,
peer_vpc_name,
name=conn_name,
peer_owner_id=peer_owner_id,
peer_region=peer_region,
region=region,
key=key,
keyid=keyid,
profile=profile
)
if 'error' in result:
ret['comment'] = "Failed to request VPC peering: {0}".format(result['error'])
ret['result'] = False
return ret
ret['changes'].update({
'old': '',
'new': result['msg']
})
return ret | [
"def",
"request_vpc_peering_connection",
"(",
"name",
",",
"requester_vpc_id",
"=",
"None",
",",
"requester_vpc_name",
"=",
"None",
",",
"peer_vpc_id",
"=",
"None",
",",
"peer_vpc_name",
"=",
"None",
",",
"conn_name",
"=",
"None",
",",
"peer_owner_id",
"=",
"Non... | name
Name of the state
requester_vpc_id
ID of the requesting VPC. Exclusive with requester_vpc_name. String type.
requester_vpc_name
Name tag of the requesting VPC. Exclusive with requester_vpc_id. String type.
peer_vpc_id
ID of the VPC tp crete VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. String type.
peer_vpc_name
Name tag of the VPC tp crete VPC peering connection with. This can only be a VPC the same account and region. Exclusive with peer_vpc_id. String type.
conn_name
The (optional) name to use for this VPC peering connection. String type.
peer_owner_id
ID of the owner of the peer VPC. String type. If this isn't supplied AWS uses your account ID. Required if peering to a different account.
peer_region
Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
request a vpc peering connection:
boto_vpc.request_vpc_peering_connection:
- requester_vpc_id: vpc-4b3522e
- peer_vpc_id: vpc-ae83f9ca
- conn_name: salt_peering_connection | [
"name",
"Name",
"of",
"the",
"state"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L1538-L1646 | train |
saltstack/salt | salt/states/boto_vpc.py | vpc_peering_connection_present | def vpc_peering_connection_present(name, requester_vpc_id=None, requester_vpc_name=None,
peer_vpc_id=None, peer_vpc_name=None, conn_name=None,
peer_owner_id=None, peer_region=None, region=None,
key=None, keyid=None, profile=None):
'''
name
Name of the state
requester_vpc_id
ID of the requesting VPC. Exclusive with requester_vpc_name.
requester_vpc_name
Name tag of the requesting VPC. Exclusive with requester_vpc_id.
peer_vpc_id
ID of the VPC tp crete VPC peering connection with. This can be a VPC in
another account. Exclusive with peer_vpc_name.
peer_vpc_name
Name tag of the VPC tp crete VPC peering connection with. This can only
be a VPC in the same account, else resolving it into a vpc ID will fail.
Exclusive with peer_vpc_id.
conn_name
The name to use for this VPC peering connection.
peer_owner_id
ID of the owner of the peer VPC. Defaults to your account ID, so a value
is required if peering with a VPC in a different account.
peer_region
Region of peer VPC. For inter-region vpc peering connections. Not required
for intra-region peering connections.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
ensure peering twixt local vpc and the other guys:
boto_vpc.vpc_peering_connection_present:
- requester_vpc_name: my_local_vpc
- peer_vpc_name: some_other_guys_vpc
- conn_name: peering_from_here_to_there
- peer_owner_id: 012345654321
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
if __salt__['boto_vpc.is_peering_connection_pending'](conn_name=conn_name, region=region,
key=key, keyid=keyid, profile=profile):
if __salt__['boto_vpc.peering_connection_pending_from_vpc'](conn_name=conn_name,
vpc_id=requester_vpc_id,
vpc_name=requester_vpc_name,
region=region, key=key,
keyid=keyid, profile=profile):
ret['comment'] = ('VPC peering {0} already requested - pending '
'acceptance by {1}'.format(conn_name, peer_owner_id
or peer_vpc_name or peer_vpc_id))
log.info(ret['comment'])
return ret
return accept_vpc_peering_connection(name=name, conn_name=conn_name,
region=region, key=key, keyid=keyid,
profile=profile)
return request_vpc_peering_connection(name=name, requester_vpc_id=requester_vpc_id,
requester_vpc_name=requester_vpc_name,
peer_vpc_id=peer_vpc_id, peer_vpc_name=peer_vpc_name,
conn_name=conn_name, peer_owner_id=peer_owner_id,
peer_region=peer_region, region=region, key=key,
keyid=keyid, profile=profile) | python | def vpc_peering_connection_present(name, requester_vpc_id=None, requester_vpc_name=None,
peer_vpc_id=None, peer_vpc_name=None, conn_name=None,
peer_owner_id=None, peer_region=None, region=None,
key=None, keyid=None, profile=None):
'''
name
Name of the state
requester_vpc_id
ID of the requesting VPC. Exclusive with requester_vpc_name.
requester_vpc_name
Name tag of the requesting VPC. Exclusive with requester_vpc_id.
peer_vpc_id
ID of the VPC tp crete VPC peering connection with. This can be a VPC in
another account. Exclusive with peer_vpc_name.
peer_vpc_name
Name tag of the VPC tp crete VPC peering connection with. This can only
be a VPC in the same account, else resolving it into a vpc ID will fail.
Exclusive with peer_vpc_id.
conn_name
The name to use for this VPC peering connection.
peer_owner_id
ID of the owner of the peer VPC. Defaults to your account ID, so a value
is required if peering with a VPC in a different account.
peer_region
Region of peer VPC. For inter-region vpc peering connections. Not required
for intra-region peering connections.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
ensure peering twixt local vpc and the other guys:
boto_vpc.vpc_peering_connection_present:
- requester_vpc_name: my_local_vpc
- peer_vpc_name: some_other_guys_vpc
- conn_name: peering_from_here_to_there
- peer_owner_id: 012345654321
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
if __salt__['boto_vpc.is_peering_connection_pending'](conn_name=conn_name, region=region,
key=key, keyid=keyid, profile=profile):
if __salt__['boto_vpc.peering_connection_pending_from_vpc'](conn_name=conn_name,
vpc_id=requester_vpc_id,
vpc_name=requester_vpc_name,
region=region, key=key,
keyid=keyid, profile=profile):
ret['comment'] = ('VPC peering {0} already requested - pending '
'acceptance by {1}'.format(conn_name, peer_owner_id
or peer_vpc_name or peer_vpc_id))
log.info(ret['comment'])
return ret
return accept_vpc_peering_connection(name=name, conn_name=conn_name,
region=region, key=key, keyid=keyid,
profile=profile)
return request_vpc_peering_connection(name=name, requester_vpc_id=requester_vpc_id,
requester_vpc_name=requester_vpc_name,
peer_vpc_id=peer_vpc_id, peer_vpc_name=peer_vpc_name,
conn_name=conn_name, peer_owner_id=peer_owner_id,
peer_region=peer_region, region=region, key=key,
keyid=keyid, profile=profile) | [
"def",
"vpc_peering_connection_present",
"(",
"name",
",",
"requester_vpc_id",
"=",
"None",
",",
"requester_vpc_name",
"=",
"None",
",",
"peer_vpc_id",
"=",
"None",
",",
"peer_vpc_name",
"=",
"None",
",",
"conn_name",
"=",
"None",
",",
"peer_owner_id",
"=",
"Non... | name
Name of the state
requester_vpc_id
ID of the requesting VPC. Exclusive with requester_vpc_name.
requester_vpc_name
Name tag of the requesting VPC. Exclusive with requester_vpc_id.
peer_vpc_id
ID of the VPC tp crete VPC peering connection with. This can be a VPC in
another account. Exclusive with peer_vpc_name.
peer_vpc_name
Name tag of the VPC tp crete VPC peering connection with. This can only
be a VPC in the same account, else resolving it into a vpc ID will fail.
Exclusive with peer_vpc_id.
conn_name
The name to use for this VPC peering connection.
peer_owner_id
ID of the owner of the peer VPC. Defaults to your account ID, so a value
is required if peering with a VPC in a different account.
peer_region
Region of peer VPC. For inter-region vpc peering connections. Not required
for intra-region peering connections.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
ensure peering twixt local vpc and the other guys:
boto_vpc.vpc_peering_connection_present:
- requester_vpc_name: my_local_vpc
- peer_vpc_name: some_other_guys_vpc
- conn_name: peering_from_here_to_there
- peer_owner_id: 012345654321 | [
"name",
"Name",
"of",
"the",
"state"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L1649-L1736 | train |
saltstack/salt | salt/states/boto_vpc.py | delete_vpc_peering_connection | def delete_vpc_peering_connection(name, conn_id=None, conn_name=None,
region=None, key=None, keyid=None, profile=None):
'''
name
Name of the state
conn_id
ID of the peering connection to delete. Exclusive with conn_name.
conn_name
The name of the peering connection to delete. Exclusive with conn_id.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
delete a vpc peering connection:
boto_vpc.delete_vpc_peering_connection:
- region: us-west-2
- conn_id: pcx-4613b12e
Connection name can be specified (instead of ID).
Specifying both conn_name and conn_id will result in an
error.
.. code-block:: yaml
delete a vpc peering connection:
boto_vpc.delete_vpc_peering_connection:
- conn_name: salt_vpc_peering
'''
log.debug('Called state to delete VPC peering connection')
ret = {
'name': name,
'result': True,
'changes': {},
'comment': 'Boto VPC peering state'
}
if conn_name:
vpc_ids = __salt__['boto_vpc.describe_vpc_peering_connection'](
conn_name, region=region, key=key, keyid=keyid, profile=profile).get('VPC-Peerings', [])
else:
vpc_ids = [conn_id]
if not vpc_ids:
ret['comment'] = 'No VPC connection found, nothing to be done.'
return ret
if __opts__['test']:
if vpc_ids:
ret['comment'] = 'VPC peering connection would be deleted'
return ret
log.debug('Called module to delete VPC peering connection')
result = __salt__['boto_vpc.delete_vpc_peering_connection'](
conn_id=conn_id, conn_name=conn_name, region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in result:
ret['comment'] = "Failed to delete VPC peering: {0}".format(result['error'])
ret['result'] = False
return ret
ret['changes'].update({
'old': '',
'new': result['msg']
})
return ret | python | def delete_vpc_peering_connection(name, conn_id=None, conn_name=None,
region=None, key=None, keyid=None, profile=None):
'''
name
Name of the state
conn_id
ID of the peering connection to delete. Exclusive with conn_name.
conn_name
The name of the peering connection to delete. Exclusive with conn_id.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
delete a vpc peering connection:
boto_vpc.delete_vpc_peering_connection:
- region: us-west-2
- conn_id: pcx-4613b12e
Connection name can be specified (instead of ID).
Specifying both conn_name and conn_id will result in an
error.
.. code-block:: yaml
delete a vpc peering connection:
boto_vpc.delete_vpc_peering_connection:
- conn_name: salt_vpc_peering
'''
log.debug('Called state to delete VPC peering connection')
ret = {
'name': name,
'result': True,
'changes': {},
'comment': 'Boto VPC peering state'
}
if conn_name:
vpc_ids = __salt__['boto_vpc.describe_vpc_peering_connection'](
conn_name, region=region, key=key, keyid=keyid, profile=profile).get('VPC-Peerings', [])
else:
vpc_ids = [conn_id]
if not vpc_ids:
ret['comment'] = 'No VPC connection found, nothing to be done.'
return ret
if __opts__['test']:
if vpc_ids:
ret['comment'] = 'VPC peering connection would be deleted'
return ret
log.debug('Called module to delete VPC peering connection')
result = __salt__['boto_vpc.delete_vpc_peering_connection'](
conn_id=conn_id, conn_name=conn_name, region=region, key=key,
keyid=keyid, profile=profile)
if 'error' in result:
ret['comment'] = "Failed to delete VPC peering: {0}".format(result['error'])
ret['result'] = False
return ret
ret['changes'].update({
'old': '',
'new': result['msg']
})
return ret | [
"def",
"delete_vpc_peering_connection",
"(",
"name",
",",
"conn_id",
"=",
"None",
",",
"conn_name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"log",
".",
"debug",... | name
Name of the state
conn_id
ID of the peering connection to delete. Exclusive with conn_name.
conn_name
The name of the peering connection to delete. Exclusive with conn_id.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
delete a vpc peering connection:
boto_vpc.delete_vpc_peering_connection:
- region: us-west-2
- conn_id: pcx-4613b12e
Connection name can be specified (instead of ID).
Specifying both conn_name and conn_id will result in an
error.
.. code-block:: yaml
delete a vpc peering connection:
boto_vpc.delete_vpc_peering_connection:
- conn_name: salt_vpc_peering | [
"name",
"Name",
"of",
"the",
"state"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L1745-L1829 | train |
saltstack/salt | salt/modules/ceph.py | zap | def zap(target=None, **kwargs):
'''
Destroy the partition table and content of a given disk.
.. code-block:: bash
salt '*' ceph.osd_prepare 'dev'='/dev/vdc' \\
'cluster_name'='ceph' \\
'cluster_uuid'='cluster_uuid'
dev
The block device to format.
cluster_name
The cluster name. Defaults to ``ceph``.
cluster_uuid
The cluster UUID. Defaults to value found in ceph config file.
'''
if target is not None:
log.warning("Depricated use of function, use kwargs")
target = kwargs.get("dev", target)
kwargs["dev"] = target
return ceph_cfg.zap(**kwargs) | python | def zap(target=None, **kwargs):
'''
Destroy the partition table and content of a given disk.
.. code-block:: bash
salt '*' ceph.osd_prepare 'dev'='/dev/vdc' \\
'cluster_name'='ceph' \\
'cluster_uuid'='cluster_uuid'
dev
The block device to format.
cluster_name
The cluster name. Defaults to ``ceph``.
cluster_uuid
The cluster UUID. Defaults to value found in ceph config file.
'''
if target is not None:
log.warning("Depricated use of function, use kwargs")
target = kwargs.get("dev", target)
kwargs["dev"] = target
return ceph_cfg.zap(**kwargs) | [
"def",
"zap",
"(",
"target",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"target",
"is",
"not",
"None",
":",
"log",
".",
"warning",
"(",
"\"Depricated use of function, use kwargs\"",
")",
"target",
"=",
"kwargs",
".",
"get",
"(",
"\"dev\"",
","... | Destroy the partition table and content of a given disk.
.. code-block:: bash
salt '*' ceph.osd_prepare 'dev'='/dev/vdc' \\
'cluster_name'='ceph' \\
'cluster_uuid'='cluster_uuid'
dev
The block device to format.
cluster_name
The cluster name. Defaults to ``ceph``.
cluster_uuid
The cluster UUID. Defaults to value found in ceph config file. | [
"Destroy",
"the",
"partition",
"table",
"and",
"content",
"of",
"a",
"given",
"disk",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ceph.py#L98-L121 | train |
saltstack/salt | salt/runners/f5.py | create_vs | def create_vs(lb, name, ip, port, protocol, profile, pool_name):
'''
Create a virtual server
CLI Examples:
.. code-block:: bash
salt-run f5.create_vs lbalancer vs_name 10.0.0.1 80 tcp http poolname
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__['load_balancers'][lb].values())
else:
raise Exception('Unable to find `{0}` load balancer'.format(lb))
F5 = F5Mgmt(lb, username, password)
F5.create_vs(name, ip, port, protocol, profile, pool_name)
return True | python | def create_vs(lb, name, ip, port, protocol, profile, pool_name):
'''
Create a virtual server
CLI Examples:
.. code-block:: bash
salt-run f5.create_vs lbalancer vs_name 10.0.0.1 80 tcp http poolname
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__['load_balancers'][lb].values())
else:
raise Exception('Unable to find `{0}` load balancer'.format(lb))
F5 = F5Mgmt(lb, username, password)
F5.create_vs(name, ip, port, protocol, profile, pool_name)
return True | [
"def",
"create_vs",
"(",
"lb",
",",
"name",
",",
"ip",
",",
"port",
",",
"protocol",
",",
"profile",
",",
"pool_name",
")",
":",
"if",
"__opts__",
"[",
"'load_balancers'",
"]",
".",
"get",
"(",
"lb",
",",
"None",
")",
":",
"(",
"username",
",",
"pa... | Create a virtual server
CLI Examples:
.. code-block:: bash
salt-run f5.create_vs lbalancer vs_name 10.0.0.1 80 tcp http poolname | [
"Create",
"a",
"virtual",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L235-L252 | train |
saltstack/salt | salt/runners/f5.py | create_pool | def create_pool(lb, name, method='ROUND_ROBIN'):
'''
Create a pool on the F5 load balancer
CLI Examples:
.. code-block:: bash
salt-run f5.create_pool load_balancer pool_name loadbalance_method
salt-run f5.create_pool load_balancer my_pool ROUND_ROBIN
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__['load_balancers'][lb].values())
else:
raise Exception('Unable to find `{0}` load balancer'.format(lb))
F5 = F5Mgmt(lb, username, password)
F5.create_pool(name, method)
return True | python | def create_pool(lb, name, method='ROUND_ROBIN'):
'''
Create a pool on the F5 load balancer
CLI Examples:
.. code-block:: bash
salt-run f5.create_pool load_balancer pool_name loadbalance_method
salt-run f5.create_pool load_balancer my_pool ROUND_ROBIN
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__['load_balancers'][lb].values())
else:
raise Exception('Unable to find `{0}` load balancer'.format(lb))
F5 = F5Mgmt(lb, username, password)
F5.create_pool(name, method)
return True | [
"def",
"create_pool",
"(",
"lb",
",",
"name",
",",
"method",
"=",
"'ROUND_ROBIN'",
")",
":",
"if",
"__opts__",
"[",
"'load_balancers'",
"]",
".",
"get",
"(",
"lb",
",",
"None",
")",
":",
"(",
"username",
",",
"password",
")",
"=",
"list",
"(",
"__opt... | Create a pool on the F5 load balancer
CLI Examples:
.. code-block:: bash
salt-run f5.create_pool load_balancer pool_name loadbalance_method
salt-run f5.create_pool load_balancer my_pool ROUND_ROBIN | [
"Create",
"a",
"pool",
"on",
"the",
"F5",
"load",
"balancer"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L255-L272 | train |
saltstack/salt | salt/runners/f5.py | add_pool_member | def add_pool_member(lb, name, port, pool_name):
'''
Add a node to a pool
CLI Examples:
.. code-block:: bash
salt-run f5.add_pool_member load_balancer 10.0.0.1 80 my_pool
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__['load_balancers'][lb].values())
else:
raise Exception('Unable to find `{0}` load balancer'.format(lb))
F5 = F5Mgmt(lb, username, password)
F5.add_pool_member(name, port, pool_name)
return True | python | def add_pool_member(lb, name, port, pool_name):
'''
Add a node to a pool
CLI Examples:
.. code-block:: bash
salt-run f5.add_pool_member load_balancer 10.0.0.1 80 my_pool
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__['load_balancers'][lb].values())
else:
raise Exception('Unable to find `{0}` load balancer'.format(lb))
F5 = F5Mgmt(lb, username, password)
F5.add_pool_member(name, port, pool_name)
return True | [
"def",
"add_pool_member",
"(",
"lb",
",",
"name",
",",
"port",
",",
"pool_name",
")",
":",
"if",
"__opts__",
"[",
"'load_balancers'",
"]",
".",
"get",
"(",
"lb",
",",
"None",
")",
":",
"(",
"username",
",",
"password",
")",
"=",
"list",
"(",
"__opts_... | Add a node to a pool
CLI Examples:
.. code-block:: bash
salt-run f5.add_pool_member load_balancer 10.0.0.1 80 my_pool | [
"Add",
"a",
"node",
"to",
"a",
"pool"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L275-L291 | train |
saltstack/salt | salt/runners/f5.py | check_pool | def check_pool(lb, name):
'''
Check to see if a pool exists
CLI Examples:
.. code-block:: bash
salt-run f5.check_pool load_balancer pool_name
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__['load_balancers'][lb].values())
else:
raise Exception('Unable to find `{0}` load balancer'.format(lb))
F5 = F5Mgmt(lb, username, password)
return F5.check_pool(name) | python | def check_pool(lb, name):
'''
Check to see if a pool exists
CLI Examples:
.. code-block:: bash
salt-run f5.check_pool load_balancer pool_name
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__['load_balancers'][lb].values())
else:
raise Exception('Unable to find `{0}` load balancer'.format(lb))
F5 = F5Mgmt(lb, username, password)
return F5.check_pool(name) | [
"def",
"check_pool",
"(",
"lb",
",",
"name",
")",
":",
"if",
"__opts__",
"[",
"'load_balancers'",
"]",
".",
"get",
"(",
"lb",
",",
"None",
")",
":",
"(",
"username",
",",
"password",
")",
"=",
"list",
"(",
"__opts__",
"[",
"'load_balancers'",
"]",
"[... | Check to see if a pool exists
CLI Examples:
.. code-block:: bash
salt-run f5.check_pool load_balancer pool_name | [
"Check",
"to",
"see",
"if",
"a",
"pool",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L294-L309 | train |
saltstack/salt | salt/runners/f5.py | check_member_pool | def check_member_pool(lb, member, pool_name):
'''
Check a pool member exists in a specific pool
CLI Examples:
.. code-block:: bash
salt-run f5.check_member_pool load_balancer 10.0.0.1 my_pool
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__['load_balancers'][lb].values())
else:
raise Exception('Unable to find `{0}` load balancer'.format(lb))
F5 = F5Mgmt(lb, username, password)
return F5.check_member_pool(member, pool_name) | python | def check_member_pool(lb, member, pool_name):
'''
Check a pool member exists in a specific pool
CLI Examples:
.. code-block:: bash
salt-run f5.check_member_pool load_balancer 10.0.0.1 my_pool
'''
if __opts__['load_balancers'].get(lb, None):
(username, password) = list(__opts__['load_balancers'][lb].values())
else:
raise Exception('Unable to find `{0}` load balancer'.format(lb))
F5 = F5Mgmt(lb, username, password)
return F5.check_member_pool(member, pool_name) | [
"def",
"check_member_pool",
"(",
"lb",
",",
"member",
",",
"pool_name",
")",
":",
"if",
"__opts__",
"[",
"'load_balancers'",
"]",
".",
"get",
"(",
"lb",
",",
"None",
")",
":",
"(",
"username",
",",
"password",
")",
"=",
"list",
"(",
"__opts__",
"[",
... | Check a pool member exists in a specific pool
CLI Examples:
.. code-block:: bash
salt-run f5.check_member_pool load_balancer 10.0.0.1 my_pool | [
"Check",
"a",
"pool",
"member",
"exists",
"in",
"a",
"specific",
"pool"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L330-L345 | train |
saltstack/salt | salt/runners/f5.py | F5Mgmt._connect | def _connect(self):
'''
Connect to F5
'''
try:
self.bigIP = f5.BIGIP(hostname=self.lb,
username=self.username,
password=self.password,
fromurl=True,
wsdls=['LocalLB.VirtualServer',
'LocalLB.Pool'])
except Exception:
raise Exception(
'Unable to connect to {0}'.format(self.lb)
)
return True | python | def _connect(self):
'''
Connect to F5
'''
try:
self.bigIP = f5.BIGIP(hostname=self.lb,
username=self.username,
password=self.password,
fromurl=True,
wsdls=['LocalLB.VirtualServer',
'LocalLB.Pool'])
except Exception:
raise Exception(
'Unable to connect to {0}'.format(self.lb)
)
return True | [
"def",
"_connect",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"bigIP",
"=",
"f5",
".",
"BIGIP",
"(",
"hostname",
"=",
"self",
".",
"lb",
",",
"username",
"=",
"self",
".",
"username",
",",
"password",
"=",
"self",
".",
"password",
",",
"fromur... | Connect to F5 | [
"Connect",
"to",
"F5"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L45-L61 | train |
saltstack/salt | salt/runners/f5.py | F5Mgmt.create_vs | def create_vs(self, name, ip, port, protocol, profile, pool_name):
'''
Create a virtual server
'''
vs = self.bigIP.LocalLB.VirtualServer
vs_def = vs.typefactory.create('Common.VirtualServerDefinition')
vs_def.name = name
vs_def.address = ip
vs_def.port = port
common_protocols = vs.typefactory.create('Common.ProtocolType')
p = [i[0] for i in common_protocols if i[0].split('_')[1] == protocol.upper()]
if p:
vs_def.protocol = p
else:
raise CommandExecutionError('Unknown protocol')
vs_def_seq = vs.typefactory.create('Common.VirtualServerSequence')
vs_def_seq.item = [vs_def]
vs_type = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerType'
)
vs_resource = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerResource'
)
vs_resource.type = vs_type.RESOURCE_TYPE_POOL
vs_resource.default_pool_name = pool_name
resource_seq = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerResourceSequence'
)
resource_seq.item = [vs_resource]
vs_context = vs.typefactory.create('LocalLB.ProfileContextType')
vs_profile = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerProfile'
)
vs_profile.profile_context = vs_context.PROFILE_CONTEXT_TYPE_ALL
vs_profile.profile_name = protocol
vs_profile_http = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerProfile'
)
vs_profile_http.profile_name = profile
vs_profile_conn = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerProfile'
)
vs_profile_conn.profile_name = 'oneconnect'
vs_profile_seq = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerProfileSequence'
)
vs_profile_seq.item = [vs_profile, vs_profile_http, vs_profile_conn]
try:
vs.create(definitions=vs_def_seq,
wildmasks=['255.255.255.255'],
resources=resource_seq,
profiles=[vs_profile_seq])
except Exception as e:
raise Exception(
'Unable to create `{0}` virtual server\n\n{1}'.format(name, e)
)
return True | python | def create_vs(self, name, ip, port, protocol, profile, pool_name):
'''
Create a virtual server
'''
vs = self.bigIP.LocalLB.VirtualServer
vs_def = vs.typefactory.create('Common.VirtualServerDefinition')
vs_def.name = name
vs_def.address = ip
vs_def.port = port
common_protocols = vs.typefactory.create('Common.ProtocolType')
p = [i[0] for i in common_protocols if i[0].split('_')[1] == protocol.upper()]
if p:
vs_def.protocol = p
else:
raise CommandExecutionError('Unknown protocol')
vs_def_seq = vs.typefactory.create('Common.VirtualServerSequence')
vs_def_seq.item = [vs_def]
vs_type = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerType'
)
vs_resource = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerResource'
)
vs_resource.type = vs_type.RESOURCE_TYPE_POOL
vs_resource.default_pool_name = pool_name
resource_seq = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerResourceSequence'
)
resource_seq.item = [vs_resource]
vs_context = vs.typefactory.create('LocalLB.ProfileContextType')
vs_profile = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerProfile'
)
vs_profile.profile_context = vs_context.PROFILE_CONTEXT_TYPE_ALL
vs_profile.profile_name = protocol
vs_profile_http = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerProfile'
)
vs_profile_http.profile_name = profile
vs_profile_conn = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerProfile'
)
vs_profile_conn.profile_name = 'oneconnect'
vs_profile_seq = vs.typefactory.create(
'LocalLB.VirtualServer.VirtualServerProfileSequence'
)
vs_profile_seq.item = [vs_profile, vs_profile_http, vs_profile_conn]
try:
vs.create(definitions=vs_def_seq,
wildmasks=['255.255.255.255'],
resources=resource_seq,
profiles=[vs_profile_seq])
except Exception as e:
raise Exception(
'Unable to create `{0}` virtual server\n\n{1}'.format(name, e)
)
return True | [
"def",
"create_vs",
"(",
"self",
",",
"name",
",",
"ip",
",",
"port",
",",
"protocol",
",",
"profile",
",",
"pool_name",
")",
":",
"vs",
"=",
"self",
".",
"bigIP",
".",
"LocalLB",
".",
"VirtualServer",
"vs_def",
"=",
"vs",
".",
"typefactory",
".",
"c... | Create a virtual server | [
"Create",
"a",
"virtual",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L63-L134 | train |
saltstack/salt | salt/runners/f5.py | F5Mgmt.create_pool | def create_pool(self, name, method='ROUND_ROBIN'):
'''
Create a pool on the F5 load balancer
'''
lbmethods = self.bigIP.LocalLB.Pool.typefactory.create(
'LocalLB.LBMethod'
)
supported_method = [i[0] for i in lbmethods if (
i[0].split('_', 2)[-1] == method.upper()
)]
if supported_method and not self.check_pool(name):
try:
self.bigIP.LocalLB.Pool.create(pool_names=[name],
lb_methods=[supported_method],
members=[[]])
except Exception as e:
raise Exception(
'Unable to create `{0}` pool\n\n{1}'.format(name, e)
)
else:
raise Exception('Unsupported method')
return True | python | def create_pool(self, name, method='ROUND_ROBIN'):
'''
Create a pool on the F5 load balancer
'''
lbmethods = self.bigIP.LocalLB.Pool.typefactory.create(
'LocalLB.LBMethod'
)
supported_method = [i[0] for i in lbmethods if (
i[0].split('_', 2)[-1] == method.upper()
)]
if supported_method and not self.check_pool(name):
try:
self.bigIP.LocalLB.Pool.create(pool_names=[name],
lb_methods=[supported_method],
members=[[]])
except Exception as e:
raise Exception(
'Unable to create `{0}` pool\n\n{1}'.format(name, e)
)
else:
raise Exception('Unsupported method')
return True | [
"def",
"create_pool",
"(",
"self",
",",
"name",
",",
"method",
"=",
"'ROUND_ROBIN'",
")",
":",
"lbmethods",
"=",
"self",
".",
"bigIP",
".",
"LocalLB",
".",
"Pool",
".",
"typefactory",
".",
"create",
"(",
"'LocalLB.LBMethod'",
")",
"supported_method",
"=",
... | Create a pool on the F5 load balancer | [
"Create",
"a",
"pool",
"on",
"the",
"F5",
"load",
"balancer"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L136-L159 | train |
saltstack/salt | salt/runners/f5.py | F5Mgmt.add_pool_member | def add_pool_member(self, name, port, pool_name):
'''
Add a node to a pool
'''
if not self.check_pool(pool_name):
raise CommandExecutionError(
'{0} pool does not exists'.format(pool_name)
)
members_seq = self.bigIP.LocalLB.Pool.typefactory.create(
'Common.IPPortDefinitionSequence'
)
members_seq.items = []
member = self.bigIP.LocalLB.Pool.typefactory.create(
'Common.IPPortDefinition'
)
member.address = name
member.port = port
members_seq.items.append(member)
try:
self.bigIP.LocalLB.Pool.add_member(pool_names=[pool_name],
members=[members_seq])
except Exception as e:
raise Exception(
'Unable to add `{0}` to `{1}`\n\n{2}'.format(name,
pool_name,
e)
)
return True | python | def add_pool_member(self, name, port, pool_name):
'''
Add a node to a pool
'''
if not self.check_pool(pool_name):
raise CommandExecutionError(
'{0} pool does not exists'.format(pool_name)
)
members_seq = self.bigIP.LocalLB.Pool.typefactory.create(
'Common.IPPortDefinitionSequence'
)
members_seq.items = []
member = self.bigIP.LocalLB.Pool.typefactory.create(
'Common.IPPortDefinition'
)
member.address = name
member.port = port
members_seq.items.append(member)
try:
self.bigIP.LocalLB.Pool.add_member(pool_names=[pool_name],
members=[members_seq])
except Exception as e:
raise Exception(
'Unable to add `{0}` to `{1}`\n\n{2}'.format(name,
pool_name,
e)
)
return True | [
"def",
"add_pool_member",
"(",
"self",
",",
"name",
",",
"port",
",",
"pool_name",
")",
":",
"if",
"not",
"self",
".",
"check_pool",
"(",
"pool_name",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'{0} pool does not exists'",
".",
"format",
"(",
"pool_name... | Add a node to a pool | [
"Add",
"a",
"node",
"to",
"a",
"pool"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L161-L193 | train |
saltstack/salt | salt/runners/f5.py | F5Mgmt.check_pool | def check_pool(self, name):
'''
Check to see if a pool exists
'''
pools = self.bigIP.LocalLB.Pool
for pool in pools.get_list():
if pool.split('/')[-1] == name:
return True
return False | python | def check_pool(self, name):
'''
Check to see if a pool exists
'''
pools = self.bigIP.LocalLB.Pool
for pool in pools.get_list():
if pool.split('/')[-1] == name:
return True
return False | [
"def",
"check_pool",
"(",
"self",
",",
"name",
")",
":",
"pools",
"=",
"self",
".",
"bigIP",
".",
"LocalLB",
".",
"Pool",
"for",
"pool",
"in",
"pools",
".",
"get_list",
"(",
")",
":",
"if",
"pool",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
... | Check to see if a pool exists | [
"Check",
"to",
"see",
"if",
"a",
"pool",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L195-L203 | train |
saltstack/salt | salt/runners/f5.py | F5Mgmt.check_virtualserver | def check_virtualserver(self, name):
'''
Check to see if a virtual server exists
'''
vs = self.bigIP.LocalLB.VirtualServer
for v in vs.get_list():
if v.split('/')[-1] == name:
return True
return False | python | def check_virtualserver(self, name):
'''
Check to see if a virtual server exists
'''
vs = self.bigIP.LocalLB.VirtualServer
for v in vs.get_list():
if v.split('/')[-1] == name:
return True
return False | [
"def",
"check_virtualserver",
"(",
"self",
",",
"name",
")",
":",
"vs",
"=",
"self",
".",
"bigIP",
".",
"LocalLB",
".",
"VirtualServer",
"for",
"v",
"in",
"vs",
".",
"get_list",
"(",
")",
":",
"if",
"v",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"... | Check to see if a virtual server exists | [
"Check",
"to",
"see",
"if",
"a",
"virtual",
"server",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L205-L213 | train |
saltstack/salt | salt/runners/f5.py | F5Mgmt.check_member_pool | def check_member_pool(self, member, pool_name):
'''
Check a pool member exists in a specific pool
'''
members = self.bigIP.LocalLB.Pool.get_member(pool_names=[pool_name])[0]
for mem in members:
if member == mem.address:
return True
return False | python | def check_member_pool(self, member, pool_name):
'''
Check a pool member exists in a specific pool
'''
members = self.bigIP.LocalLB.Pool.get_member(pool_names=[pool_name])[0]
for mem in members:
if member == mem.address:
return True
return False | [
"def",
"check_member_pool",
"(",
"self",
",",
"member",
",",
"pool_name",
")",
":",
"members",
"=",
"self",
".",
"bigIP",
".",
"LocalLB",
".",
"Pool",
".",
"get_member",
"(",
"pool_names",
"=",
"[",
"pool_name",
"]",
")",
"[",
"0",
"]",
"for",
"mem",
... | Check a pool member exists in a specific pool | [
"Check",
"a",
"pool",
"member",
"exists",
"in",
"a",
"specific",
"pool"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L215-L223 | train |
saltstack/salt | salt/runners/f5.py | F5Mgmt.lbmethods | def lbmethods(self):
'''
List all the load balancer methods
'''
methods = self.bigIP.LocalLB.Pool.typefactory.create(
'LocalLB.LBMethod'
)
return [method[0].split('_', 2)[-1] for method in methods] | python | def lbmethods(self):
'''
List all the load balancer methods
'''
methods = self.bigIP.LocalLB.Pool.typefactory.create(
'LocalLB.LBMethod'
)
return [method[0].split('_', 2)[-1] for method in methods] | [
"def",
"lbmethods",
"(",
"self",
")",
":",
"methods",
"=",
"self",
".",
"bigIP",
".",
"LocalLB",
".",
"Pool",
".",
"typefactory",
".",
"create",
"(",
"'LocalLB.LBMethod'",
")",
"return",
"[",
"method",
"[",
"0",
"]",
".",
"split",
"(",
"'_'",
",",
"2... | List all the load balancer methods | [
"List",
"all",
"the",
"load",
"balancer",
"methods"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/f5.py#L225-L232 | train |
saltstack/salt | salt/cloud/clouds/softlayer.py | get_conn | def get_conn(service='SoftLayer_Virtual_Guest'):
'''
Return a conn object for the passed VM data
'''
client = SoftLayer.Client(
username=config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
),
api_key=config.get_cloud_config_value(
'apikey', get_configured_provider(), __opts__, search_global=False
),
)
return client[service] | python | def get_conn(service='SoftLayer_Virtual_Guest'):
'''
Return a conn object for the passed VM data
'''
client = SoftLayer.Client(
username=config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
),
api_key=config.get_cloud_config_value(
'apikey', get_configured_provider(), __opts__, search_global=False
),
)
return client[service] | [
"def",
"get_conn",
"(",
"service",
"=",
"'SoftLayer_Virtual_Guest'",
")",
":",
"client",
"=",
"SoftLayer",
".",
"Client",
"(",
"username",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'user'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
","... | Return a conn object for the passed VM data | [
"Return",
"a",
"conn",
"object",
"for",
"the",
"passed",
"VM",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer.py#L104-L116 | train |
saltstack/salt | salt/cloud/clouds/softlayer.py | avail_locations | def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn()
response = conn.getCreateObjectOptions()
#return response
for datacenter in response['datacenters']:
#return data center
ret[datacenter['template']['datacenter']['name']] = {
'name': datacenter['template']['datacenter']['name'],
}
return ret | python | def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn()
response = conn.getCreateObjectOptions()
#return response
for datacenter in response['datacenters']:
#return data center
ret[datacenter['template']['datacenter']['name']] = {
'name': datacenter['template']['datacenter']['name'],
}
return ret | [
"def",
"avail_locations",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_locations function must be called with '",
"'-f or --function, or with the --list-locations option'",
")",
"ret",
"=",
"{",
... | List all available locations | [
"List",
"all",
"available",
"locations"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer.py#L119-L138 | train |
saltstack/salt | salt/cloud/clouds/softlayer.py | avail_sizes | def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. This data is provided in three dicts.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
ret = {
'block devices': {},
'memory': {},
'processors': {},
}
conn = get_conn()
response = conn.getCreateObjectOptions()
for device in response['blockDevices']:
#return device['template']['blockDevices']
ret['block devices'][device['itemPrice']['item']['description']] = {
'name': device['itemPrice']['item']['description'],
'capacity':
device['template']['blockDevices'][0]['diskImage']['capacity'],
}
for memory in response['memory']:
ret['memory'][memory['itemPrice']['item']['description']] = {
'name': memory['itemPrice']['item']['description'],
'maxMemory': memory['template']['maxMemory'],
}
for processors in response['processors']:
ret['processors'][processors['itemPrice']['item']['description']] = {
'name': processors['itemPrice']['item']['description'],
'start cpus': processors['template']['startCpus'],
}
return ret | python | def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. This data is provided in three dicts.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
ret = {
'block devices': {},
'memory': {},
'processors': {},
}
conn = get_conn()
response = conn.getCreateObjectOptions()
for device in response['blockDevices']:
#return device['template']['blockDevices']
ret['block devices'][device['itemPrice']['item']['description']] = {
'name': device['itemPrice']['item']['description'],
'capacity':
device['template']['blockDevices'][0]['diskImage']['capacity'],
}
for memory in response['memory']:
ret['memory'][memory['itemPrice']['item']['description']] = {
'name': memory['itemPrice']['item']['description'],
'maxMemory': memory['template']['maxMemory'],
}
for processors in response['processors']:
ret['processors'][processors['itemPrice']['item']['description']] = {
'name': processors['itemPrice']['item']['description'],
'start cpus': processors['template']['startCpus'],
}
return ret | [
"def",
"avail_sizes",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_sizes function must be called with '",
"'-f or --function, or with the --list-sizes option'",
")",
"ret",
"=",
"{",
"'block devi... | Return a dict of all available VM sizes on the cloud provider with
relevant data. This data is provided in three dicts. | [
"Return",
"a",
"dict",
"of",
"all",
"available",
"VM",
"sizes",
"on",
"the",
"cloud",
"provider",
"with",
"relevant",
"data",
".",
"This",
"data",
"is",
"provided",
"in",
"three",
"dicts",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer.py#L141-L176 | train |
saltstack/salt | salt/cloud/clouds/softlayer.py | avail_images | def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn()
response = conn.getCreateObjectOptions()
for image in response['operatingSystems']:
ret[image['itemPrice']['item']['description']] = {
'name': image['itemPrice']['item']['description'],
'template': image['template']['operatingSystemReferenceCode'],
}
return ret | python | def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn()
response = conn.getCreateObjectOptions()
for image in response['operatingSystems']:
ret[image['itemPrice']['item']['description']] = {
'name': image['itemPrice']['item']['description'],
'template': image['template']['operatingSystemReferenceCode'],
}
return ret | [
"def",
"avail_images",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-images option'",
")",
"ret",
"=",
"{",
"}",
"c... | Return a dict of all available VM images on the cloud provider. | [
"Return",
"a",
"dict",
"of",
"all",
"available",
"VM",
"images",
"on",
"the",
"cloud",
"provider",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer.py#L179-L197 | train |
saltstack/salt | salt/cloud/clouds/softlayer.py | list_custom_images | def list_custom_images(call=None):
'''
Return a dict of all custom VM images on the cloud provider.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vlans function must be called with -f or --function.'
)
ret = {}
conn = get_conn('SoftLayer_Account')
response = conn.getBlockDeviceTemplateGroups()
for image in response:
if 'globalIdentifier' not in image:
continue
ret[image['name']] = {
'id': image['id'],
'name': image['name'],
'globalIdentifier': image['globalIdentifier'],
}
if 'note' in image:
ret[image['name']]['note'] = image['note']
return ret | python | def list_custom_images(call=None):
'''
Return a dict of all custom VM images on the cloud provider.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vlans function must be called with -f or --function.'
)
ret = {}
conn = get_conn('SoftLayer_Account')
response = conn.getBlockDeviceTemplateGroups()
for image in response:
if 'globalIdentifier' not in image:
continue
ret[image['name']] = {
'id': image['id'],
'name': image['name'],
'globalIdentifier': image['globalIdentifier'],
}
if 'note' in image:
ret[image['name']]['note'] = image['note']
return ret | [
"def",
"list_custom_images",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_vlans function must be called with -f or --function.'",
")",
"ret",
"=",
"{",
"}",
"conn",
"=",
"get_conn",
"(",
... | Return a dict of all custom VM images on the cloud provider. | [
"Return",
"a",
"dict",
"of",
"all",
"custom",
"VM",
"images",
"on",
"the",
"cloud",
"provider",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer.py#L200-L222 | train |
saltstack/salt | salt/cloud/clouds/softlayer.py | create | def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'softlayer',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
name = vm_['name']
hostname = name
domain = config.get_cloud_config_value(
'domain', vm_, __opts__, default=None
)
if domain is None:
SaltCloudSystemExit(
'A domain name is required for the SoftLayer driver.'
)
if vm_.get('use_fqdn'):
name = '.'.join([name, domain])
vm_['name'] = name
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(name),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', name)
conn = get_conn()
kwargs = {
'hostname': hostname,
'domain': domain,
'startCpus': vm_['cpu_number'],
'maxMemory': vm_['ram'],
'hourlyBillingFlag': vm_['hourly_billing'],
}
local_disk_flag = config.get_cloud_config_value(
'local_disk', vm_, __opts__, default=False
)
kwargs['localDiskFlag'] = local_disk_flag
if 'image' in vm_:
kwargs['operatingSystemReferenceCode'] = vm_['image']
kwargs['blockDevices'] = []
disks = vm_['disk_size']
if isinstance(disks, int):
disks = [six.text_type(disks)]
elif isinstance(disks, six.string_types):
disks = [size.strip() for size in disks.split(',')]
count = 0
for disk in disks:
# device number '1' is reserved for the SWAP disk
if count == 1:
count += 1
block_device = {'device': six.text_type(count),
'diskImage': {'capacity': six.text_type(disk)}}
kwargs['blockDevices'].append(block_device)
count += 1
# Upper bound must be 5 as we're skipping '1' for the SWAP disk ID
if count > 5:
log.warning('More that 5 disks were specified for %s .'
'The first 5 disks will be applied to the VM, '
'but the remaining disks will be ignored.\n'
'Please adjust your cloud configuration to only '
'specify a maximum of 5 disks.', name)
break
elif 'global_identifier' in vm_:
kwargs['blockDeviceTemplateGroup'] = {
'globalIdentifier': vm_['global_identifier']
}
location = get_location(vm_)
if location:
kwargs['datacenter'] = {'name': location}
private_vlan = config.get_cloud_config_value(
'private_vlan', vm_, __opts__, default=False
)
if private_vlan:
kwargs['primaryBackendNetworkComponent'] = {
'networkVlan': {
'id': private_vlan,
}
}
private_network = config.get_cloud_config_value(
'private_network', vm_, __opts__, default=False
)
if bool(private_network) is True:
kwargs['privateNetworkOnlyFlag'] = 'True'
public_vlan = config.get_cloud_config_value(
'public_vlan', vm_, __opts__, default=False
)
if public_vlan:
kwargs['primaryNetworkComponent'] = {
'networkVlan': {
'id': public_vlan,
}
}
public_security_groups = config.get_cloud_config_value(
'public_security_groups', vm_, __opts__, default=False
)
if public_security_groups:
secgroups = [{'securityGroup': {'id': int(sg)}}
for sg in public_security_groups]
pnc = kwargs.get('primaryNetworkComponent', {})
pnc['securityGroupBindings'] = secgroups
kwargs.update({'primaryNetworkComponent': pnc})
private_security_groups = config.get_cloud_config_value(
'private_security_groups', vm_, __opts__, default=False
)
if private_security_groups:
secgroups = [{'securityGroup': {'id': int(sg)}}
for sg in private_security_groups]
pbnc = kwargs.get('primaryBackendNetworkComponent', {})
pbnc['securityGroupBindings'] = secgroups
kwargs.update({'primaryBackendNetworkComponent': pbnc})
max_net_speed = config.get_cloud_config_value(
'max_net_speed', vm_, __opts__, default=10
)
if max_net_speed:
kwargs['networkComponents'] = [{
'maxSpeed': int(max_net_speed)
}]
post_uri = config.get_cloud_config_value(
'post_uri', vm_, __opts__, default=None
)
if post_uri:
kwargs['postInstallScriptUri'] = post_uri
dedicated_host_id = config.get_cloud_config_value(
'dedicated_host_id', vm_, __opts__, default=None
)
if dedicated_host_id:
kwargs['dedicatedHost'] = {'id': dedicated_host_id}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(name),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
response = conn.createObject(kwargs)
except Exception as exc:
log.error(
'Error creating %s on SoftLayer\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s', name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
ip_type = 'primaryIpAddress'
private_ssh = config.get_cloud_config_value(
'private_ssh', vm_, __opts__, default=False
)
private_wds = config.get_cloud_config_value(
'private_windows', vm_, __opts__, default=False
)
if private_ssh or private_wds or public_vlan is None:
ip_type = 'primaryBackendIpAddress'
def wait_for_ip():
'''
Wait for the IP address to become available
'''
nodes = list_nodes_full()
if ip_type in nodes[hostname]:
return nodes[hostname][ip_type]
time.sleep(1)
return False
ip_address = salt.utils.cloud.wait_for_fun(
wait_for_ip,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if config.get_cloud_config_value('deploy', vm_, __opts__) is not True:
return show_instance(hostname, call='action')
SSH_PORT = 22
WINDOWS_DS_PORT = 445
managing_port = SSH_PORT
if config.get_cloud_config_value('windows', vm_, __opts__) or \
config.get_cloud_config_value('win_installer', vm_, __opts__):
managing_port = WINDOWS_DS_PORT
ssh_connect_timeout = config.get_cloud_config_value(
'ssh_connect_timeout', vm_, __opts__, 15 * 60
)
connect_timeout = config.get_cloud_config_value(
'connect_timeout', vm_, __opts__, ssh_connect_timeout
)
if not salt.utils.cloud.wait_for_port(ip_address,
port=managing_port,
timeout=connect_timeout):
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
pass_conn = get_conn(service='SoftLayer_Account')
mask = {
'virtualGuests': {
'powerState': '',
'operatingSystem': {
'passwords': ''
},
},
}
def get_credentials():
'''
Wait for the password to become available
'''
node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
for node in node_info:
if node['id'] == response['id'] and \
'passwords' in node['operatingSystem'] and \
node['operatingSystem']['passwords']:
return node['operatingSystem']['passwords'][0]['username'], node['operatingSystem']['passwords'][0]['password']
time.sleep(5)
return False
username, passwd = salt.utils.cloud.wait_for_fun( # pylint: disable=W0633
get_credentials,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
response['username'] = username
response['password'] = passwd
response['public_ip'] = ip_address
ssh_username = config.get_cloud_config_value(
'ssh_username', vm_, __opts__, default=username
)
vm_['ssh_host'] = ip_address
vm_['password'] = passwd
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(response)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(name),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret | python | def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'softlayer',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
name = vm_['name']
hostname = name
domain = config.get_cloud_config_value(
'domain', vm_, __opts__, default=None
)
if domain is None:
SaltCloudSystemExit(
'A domain name is required for the SoftLayer driver.'
)
if vm_.get('use_fqdn'):
name = '.'.join([name, domain])
vm_['name'] = name
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(name),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', name)
conn = get_conn()
kwargs = {
'hostname': hostname,
'domain': domain,
'startCpus': vm_['cpu_number'],
'maxMemory': vm_['ram'],
'hourlyBillingFlag': vm_['hourly_billing'],
}
local_disk_flag = config.get_cloud_config_value(
'local_disk', vm_, __opts__, default=False
)
kwargs['localDiskFlag'] = local_disk_flag
if 'image' in vm_:
kwargs['operatingSystemReferenceCode'] = vm_['image']
kwargs['blockDevices'] = []
disks = vm_['disk_size']
if isinstance(disks, int):
disks = [six.text_type(disks)]
elif isinstance(disks, six.string_types):
disks = [size.strip() for size in disks.split(',')]
count = 0
for disk in disks:
# device number '1' is reserved for the SWAP disk
if count == 1:
count += 1
block_device = {'device': six.text_type(count),
'diskImage': {'capacity': six.text_type(disk)}}
kwargs['blockDevices'].append(block_device)
count += 1
# Upper bound must be 5 as we're skipping '1' for the SWAP disk ID
if count > 5:
log.warning('More that 5 disks were specified for %s .'
'The first 5 disks will be applied to the VM, '
'but the remaining disks will be ignored.\n'
'Please adjust your cloud configuration to only '
'specify a maximum of 5 disks.', name)
break
elif 'global_identifier' in vm_:
kwargs['blockDeviceTemplateGroup'] = {
'globalIdentifier': vm_['global_identifier']
}
location = get_location(vm_)
if location:
kwargs['datacenter'] = {'name': location}
private_vlan = config.get_cloud_config_value(
'private_vlan', vm_, __opts__, default=False
)
if private_vlan:
kwargs['primaryBackendNetworkComponent'] = {
'networkVlan': {
'id': private_vlan,
}
}
private_network = config.get_cloud_config_value(
'private_network', vm_, __opts__, default=False
)
if bool(private_network) is True:
kwargs['privateNetworkOnlyFlag'] = 'True'
public_vlan = config.get_cloud_config_value(
'public_vlan', vm_, __opts__, default=False
)
if public_vlan:
kwargs['primaryNetworkComponent'] = {
'networkVlan': {
'id': public_vlan,
}
}
public_security_groups = config.get_cloud_config_value(
'public_security_groups', vm_, __opts__, default=False
)
if public_security_groups:
secgroups = [{'securityGroup': {'id': int(sg)}}
for sg in public_security_groups]
pnc = kwargs.get('primaryNetworkComponent', {})
pnc['securityGroupBindings'] = secgroups
kwargs.update({'primaryNetworkComponent': pnc})
private_security_groups = config.get_cloud_config_value(
'private_security_groups', vm_, __opts__, default=False
)
if private_security_groups:
secgroups = [{'securityGroup': {'id': int(sg)}}
for sg in private_security_groups]
pbnc = kwargs.get('primaryBackendNetworkComponent', {})
pbnc['securityGroupBindings'] = secgroups
kwargs.update({'primaryBackendNetworkComponent': pbnc})
max_net_speed = config.get_cloud_config_value(
'max_net_speed', vm_, __opts__, default=10
)
if max_net_speed:
kwargs['networkComponents'] = [{
'maxSpeed': int(max_net_speed)
}]
post_uri = config.get_cloud_config_value(
'post_uri', vm_, __opts__, default=None
)
if post_uri:
kwargs['postInstallScriptUri'] = post_uri
dedicated_host_id = config.get_cloud_config_value(
'dedicated_host_id', vm_, __opts__, default=None
)
if dedicated_host_id:
kwargs['dedicatedHost'] = {'id': dedicated_host_id}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(name),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
response = conn.createObject(kwargs)
except Exception as exc:
log.error(
'Error creating %s on SoftLayer\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s', name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
ip_type = 'primaryIpAddress'
private_ssh = config.get_cloud_config_value(
'private_ssh', vm_, __opts__, default=False
)
private_wds = config.get_cloud_config_value(
'private_windows', vm_, __opts__, default=False
)
if private_ssh or private_wds or public_vlan is None:
ip_type = 'primaryBackendIpAddress'
def wait_for_ip():
'''
Wait for the IP address to become available
'''
nodes = list_nodes_full()
if ip_type in nodes[hostname]:
return nodes[hostname][ip_type]
time.sleep(1)
return False
ip_address = salt.utils.cloud.wait_for_fun(
wait_for_ip,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if config.get_cloud_config_value('deploy', vm_, __opts__) is not True:
return show_instance(hostname, call='action')
SSH_PORT = 22
WINDOWS_DS_PORT = 445
managing_port = SSH_PORT
if config.get_cloud_config_value('windows', vm_, __opts__) or \
config.get_cloud_config_value('win_installer', vm_, __opts__):
managing_port = WINDOWS_DS_PORT
ssh_connect_timeout = config.get_cloud_config_value(
'ssh_connect_timeout', vm_, __opts__, 15 * 60
)
connect_timeout = config.get_cloud_config_value(
'connect_timeout', vm_, __opts__, ssh_connect_timeout
)
if not salt.utils.cloud.wait_for_port(ip_address,
port=managing_port,
timeout=connect_timeout):
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
pass_conn = get_conn(service='SoftLayer_Account')
mask = {
'virtualGuests': {
'powerState': '',
'operatingSystem': {
'passwords': ''
},
},
}
def get_credentials():
'''
Wait for the password to become available
'''
node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
for node in node_info:
if node['id'] == response['id'] and \
'passwords' in node['operatingSystem'] and \
node['operatingSystem']['passwords']:
return node['operatingSystem']['passwords'][0]['username'], node['operatingSystem']['passwords'][0]['password']
time.sleep(5)
return False
username, passwd = salt.utils.cloud.wait_for_fun( # pylint: disable=W0633
get_credentials,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
response['username'] = username
response['password'] = passwd
response['public_ip'] = ip_address
ssh_username = config.get_cloud_config_value(
'ssh_username', vm_, __opts__, default=username
)
vm_['ssh_host'] = ip_address
vm_['password'] = passwd
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(response)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(name),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret | [
"def",
"create",
"(",
"vm_",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"vm_",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
"'softl... | Create a single VM from a data dict | [
"Create",
"a",
"single",
"VM",
"from",
"a",
"data",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer.py#L244-L523 | train |
saltstack/salt | salt/cloud/clouds/softlayer.py | list_nodes_full | def list_nodes_full(mask='mask[id]', call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='SoftLayer_Account')
response = conn.getVirtualGuests()
for node_id in response:
hostname = node_id['hostname']
ret[hostname] = node_id
__utils__['cloud.cache_node_list'](ret, __active_provider_name__.split(':')[0], __opts__)
return ret | python | def list_nodes_full(mask='mask[id]', call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='SoftLayer_Account')
response = conn.getVirtualGuests()
for node_id in response:
hostname = node_id['hostname']
ret[hostname] = node_id
__utils__['cloud.cache_node_list'](ret, __active_provider_name__.split(':')[0], __opts__)
return ret | [
"def",
"list_nodes_full",
"(",
"mask",
"=",
"'mask[id]'",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_full function must be called with -f or --function.'",
")",
"ret",
"=",
"{",
"}",... | Return a list of the VMs that are on the provider | [
"Return",
"a",
"list",
"of",
"the",
"VMs",
"that",
"are",
"on",
"the",
"provider"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer.py#L526-L542 | train |
saltstack/salt | salt/cloud/clouds/softlayer.py | list_nodes | def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full()
if 'error' in nodes:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
nodes['error']['Errors']['Error']['Message']
)
)
for node in nodes:
ret[node] = {
'id': nodes[node]['hostname'],
'ram': nodes[node]['maxMemory'],
'cpus': nodes[node]['maxCpu'],
}
if 'primaryIpAddress' in nodes[node]:
ret[node]['public_ips'] = nodes[node]['primaryIpAddress']
if 'primaryBackendIpAddress' in nodes[node]:
ret[node]['private_ips'] = nodes[node]['primaryBackendIpAddress']
if 'status' in nodes[node]:
ret[node]['state'] = six.text_type(nodes[node]['status']['name'])
return ret | python | def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full()
if 'error' in nodes:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
nodes['error']['Errors']['Error']['Message']
)
)
for node in nodes:
ret[node] = {
'id': nodes[node]['hostname'],
'ram': nodes[node]['maxMemory'],
'cpus': nodes[node]['maxCpu'],
}
if 'primaryIpAddress' in nodes[node]:
ret[node]['public_ips'] = nodes[node]['primaryIpAddress']
if 'primaryBackendIpAddress' in nodes[node]:
ret[node]['private_ips'] = nodes[node]['primaryBackendIpAddress']
if 'status' in nodes[node]:
ret[node]['state'] = six.text_type(nodes[node]['status']['name'])
return ret | [
"def",
"list_nodes",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes function must be called with -f or --function.'",
")",
"ret",
"=",
"{",
"}",
"nodes",
"=",
"list_nodes_full",
"(",
"... | Return a list of the VMs that are on the provider | [
"Return",
"a",
"list",
"of",
"the",
"VMs",
"that",
"are",
"on",
"the",
"provider"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer.py#L545-L574 | train |
saltstack/salt | salt/cloud/clouds/softlayer.py | destroy | def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
node = show_instance(name, call='action')
conn = get_conn()
response = conn.deleteObject(id=node['id'])
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return response | python | def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
node = show_instance(name, call='action')
conn = get_conn()
response = conn.deleteObject(id=node['id'])
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return response | [
"def",
"destroy",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called with -d, --destroy, '",
"'-a or --action.'",
")",
"__utils__",
"[",
"'cloud.fire_event'",
... | Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine | [
"Destroy",
"a",
"node",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer.py#L600-L640 | train |
saltstack/salt | salt/modules/ipset.py | new_set | def new_set(set=None, set_type=None, family='ipv4', comment=False, **kwargs):
'''
.. versionadded:: 2014.7.0
Create new custom set
CLI Example:
.. code-block:: bash
salt '*' ipset.new_set custom_set list:set
salt '*' ipset.new_set custom_set list:set comment=True
IPv6:
salt '*' ipset.new_set custom_set list:set family=ipv6
'''
ipset_family = _IPSET_FAMILIES[family]
if not set:
return 'Error: Set needs to be specified'
if not set_type:
return 'Error: Set Type needs to be specified'
if set_type not in _IPSET_SET_TYPES:
return 'Error: Set Type is invalid'
# Check for required arguments
for item in _CREATE_OPTIONS_REQUIRED[set_type]:
if item not in kwargs:
return 'Error: {0} is a required argument'.format(item)
cmd = '{0} create {1} {2}'.format(_ipset_cmd(), set, set_type)
for item in _CREATE_OPTIONS[set_type]:
if item in kwargs:
if item in _CREATE_OPTIONS_WITHOUT_VALUE:
cmd = '{0} {1} '.format(cmd, item)
else:
cmd = '{0} {1} {2} '.format(cmd, item, kwargs[item])
# Family only valid for certain set types
if 'family' in _CREATE_OPTIONS[set_type]:
cmd = '{0} family {1}'.format(cmd, ipset_family)
if comment:
cmd = '{0} comment'.format(cmd)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
out = True
return out | python | def new_set(set=None, set_type=None, family='ipv4', comment=False, **kwargs):
'''
.. versionadded:: 2014.7.0
Create new custom set
CLI Example:
.. code-block:: bash
salt '*' ipset.new_set custom_set list:set
salt '*' ipset.new_set custom_set list:set comment=True
IPv6:
salt '*' ipset.new_set custom_set list:set family=ipv6
'''
ipset_family = _IPSET_FAMILIES[family]
if not set:
return 'Error: Set needs to be specified'
if not set_type:
return 'Error: Set Type needs to be specified'
if set_type not in _IPSET_SET_TYPES:
return 'Error: Set Type is invalid'
# Check for required arguments
for item in _CREATE_OPTIONS_REQUIRED[set_type]:
if item not in kwargs:
return 'Error: {0} is a required argument'.format(item)
cmd = '{0} create {1} {2}'.format(_ipset_cmd(), set, set_type)
for item in _CREATE_OPTIONS[set_type]:
if item in kwargs:
if item in _CREATE_OPTIONS_WITHOUT_VALUE:
cmd = '{0} {1} '.format(cmd, item)
else:
cmd = '{0} {1} {2} '.format(cmd, item, kwargs[item])
# Family only valid for certain set types
if 'family' in _CREATE_OPTIONS[set_type]:
cmd = '{0} family {1}'.format(cmd, ipset_family)
if comment:
cmd = '{0} comment'.format(cmd)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
out = True
return out | [
"def",
"new_set",
"(",
"set",
"=",
"None",
",",
"set_type",
"=",
"None",
",",
"family",
"=",
"'ipv4'",
",",
"comment",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"ipset_family",
"=",
"_IPSET_FAMILIES",
"[",
"family",
"]",
"if",
"not",
"set",
":... | .. versionadded:: 2014.7.0
Create new custom set
CLI Example:
.. code-block:: bash
salt '*' ipset.new_set custom_set list:set
salt '*' ipset.new_set custom_set list:set comment=True
IPv6:
salt '*' ipset.new_set custom_set list:set family=ipv6 | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipset.py#L146-L199 | train |
saltstack/salt | salt/modules/ipset.py | delete_set | def delete_set(set=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete ipset set.
CLI Example:
.. code-block:: bash
salt '*' ipset.delete_set custom_set
IPv6:
salt '*' ipset.delete_set custom_set family=ipv6
'''
if not set:
return 'Error: Set needs to be specified'
cmd = '{0} destroy {1}'.format(_ipset_cmd(), set)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
out = True
return out | python | def delete_set(set=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete ipset set.
CLI Example:
.. code-block:: bash
salt '*' ipset.delete_set custom_set
IPv6:
salt '*' ipset.delete_set custom_set family=ipv6
'''
if not set:
return 'Error: Set needs to be specified'
cmd = '{0} destroy {1}'.format(_ipset_cmd(), set)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
out = True
return out | [
"def",
"delete_set",
"(",
"set",
"=",
"None",
",",
"family",
"=",
"'ipv4'",
")",
":",
"if",
"not",
"set",
":",
"return",
"'Error: Set needs to be specified'",
"cmd",
"=",
"'{0} destroy {1}'",
".",
"format",
"(",
"_ipset_cmd",
"(",
")",
",",
"set",
")",
"ou... | .. versionadded:: 2014.7.0
Delete ipset set.
CLI Example:
.. code-block:: bash
salt '*' ipset.delete_set custom_set
IPv6:
salt '*' ipset.delete_set custom_set family=ipv6 | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipset.py#L202-L226 | train |
saltstack/salt | salt/modules/ipset.py | rename_set | def rename_set(set=None, new_set=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete ipset set.
CLI Example:
.. code-block:: bash
salt '*' ipset.rename_set custom_set new_set=new_set_name
IPv6:
salt '*' ipset.rename_set custom_set new_set=new_set_name family=ipv6
'''
if not set:
return 'Error: Set needs to be specified'
if not new_set:
return 'Error: New name for set needs to be specified'
settype = _find_set_type(set)
if not settype:
return 'Error: Set does not exist'
settype = _find_set_type(new_set)
if settype:
return 'Error: New Set already exists'
cmd = '{0} rename {1} {2}'.format(_ipset_cmd(), set, new_set)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
out = True
return out | python | def rename_set(set=None, new_set=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Delete ipset set.
CLI Example:
.. code-block:: bash
salt '*' ipset.rename_set custom_set new_set=new_set_name
IPv6:
salt '*' ipset.rename_set custom_set new_set=new_set_name family=ipv6
'''
if not set:
return 'Error: Set needs to be specified'
if not new_set:
return 'Error: New name for set needs to be specified'
settype = _find_set_type(set)
if not settype:
return 'Error: Set does not exist'
settype = _find_set_type(new_set)
if settype:
return 'Error: New Set already exists'
cmd = '{0} rename {1} {2}'.format(_ipset_cmd(), set, new_set)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
out = True
return out | [
"def",
"rename_set",
"(",
"set",
"=",
"None",
",",
"new_set",
"=",
"None",
",",
"family",
"=",
"'ipv4'",
")",
":",
"if",
"not",
"set",
":",
"return",
"'Error: Set needs to be specified'",
"if",
"not",
"new_set",
":",
"return",
"'Error: New name for set needs to ... | .. versionadded:: 2014.7.0
Delete ipset set.
CLI Example:
.. code-block:: bash
salt '*' ipset.rename_set custom_set new_set=new_set_name
IPv6:
salt '*' ipset.rename_set custom_set new_set=new_set_name family=ipv6 | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipset.py#L229-L264 | train |
saltstack/salt | salt/modules/ipset.py | list_sets | def list_sets(family='ipv4'):
'''
.. versionadded:: 2014.7.0
List all ipset sets.
CLI Example:
.. code-block:: bash
salt '*' ipset.list_sets
'''
cmd = '{0} list -t'.format(_ipset_cmd())
out = __salt__['cmd.run'](cmd, python_shell=False)
_tmp = out.split('\n')
count = 0
sets = []
sets.append({})
for item in _tmp:
if not item:
count = count + 1
sets.append({})
continue
key, value = item.split(':', 1)
sets[count][key] = value[1:]
return sets | python | def list_sets(family='ipv4'):
'''
.. versionadded:: 2014.7.0
List all ipset sets.
CLI Example:
.. code-block:: bash
salt '*' ipset.list_sets
'''
cmd = '{0} list -t'.format(_ipset_cmd())
out = __salt__['cmd.run'](cmd, python_shell=False)
_tmp = out.split('\n')
count = 0
sets = []
sets.append({})
for item in _tmp:
if not item:
count = count + 1
sets.append({})
continue
key, value = item.split(':', 1)
sets[count][key] = value[1:]
return sets | [
"def",
"list_sets",
"(",
"family",
"=",
"'ipv4'",
")",
":",
"cmd",
"=",
"'{0} list -t'",
".",
"format",
"(",
"_ipset_cmd",
"(",
")",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"_tmp",
"=",
... | .. versionadded:: 2014.7.0
List all ipset sets.
CLI Example:
.. code-block:: bash
salt '*' ipset.list_sets | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipset.py#L267-L295 | train |
saltstack/salt | salt/modules/ipset.py | check_set | def check_set(set=None, family='ipv4'):
'''
Check that given ipset set exists.
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' ipset.check_set setname
'''
if not set:
return 'Error: Set needs to be specified'
setinfo = _find_set_info(set)
if not setinfo:
return False
return True | python | def check_set(set=None, family='ipv4'):
'''
Check that given ipset set exists.
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' ipset.check_set setname
'''
if not set:
return 'Error: Set needs to be specified'
setinfo = _find_set_info(set)
if not setinfo:
return False
return True | [
"def",
"check_set",
"(",
"set",
"=",
"None",
",",
"family",
"=",
"'ipv4'",
")",
":",
"if",
"not",
"set",
":",
"return",
"'Error: Set needs to be specified'",
"setinfo",
"=",
"_find_set_info",
"(",
"set",
")",
"if",
"not",
"setinfo",
":",
"return",
"False",
... | Check that given ipset set exists.
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' ipset.check_set setname | [
"Check",
"that",
"given",
"ipset",
"set",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipset.py#L298-L317 | train |
saltstack/salt | salt/modules/ipset.py | add | def add(setname=None, entry=None, family='ipv4', **kwargs):
'''
Append an entry to the specified set.
CLI Example:
.. code-block:: bash
salt '*' ipset.add setname 192.168.1.26
salt '*' ipset.add setname 192.168.0.3,AA:BB:CC:DD:EE:FF
'''
if not setname:
return 'Error: Set needs to be specified'
if not entry:
return 'Error: Entry needs to be specified'
setinfo = _find_set_info(setname)
if not setinfo:
return 'Error: Set {0} does not exist'.format(setname)
settype = setinfo['Type']
cmd = '{0}'.format(entry)
if 'timeout' in kwargs:
if 'timeout' not in setinfo['Header']:
return 'Error: Set {0} not created with timeout support'.format(setname)
if 'packets' in kwargs or 'bytes' in kwargs:
if 'counters' not in setinfo['Header']:
return 'Error: Set {0} not created with counters support'.format(setname)
if 'comment' in kwargs:
if 'comment' not in setinfo['Header']:
return 'Error: Set {0} not created with comment support'.format(setname)
if 'comment' not in entry:
cmd = '{0} comment "{1}"'.format(cmd, kwargs['comment'])
if set(['skbmark', 'skbprio', 'skbqueue']) & set(kwargs):
if 'skbinfo' not in setinfo['Header']:
return 'Error: Set {0} not created with skbinfo support'.format(setname)
for item in _ADD_OPTIONS[settype]:
if item in kwargs:
cmd = '{0} {1} {2}'.format(cmd, item, kwargs[item])
current_members = _find_set_members(setname)
if cmd in current_members:
return 'Warn: Entry {0} already exists in set {1}'.format(cmd, setname)
# Using -exist to ensure entries are updated if the comment changes
cmd = '{0} add -exist {1} {2}'.format(_ipset_cmd(), setname, cmd)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
return 'Success'
return 'Error: {0}'.format(out) | python | def add(setname=None, entry=None, family='ipv4', **kwargs):
'''
Append an entry to the specified set.
CLI Example:
.. code-block:: bash
salt '*' ipset.add setname 192.168.1.26
salt '*' ipset.add setname 192.168.0.3,AA:BB:CC:DD:EE:FF
'''
if not setname:
return 'Error: Set needs to be specified'
if not entry:
return 'Error: Entry needs to be specified'
setinfo = _find_set_info(setname)
if not setinfo:
return 'Error: Set {0} does not exist'.format(setname)
settype = setinfo['Type']
cmd = '{0}'.format(entry)
if 'timeout' in kwargs:
if 'timeout' not in setinfo['Header']:
return 'Error: Set {0} not created with timeout support'.format(setname)
if 'packets' in kwargs or 'bytes' in kwargs:
if 'counters' not in setinfo['Header']:
return 'Error: Set {0} not created with counters support'.format(setname)
if 'comment' in kwargs:
if 'comment' not in setinfo['Header']:
return 'Error: Set {0} not created with comment support'.format(setname)
if 'comment' not in entry:
cmd = '{0} comment "{1}"'.format(cmd, kwargs['comment'])
if set(['skbmark', 'skbprio', 'skbqueue']) & set(kwargs):
if 'skbinfo' not in setinfo['Header']:
return 'Error: Set {0} not created with skbinfo support'.format(setname)
for item in _ADD_OPTIONS[settype]:
if item in kwargs:
cmd = '{0} {1} {2}'.format(cmd, item, kwargs[item])
current_members = _find_set_members(setname)
if cmd in current_members:
return 'Warn: Entry {0} already exists in set {1}'.format(cmd, setname)
# Using -exist to ensure entries are updated if the comment changes
cmd = '{0} add -exist {1} {2}'.format(_ipset_cmd(), setname, cmd)
out = __salt__['cmd.run'](cmd, python_shell=False)
if not out:
return 'Success'
return 'Error: {0}'.format(out) | [
"def",
"add",
"(",
"setname",
"=",
"None",
",",
"entry",
"=",
"None",
",",
"family",
"=",
"'ipv4'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"setname",
":",
"return",
"'Error: Set needs to be specified'",
"if",
"not",
"entry",
":",
"return",
"'Err... | Append an entry to the specified set.
CLI Example:
.. code-block:: bash
salt '*' ipset.add setname 192.168.1.26
salt '*' ipset.add setname 192.168.0.3,AA:BB:CC:DD:EE:FF | [
"Append",
"an",
"entry",
"to",
"the",
"specified",
"set",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipset.py#L320-L378 | train |
saltstack/salt | salt/modules/ipset.py | check | def check(set=None, entry=None, family='ipv4'):
'''
Check that an entry exists in the specified set.
set
The ipset name
entry
An entry in the ipset. This parameter can be a single IP address, a
range of IP addresses, or a subnet block. Example:
.. code-block:: cfg
192.168.0.1
192.168.0.2-192.168.0.19
192.168.0.0/25
family
IP protocol version: ipv4 or ipv6
CLI Example:
.. code-block:: bash
salt '*' ipset.check setname '192.168.0.1 comment "Hello"'
'''
if not set:
return 'Error: Set needs to be specified'
if not entry:
return 'Error: Entry needs to be specified'
settype = _find_set_type(set)
if not settype:
return 'Error: Set {0} does not exist'.format(set)
current_members = _parse_members(settype, _find_set_members(set))
if not current_members:
return False
if isinstance(entry, list):
entries = _parse_members(settype, entry)
else:
entries = [_parse_member(settype, entry)]
for current_member in current_members:
for entry in entries:
if _member_contains(current_member, entry):
return True
return False | python | def check(set=None, entry=None, family='ipv4'):
'''
Check that an entry exists in the specified set.
set
The ipset name
entry
An entry in the ipset. This parameter can be a single IP address, a
range of IP addresses, or a subnet block. Example:
.. code-block:: cfg
192.168.0.1
192.168.0.2-192.168.0.19
192.168.0.0/25
family
IP protocol version: ipv4 or ipv6
CLI Example:
.. code-block:: bash
salt '*' ipset.check setname '192.168.0.1 comment "Hello"'
'''
if not set:
return 'Error: Set needs to be specified'
if not entry:
return 'Error: Entry needs to be specified'
settype = _find_set_type(set)
if not settype:
return 'Error: Set {0} does not exist'.format(set)
current_members = _parse_members(settype, _find_set_members(set))
if not current_members:
return False
if isinstance(entry, list):
entries = _parse_members(settype, entry)
else:
entries = [_parse_member(settype, entry)]
for current_member in current_members:
for entry in entries:
if _member_contains(current_member, entry):
return True
return False | [
"def",
"check",
"(",
"set",
"=",
"None",
",",
"entry",
"=",
"None",
",",
"family",
"=",
"'ipv4'",
")",
":",
"if",
"not",
"set",
":",
"return",
"'Error: Set needs to be specified'",
"if",
"not",
"entry",
":",
"return",
"'Error: Entry needs to be specified'",
"s... | Check that an entry exists in the specified set.
set
The ipset name
entry
An entry in the ipset. This parameter can be a single IP address, a
range of IP addresses, or a subnet block. Example:
.. code-block:: cfg
192.168.0.1
192.168.0.2-192.168.0.19
192.168.0.0/25
family
IP protocol version: ipv4 or ipv6
CLI Example:
.. code-block:: bash
salt '*' ipset.check setname '192.168.0.1 comment "Hello"' | [
"Check",
"that",
"an",
"entry",
"exists",
"in",
"the",
"specified",
"set",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipset.py#L410-L461 | train |
saltstack/salt | salt/modules/ipset.py | flush | def flush(set=None, family='ipv4'):
'''
Flush entries in the specified set,
Flush all sets if set is not specified.
CLI Example:
.. code-block:: bash
salt '*' ipset.flush
salt '*' ipset.flush set
IPv6:
salt '*' ipset.flush
salt '*' ipset.flush set
'''
settype = _find_set_type(set)
if not settype:
return 'Error: Set {0} does not exist'.format(set)
ipset_family = _IPSET_FAMILIES[family]
if set:
cmd = '{0} flush {1}'.format(_ipset_cmd(), set)
else:
cmd = '{0} flush'.format(_ipset_cmd())
out = __salt__['cmd.run'](cmd, python_shell=False)
return not out | python | def flush(set=None, family='ipv4'):
'''
Flush entries in the specified set,
Flush all sets if set is not specified.
CLI Example:
.. code-block:: bash
salt '*' ipset.flush
salt '*' ipset.flush set
IPv6:
salt '*' ipset.flush
salt '*' ipset.flush set
'''
settype = _find_set_type(set)
if not settype:
return 'Error: Set {0} does not exist'.format(set)
ipset_family = _IPSET_FAMILIES[family]
if set:
cmd = '{0} flush {1}'.format(_ipset_cmd(), set)
else:
cmd = '{0} flush'.format(_ipset_cmd())
out = __salt__['cmd.run'](cmd, python_shell=False)
return not out | [
"def",
"flush",
"(",
"set",
"=",
"None",
",",
"family",
"=",
"'ipv4'",
")",
":",
"settype",
"=",
"_find_set_type",
"(",
"set",
")",
"if",
"not",
"settype",
":",
"return",
"'Error: Set {0} does not exist'",
".",
"format",
"(",
"set",
")",
"ipset_family",
"=... | Flush entries in the specified set,
Flush all sets if set is not specified.
CLI Example:
.. code-block:: bash
salt '*' ipset.flush
salt '*' ipset.flush set
IPv6:
salt '*' ipset.flush
salt '*' ipset.flush set | [
"Flush",
"entries",
"in",
"the",
"specified",
"set",
"Flush",
"all",
"sets",
"if",
"set",
"is",
"not",
"specified",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipset.py#L496-L526 | train |
saltstack/salt | salt/modules/ipset.py | _find_set_members | def _find_set_members(set):
'''
Return list of members for a set
'''
cmd = '{0} list {1}'.format(_ipset_cmd(), set)
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0:
# Set doesn't exist return false
return False
_tmp = out['stdout'].split('\n')
members = []
startMembers = False
for i in _tmp:
if startMembers:
members.append(i)
if 'Members:' in i:
startMembers = True
return members | python | def _find_set_members(set):
'''
Return list of members for a set
'''
cmd = '{0} list {1}'.format(_ipset_cmd(), set)
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0:
# Set doesn't exist return false
return False
_tmp = out['stdout'].split('\n')
members = []
startMembers = False
for i in _tmp:
if startMembers:
members.append(i)
if 'Members:' in i:
startMembers = True
return members | [
"def",
"_find_set_members",
"(",
"set",
")",
":",
"cmd",
"=",
"'{0} list {1}'",
".",
"format",
"(",
"_ipset_cmd",
"(",
")",
",",
"set",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"if",
"o... | Return list of members for a set | [
"Return",
"list",
"of",
"members",
"for",
"a",
"set"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipset.py#L529-L549 | train |
saltstack/salt | salt/modules/ipset.py | _find_set_info | def _find_set_info(set):
'''
Return information about the set
'''
cmd = '{0} list -t {1}'.format(_ipset_cmd(), set)
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0:
# Set doesn't exist return false
return False
setinfo = {}
_tmp = out['stdout'].split('\n')
for item in _tmp:
# Only split if item has a colon
if ':' in item:
key, value = item.split(':', 1)
setinfo[key] = value[1:]
return setinfo | python | def _find_set_info(set):
'''
Return information about the set
'''
cmd = '{0} list -t {1}'.format(_ipset_cmd(), set)
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0:
# Set doesn't exist return false
return False
setinfo = {}
_tmp = out['stdout'].split('\n')
for item in _tmp:
# Only split if item has a colon
if ':' in item:
key, value = item.split(':', 1)
setinfo[key] = value[1:]
return setinfo | [
"def",
"_find_set_info",
"(",
"set",
")",
":",
"cmd",
"=",
"'{0} list -t {1}'",
".",
"format",
"(",
"_ipset_cmd",
"(",
")",
",",
"set",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"if",
"o... | Return information about the set | [
"Return",
"information",
"about",
"the",
"set"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ipset.py#L552-L571 | train |
saltstack/salt | salt/runners/http.py | query | def query(url, output=True, **kwargs):
'''
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
CLI Example:
.. code-block:: bash
salt-run http.query http://somelink.com/
salt-run http.query http://somelink.com/ method=POST \
params='key1=val1&key2=val2'
salt-run http.query http://somelink.com/ method=POST \
data='<xml>somecontent</xml>'
'''
if output is not True:
log.warning('Output option has been deprecated. Please use --quiet.')
if 'node' not in kwargs:
kwargs['node'] = 'master'
opts = __opts__.copy()
if 'opts' in kwargs:
opts.update(kwargs['opts'])
del kwargs['opts']
ret = salt.utils.http.query(url=url, opts=opts, **kwargs)
return ret | python | def query(url, output=True, **kwargs):
'''
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
CLI Example:
.. code-block:: bash
salt-run http.query http://somelink.com/
salt-run http.query http://somelink.com/ method=POST \
params='key1=val1&key2=val2'
salt-run http.query http://somelink.com/ method=POST \
data='<xml>somecontent</xml>'
'''
if output is not True:
log.warning('Output option has been deprecated. Please use --quiet.')
if 'node' not in kwargs:
kwargs['node'] = 'master'
opts = __opts__.copy()
if 'opts' in kwargs:
opts.update(kwargs['opts'])
del kwargs['opts']
ret = salt.utils.http.query(url=url, opts=opts, **kwargs)
return ret | [
"def",
"query",
"(",
"url",
",",
"output",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"output",
"is",
"not",
"True",
":",
"log",
".",
"warning",
"(",
"'Output option has been deprecated. Please use --quiet.'",
")",
"if",
"'node'",
"not",
"in",
"... | Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
CLI Example:
.. code-block:: bash
salt-run http.query http://somelink.com/
salt-run http.query http://somelink.com/ method=POST \
params='key1=val1&key2=val2'
salt-run http.query http://somelink.com/ method=POST \
data='<xml>somecontent</xml>' | [
"Query",
"a",
"resource",
"and",
"decode",
"the",
"return",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/http.py#L18-L45 | train |
saltstack/salt | salt/runners/http.py | update_ca_bundle | def update_ca_bundle(target=None, source=None, merge_files=None):
'''
Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run http.update_ca_bundle
salt-run http.update_ca_bundle target=/path/to/cacerts.pem
salt-run http.update_ca_bundle source=https://example.com/cacerts.pem
If the ``target`` is not specified, it will be pulled from the ``ca_cert``
configuration variable available to the master. If it cannot be found there,
it will be placed at ``<<FILE_ROOTS>>/cacerts.pem``.
If the ``source`` is not specified, it will be pulled from the
``ca_cert_url`` configuration variable available to the master. If it cannot
be found, it will be downloaded from the cURL website, using an http (not
https) URL. USING THE DEFAULT URL SHOULD BE AVOIDED!
``merge_files`` may also be specified, which includes a string or list of
strings representing a file or files to be appended to the end of the CA
bundle, once it is downloaded.
CLI Example:
.. code-block:: bash
salt-run http.update_ca_bundle merge_files=/path/to/mycert.pem
'''
return salt.utils.http.update_ca_bundle(
target, source, __opts__, merge_files
) | python | def update_ca_bundle(target=None, source=None, merge_files=None):
'''
Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run http.update_ca_bundle
salt-run http.update_ca_bundle target=/path/to/cacerts.pem
salt-run http.update_ca_bundle source=https://example.com/cacerts.pem
If the ``target`` is not specified, it will be pulled from the ``ca_cert``
configuration variable available to the master. If it cannot be found there,
it will be placed at ``<<FILE_ROOTS>>/cacerts.pem``.
If the ``source`` is not specified, it will be pulled from the
``ca_cert_url`` configuration variable available to the master. If it cannot
be found, it will be downloaded from the cURL website, using an http (not
https) URL. USING THE DEFAULT URL SHOULD BE AVOIDED!
``merge_files`` may also be specified, which includes a string or list of
strings representing a file or files to be appended to the end of the CA
bundle, once it is downloaded.
CLI Example:
.. code-block:: bash
salt-run http.update_ca_bundle merge_files=/path/to/mycert.pem
'''
return salt.utils.http.update_ca_bundle(
target, source, __opts__, merge_files
) | [
"def",
"update_ca_bundle",
"(",
"target",
"=",
"None",
",",
"source",
"=",
"None",
",",
"merge_files",
"=",
"None",
")",
":",
"return",
"salt",
".",
"utils",
".",
"http",
".",
"update_ca_bundle",
"(",
"target",
",",
"source",
",",
"__opts__",
",",
"merge... | Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run http.update_ca_bundle
salt-run http.update_ca_bundle target=/path/to/cacerts.pem
salt-run http.update_ca_bundle source=https://example.com/cacerts.pem
If the ``target`` is not specified, it will be pulled from the ``ca_cert``
configuration variable available to the master. If it cannot be found there,
it will be placed at ``<<FILE_ROOTS>>/cacerts.pem``.
If the ``source`` is not specified, it will be pulled from the
``ca_cert_url`` configuration variable available to the master. If it cannot
be found, it will be downloaded from the cURL website, using an http (not
https) URL. USING THE DEFAULT URL SHOULD BE AVOIDED!
``merge_files`` may also be specified, which includes a string or list of
strings representing a file or files to be appended to the end of the CA
bundle, once it is downloaded.
CLI Example:
.. code-block:: bash
salt-run http.update_ca_bundle merge_files=/path/to/mycert.pem | [
"Update",
"the",
"local",
"CA",
"bundle",
"file",
"from",
"a",
"URL"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/http.py#L48-L83 | train |
saltstack/salt | salt/states/grafana4_user.py | present | def present(name,
password,
email=None,
is_admin=False,
fullname=None,
theme=None,
default_organization=None,
organizations=None,
profile='grafana'):
'''
Ensure that a user is present.
name
Name of the user.
password
Password of the user.
email
Optional - Email of the user.
is_admin
Optional - Set user as admin user. Default: False
fullname
Optional - Full name of the user.
theme
Optional - Selected theme of the user.
default_organization
Optional - Set user's default organization
organizations
Optional - List of viewer member organizations or pairs of organization and role that the user belongs to.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
Here is an example for using default_organization and organizations
parameters. The user will be added as a viewer to ReadonlyOrg, as an editor
to TestOrg and as an admin to AdminOrg. When she logs on, TestOrg will be
the default. The state will fail if any organisation is unknown or invalid
roles are defined.
.. code-block:: yaml
add_grafana_test_user:
grafana4_user.present:
- name: test
- password: 1234567890
- fullname: 'Test User'
- default_organization: TestOrg
- organizations:
- ReadonlyOrg
- TestOrg: Editor
- Staging: Admin
'''
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
ret = {'name': name, 'result': None, 'comment': None, 'changes': {}}
user = __salt__['grafana4.get_user'](name, profile)
create = not user
if create:
if __opts__['test']:
ret['comment'] = 'User {0} will be created'.format(name)
return ret
__salt__['grafana4.create_user'](
login=name,
password=password,
email=email,
name=fullname,
profile=profile)
user = __salt__['grafana4.get_user'](name, profile)
ret['changes']['new'] = user
user_data = __salt__['grafana4.get_user_data'](user['id'], profile=profile)
if default_organization:
try:
org_id = __salt__['grafana4.get_org'](default_organization, profile)['id']
except HTTPError as e:
ret['comment'] = 'Error while looking up user {}\'s default grafana org {}: {}'.format(
name, default_organization, e)
ret['result'] = False
return ret
new_data = _get_json_data(login=name, email=email, name=fullname, theme=theme,
orgId=org_id if default_organization else None,
defaults=user_data)
old_data = _get_json_data(login=None, email=None, name=None, theme=None,
orgId=None,
defaults=user_data)
if organizations:
ret = _update_user_organizations(name, user['id'], organizations, ret, profile)
if 'result' in ret and ret['result'] is False:
return ret
if new_data != old_data:
if __opts__['test']:
ret['comment'] = 'User {0} will be updated'.format(name)
dictupdate.update(ret['changes'], deep_diff(old_data, new_data))
return ret
__salt__['grafana4.update_user'](user['id'], profile=profile, orgid=org_id, **new_data)
dictupdate.update(
ret['changes'], deep_diff(
user_data, __salt__['grafana4.get_user_data'](user['id'])))
if user['isAdmin'] != is_admin:
if __opts__['test']:
ret['comment'] = 'User {0} isAdmin status will be updated'.format(
name)
return ret
__salt__['grafana4.update_user_permissions'](
user['id'], isGrafanaAdmin=is_admin, profile=profile)
dictupdate.update(ret['changes'], deep_diff(
user, __salt__['grafana4.get_user'](name, profile)))
ret['result'] = True
if create:
ret['changes'] = ret['changes']['new']
ret['comment'] = 'New user {0} added'.format(name)
else:
if ret['changes']:
ret['comment'] = 'User {0} updated'.format(name)
else:
ret['changes'] = {}
ret['comment'] = 'User {0} already up-to-date'.format(name)
return ret | python | def present(name,
password,
email=None,
is_admin=False,
fullname=None,
theme=None,
default_organization=None,
organizations=None,
profile='grafana'):
'''
Ensure that a user is present.
name
Name of the user.
password
Password of the user.
email
Optional - Email of the user.
is_admin
Optional - Set user as admin user. Default: False
fullname
Optional - Full name of the user.
theme
Optional - Selected theme of the user.
default_organization
Optional - Set user's default organization
organizations
Optional - List of viewer member organizations or pairs of organization and role that the user belongs to.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
Here is an example for using default_organization and organizations
parameters. The user will be added as a viewer to ReadonlyOrg, as an editor
to TestOrg and as an admin to AdminOrg. When she logs on, TestOrg will be
the default. The state will fail if any organisation is unknown or invalid
roles are defined.
.. code-block:: yaml
add_grafana_test_user:
grafana4_user.present:
- name: test
- password: 1234567890
- fullname: 'Test User'
- default_organization: TestOrg
- organizations:
- ReadonlyOrg
- TestOrg: Editor
- Staging: Admin
'''
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
ret = {'name': name, 'result': None, 'comment': None, 'changes': {}}
user = __salt__['grafana4.get_user'](name, profile)
create = not user
if create:
if __opts__['test']:
ret['comment'] = 'User {0} will be created'.format(name)
return ret
__salt__['grafana4.create_user'](
login=name,
password=password,
email=email,
name=fullname,
profile=profile)
user = __salt__['grafana4.get_user'](name, profile)
ret['changes']['new'] = user
user_data = __salt__['grafana4.get_user_data'](user['id'], profile=profile)
if default_organization:
try:
org_id = __salt__['grafana4.get_org'](default_organization, profile)['id']
except HTTPError as e:
ret['comment'] = 'Error while looking up user {}\'s default grafana org {}: {}'.format(
name, default_organization, e)
ret['result'] = False
return ret
new_data = _get_json_data(login=name, email=email, name=fullname, theme=theme,
orgId=org_id if default_organization else None,
defaults=user_data)
old_data = _get_json_data(login=None, email=None, name=None, theme=None,
orgId=None,
defaults=user_data)
if organizations:
ret = _update_user_organizations(name, user['id'], organizations, ret, profile)
if 'result' in ret and ret['result'] is False:
return ret
if new_data != old_data:
if __opts__['test']:
ret['comment'] = 'User {0} will be updated'.format(name)
dictupdate.update(ret['changes'], deep_diff(old_data, new_data))
return ret
__salt__['grafana4.update_user'](user['id'], profile=profile, orgid=org_id, **new_data)
dictupdate.update(
ret['changes'], deep_diff(
user_data, __salt__['grafana4.get_user_data'](user['id'])))
if user['isAdmin'] != is_admin:
if __opts__['test']:
ret['comment'] = 'User {0} isAdmin status will be updated'.format(
name)
return ret
__salt__['grafana4.update_user_permissions'](
user['id'], isGrafanaAdmin=is_admin, profile=profile)
dictupdate.update(ret['changes'], deep_diff(
user, __salt__['grafana4.get_user'](name, profile)))
ret['result'] = True
if create:
ret['changes'] = ret['changes']['new']
ret['comment'] = 'New user {0} added'.format(name)
else:
if ret['changes']:
ret['comment'] = 'User {0} updated'.format(name)
else:
ret['changes'] = {}
ret['comment'] = 'User {0} already up-to-date'.format(name)
return ret | [
"def",
"present",
"(",
"name",
",",
"password",
",",
"email",
"=",
"None",
",",
"is_admin",
"=",
"False",
",",
"fullname",
"=",
"None",
",",
"theme",
"=",
"None",
",",
"default_organization",
"=",
"None",
",",
"organizations",
"=",
"None",
",",
"profile"... | Ensure that a user is present.
name
Name of the user.
password
Password of the user.
email
Optional - Email of the user.
is_admin
Optional - Set user as admin user. Default: False
fullname
Optional - Full name of the user.
theme
Optional - Selected theme of the user.
default_organization
Optional - Set user's default organization
organizations
Optional - List of viewer member organizations or pairs of organization and role that the user belongs to.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
Here is an example for using default_organization and organizations
parameters. The user will be added as a viewer to ReadonlyOrg, as an editor
to TestOrg and as an admin to AdminOrg. When she logs on, TestOrg will be
the default. The state will fail if any organisation is unknown or invalid
roles are defined.
.. code-block:: yaml
add_grafana_test_user:
grafana4_user.present:
- name: test
- password: 1234567890
- fullname: 'Test User'
- default_organization: TestOrg
- organizations:
- ReadonlyOrg
- TestOrg: Editor
- Staging: Admin | [
"Ensure",
"that",
"a",
"user",
"is",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana4_user.py#L55-L187 | train |
saltstack/salt | salt/states/grafana4_user.py | absent | def absent(name, profile='grafana'):
'''
Ensure that a user is present.
name
Name of the user to remove.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
'''
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
ret = {'name': name, 'result': None, 'comment': None, 'changes': {}}
user = __salt__['grafana4.get_user'](name, profile)
if user:
if __opts__['test']:
ret['comment'] = 'User {0} will be deleted'.format(name)
return ret
orgs = __salt__['grafana4.get_user_orgs'](user['id'], profile=profile)
__salt__['grafana4.delete_user'](user['id'], profile=profile)
for org in orgs:
if org['name'] == user['email']:
# Remove entire Org in the case where auto_assign_org=false:
# When set to false, new users will automatically cause a new
# organization to be created for that new user (the org name
# will be the email)
__salt__['grafana4.delete_org'](org['orgId'], profile=profile)
else:
__salt__['grafana4.delete_user_org'](
user['id'], org['orgId'], profile=profile)
else:
ret['result'] = True
ret['comment'] = 'User {0} already absent'.format(name)
return ret
ret['result'] = True
ret['changes'][name] = 'Absent'
ret['comment'] = 'User {0} was deleted'.format(name)
return ret | python | def absent(name, profile='grafana'):
'''
Ensure that a user is present.
name
Name of the user to remove.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
'''
if isinstance(profile, string_types):
profile = __salt__['config.option'](profile)
ret = {'name': name, 'result': None, 'comment': None, 'changes': {}}
user = __salt__['grafana4.get_user'](name, profile)
if user:
if __opts__['test']:
ret['comment'] = 'User {0} will be deleted'.format(name)
return ret
orgs = __salt__['grafana4.get_user_orgs'](user['id'], profile=profile)
__salt__['grafana4.delete_user'](user['id'], profile=profile)
for org in orgs:
if org['name'] == user['email']:
# Remove entire Org in the case where auto_assign_org=false:
# When set to false, new users will automatically cause a new
# organization to be created for that new user (the org name
# will be the email)
__salt__['grafana4.delete_org'](org['orgId'], profile=profile)
else:
__salt__['grafana4.delete_user_org'](
user['id'], org['orgId'], profile=profile)
else:
ret['result'] = True
ret['comment'] = 'User {0} already absent'.format(name)
return ret
ret['result'] = True
ret['changes'][name] = 'Absent'
ret['comment'] = 'User {0} was deleted'.format(name)
return ret | [
"def",
"absent",
"(",
"name",
",",
"profile",
"=",
"'grafana'",
")",
":",
"if",
"isinstance",
"(",
"profile",
",",
"string_types",
")",
":",
"profile",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"profile",
")",
"ret",
"=",
"{",
"'name'",
":",
"... | Ensure that a user is present.
name
Name of the user to remove.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'. | [
"Ensure",
"that",
"a",
"user",
"is",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana4_user.py#L190-L231 | train |
saltstack/salt | salt/modules/saltcloudmod.py | create | def create(name, profile):
'''
Create the named vm
CLI Example:
.. code-block:: bash
salt <minion-id> saltcloud.create webserver rackspace_centos_512
'''
cmd = 'salt-cloud --out json -p {0} {1}'.format(profile, name)
out = __salt__['cmd.run_stdout'](cmd, python_shell=False)
try:
ret = salt.utils.json.loads(out)
except ValueError:
ret = {}
return ret | python | def create(name, profile):
'''
Create the named vm
CLI Example:
.. code-block:: bash
salt <minion-id> saltcloud.create webserver rackspace_centos_512
'''
cmd = 'salt-cloud --out json -p {0} {1}'.format(profile, name)
out = __salt__['cmd.run_stdout'](cmd, python_shell=False)
try:
ret = salt.utils.json.loads(out)
except ValueError:
ret = {}
return ret | [
"def",
"create",
"(",
"name",
",",
"profile",
")",
":",
"cmd",
"=",
"'salt-cloud --out json -p {0} {1}'",
".",
"format",
"(",
"profile",
",",
"name",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run_stdout'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
... | Create the named vm
CLI Example:
.. code-block:: bash
salt <minion-id> saltcloud.create webserver rackspace_centos_512 | [
"Create",
"the",
"named",
"vm"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltcloudmod.py#L32-L48 | train |
saltstack/salt | salt/states/postgres_database.py | present | def present(name,
tablespace=None,
encoding=None,
lc_collate=None,
lc_ctype=None,
owner=None,
owner_recurse=False,
template=None,
user=None,
maintenance_db=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Ensure that the named database is present with the specified properties.
For more information about all of these options see man createdb(1)
name
The name of the database to manage
tablespace
Default tablespace for the database
encoding
The character encoding scheme to be used in this database
lc_collate
The LC_COLLATE setting to be used in this database
lc_ctype
The LC_CTYPE setting to be used in this database
owner
The username of the database owner
owner_recurse
Recurse owner change to all relations in the database
template
The template database from which to build this database
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
.. versionadded:: 0.17.0
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Database {0} is already present'.format(name)}
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
dbs = __salt__['postgres.db_list'](**db_args)
db_params = dbs.get(name, {})
if name in dbs and all((
db_params.get('Tablespace') == tablespace if tablespace else True,
(
db_params.get('Encoding').lower() == encoding.lower()
if encoding else True
),
db_params.get('Collate') == lc_collate if lc_collate else True,
db_params.get('Ctype') == lc_ctype if lc_ctype else True,
db_params.get('Owner') == owner if owner else True
)):
return ret
elif name in dbs and any((
db_params.get('Encoding').lower() != encoding.lower() if encoding else False,
db_params.get('Collate') != lc_collate if lc_collate else False,
db_params.get('Ctype') != lc_ctype if lc_ctype else False
)):
ret['comment'] = 'Database {0} has wrong parameters ' \
'which couldn\'t be changed on fly.'.format(name)
ret['result'] = False
return ret
# The database is not present, make it!
if __opts__['test']:
ret['result'] = None
if name not in dbs:
ret['comment'] = 'Database {0} is set to be created'.format(name)
else:
ret['comment'] = 'Database {0} exists, but parameters ' \
'need to be changed'.format(name)
return ret
if (
name not in dbs and __salt__['postgres.db_create'](
name,
tablespace=tablespace,
encoding=encoding,
lc_collate=lc_collate,
lc_ctype=lc_ctype,
owner=owner,
template=template,
**db_args)
):
ret['comment'] = 'The database {0} has been created'.format(name)
ret['changes'][name] = 'Present'
elif (
name in dbs and __salt__['postgres.db_alter'](
name,
tablespace=tablespace,
owner=owner, owner_recurse=owner_recurse, **db_args)
):
ret['comment'] = ('Parameters for database {0} have been changed'
).format(name)
ret['changes'][name] = 'Parameters changed'
elif name in dbs:
ret['comment'] = ('Failed to change parameters for database {0}'
).format(name)
ret['result'] = False
else:
ret['comment'] = 'Failed to create database {0}'.format(name)
ret['result'] = False
return ret | python | def present(name,
tablespace=None,
encoding=None,
lc_collate=None,
lc_ctype=None,
owner=None,
owner_recurse=False,
template=None,
user=None,
maintenance_db=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Ensure that the named database is present with the specified properties.
For more information about all of these options see man createdb(1)
name
The name of the database to manage
tablespace
Default tablespace for the database
encoding
The character encoding scheme to be used in this database
lc_collate
The LC_COLLATE setting to be used in this database
lc_ctype
The LC_CTYPE setting to be used in this database
owner
The username of the database owner
owner_recurse
Recurse owner change to all relations in the database
template
The template database from which to build this database
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
.. versionadded:: 0.17.0
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Database {0} is already present'.format(name)}
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'host': db_host,
'user': db_user,
'port': db_port,
'password': db_password,
}
dbs = __salt__['postgres.db_list'](**db_args)
db_params = dbs.get(name, {})
if name in dbs and all((
db_params.get('Tablespace') == tablespace if tablespace else True,
(
db_params.get('Encoding').lower() == encoding.lower()
if encoding else True
),
db_params.get('Collate') == lc_collate if lc_collate else True,
db_params.get('Ctype') == lc_ctype if lc_ctype else True,
db_params.get('Owner') == owner if owner else True
)):
return ret
elif name in dbs and any((
db_params.get('Encoding').lower() != encoding.lower() if encoding else False,
db_params.get('Collate') != lc_collate if lc_collate else False,
db_params.get('Ctype') != lc_ctype if lc_ctype else False
)):
ret['comment'] = 'Database {0} has wrong parameters ' \
'which couldn\'t be changed on fly.'.format(name)
ret['result'] = False
return ret
# The database is not present, make it!
if __opts__['test']:
ret['result'] = None
if name not in dbs:
ret['comment'] = 'Database {0} is set to be created'.format(name)
else:
ret['comment'] = 'Database {0} exists, but parameters ' \
'need to be changed'.format(name)
return ret
if (
name not in dbs and __salt__['postgres.db_create'](
name,
tablespace=tablespace,
encoding=encoding,
lc_collate=lc_collate,
lc_ctype=lc_ctype,
owner=owner,
template=template,
**db_args)
):
ret['comment'] = 'The database {0} has been created'.format(name)
ret['changes'][name] = 'Present'
elif (
name in dbs and __salt__['postgres.db_alter'](
name,
tablespace=tablespace,
owner=owner, owner_recurse=owner_recurse, **db_args)
):
ret['comment'] = ('Parameters for database {0} have been changed'
).format(name)
ret['changes'][name] = 'Parameters changed'
elif name in dbs:
ret['comment'] = ('Failed to change parameters for database {0}'
).format(name)
ret['result'] = False
else:
ret['comment'] = 'Failed to create database {0}'.format(name)
ret['result'] = False
return ret | [
"def",
"present",
"(",
"name",
",",
"tablespace",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"lc_collate",
"=",
"None",
",",
"lc_ctype",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"owner_recurse",
"=",
"False",
",",
"template",
"=",
"None",
",",... | Ensure that the named database is present with the specified properties.
For more information about all of these options see man createdb(1)
name
The name of the database to manage
tablespace
Default tablespace for the database
encoding
The character encoding scheme to be used in this database
lc_collate
The LC_COLLATE setting to be used in this database
lc_ctype
The LC_CTYPE setting to be used in this database
owner
The username of the database owner
owner_recurse
Recurse owner change to all relations in the database
template
The template database from which to build this database
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
.. versionadded:: 0.17.0 | [
"Ensure",
"that",
"the",
"named",
"database",
"is",
"present",
"with",
"the",
"specified",
"properties",
".",
"For",
"more",
"information",
"about",
"all",
"of",
"these",
"options",
"see",
"man",
"createdb",
"(",
"1",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_database.py#L26-L161 | train |
saltstack/salt | salt/modules/rbac_solaris.py | profile_list | def profile_list(default_only=False):
'''
List all available profiles
default_only : boolean
return only default profile
CLI Example:
.. code-block:: bash
salt '*' rbac.profile_list
'''
profiles = {}
default_profiles = ['All']
## lookup default profile(s)
with salt.utils.files.fopen('/etc/security/policy.conf', 'r') as policy_conf:
for policy in policy_conf:
policy = salt.utils.stringutils.to_unicode(policy)
policy = policy.split('=')
if policy[0].strip() == 'PROFS_GRANTED':
default_profiles.extend(policy[1].strip().split(','))
## read prof_attr file (profname:res1:res2:desc:attr)
with salt.utils.files.fopen('/etc/security/prof_attr', 'r') as prof_attr:
for profile in prof_attr:
profile = salt.utils.stringutils.to_unicode(profile)
profile = profile.split(':')
# skip comments and non complaint lines
if len(profile) != 5:
continue
# add profile info to dict
profiles[profile[0]] = profile[3]
## filtered profiles
if default_only:
for p in [p for p in profiles if p not in default_profiles]:
del profiles[p]
return profiles | python | def profile_list(default_only=False):
'''
List all available profiles
default_only : boolean
return only default profile
CLI Example:
.. code-block:: bash
salt '*' rbac.profile_list
'''
profiles = {}
default_profiles = ['All']
## lookup default profile(s)
with salt.utils.files.fopen('/etc/security/policy.conf', 'r') as policy_conf:
for policy in policy_conf:
policy = salt.utils.stringutils.to_unicode(policy)
policy = policy.split('=')
if policy[0].strip() == 'PROFS_GRANTED':
default_profiles.extend(policy[1].strip().split(','))
## read prof_attr file (profname:res1:res2:desc:attr)
with salt.utils.files.fopen('/etc/security/prof_attr', 'r') as prof_attr:
for profile in prof_attr:
profile = salt.utils.stringutils.to_unicode(profile)
profile = profile.split(':')
# skip comments and non complaint lines
if len(profile) != 5:
continue
# add profile info to dict
profiles[profile[0]] = profile[3]
## filtered profiles
if default_only:
for p in [p for p in profiles if p not in default_profiles]:
del profiles[p]
return profiles | [
"def",
"profile_list",
"(",
"default_only",
"=",
"False",
")",
":",
"profiles",
"=",
"{",
"}",
"default_profiles",
"=",
"[",
"'All'",
"]",
"## lookup default profile(s)",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/etc/security/policy.conf'... | List all available profiles
default_only : boolean
return only default profile
CLI Example:
.. code-block:: bash
salt '*' rbac.profile_list | [
"List",
"all",
"available",
"profiles"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbac_solaris.py#L34-L76 | train |
saltstack/salt | salt/modules/rbac_solaris.py | profile_get | def profile_get(user, default_hidden=True):
'''
List profiles for user
user : string
username
default_hidden : boolean
hide default profiles
CLI Example:
.. code-block:: bash
salt '*' rbac.profile_get leo
salt '*' rbac.profile_get leo default_hidden=False
'''
user_profiles = []
## read user_attr file (user:qualifier:res1:res2:attr)
with salt.utils.files.fopen('/etc/user_attr', 'r') as user_attr:
for profile in user_attr:
profile = salt.utils.stringutils.to_unicode(profile)
profile = profile.strip().split(':')
# skip comments and non complaint lines
if len(profile) != 5:
continue
# skip other users
if profile[0] != user:
continue
# parse attr
attrs = {}
for attr in profile[4].strip().split(';'):
attr_key, attr_val = attr.strip().split('=')
if attr_key in ['auths', 'profiles', 'roles']:
attrs[attr_key] = attr_val.strip().split(',')
else:
attrs[attr_key] = attr_val
if 'profiles' in attrs:
user_profiles.extend(attrs['profiles'])
## remove default profiles
if default_hidden:
for profile in profile_list(default_only=True):
if profile in user_profiles:
user_profiles.remove(profile)
return list(set(user_profiles)) | python | def profile_get(user, default_hidden=True):
'''
List profiles for user
user : string
username
default_hidden : boolean
hide default profiles
CLI Example:
.. code-block:: bash
salt '*' rbac.profile_get leo
salt '*' rbac.profile_get leo default_hidden=False
'''
user_profiles = []
## read user_attr file (user:qualifier:res1:res2:attr)
with salt.utils.files.fopen('/etc/user_attr', 'r') as user_attr:
for profile in user_attr:
profile = salt.utils.stringutils.to_unicode(profile)
profile = profile.strip().split(':')
# skip comments and non complaint lines
if len(profile) != 5:
continue
# skip other users
if profile[0] != user:
continue
# parse attr
attrs = {}
for attr in profile[4].strip().split(';'):
attr_key, attr_val = attr.strip().split('=')
if attr_key in ['auths', 'profiles', 'roles']:
attrs[attr_key] = attr_val.strip().split(',')
else:
attrs[attr_key] = attr_val
if 'profiles' in attrs:
user_profiles.extend(attrs['profiles'])
## remove default profiles
if default_hidden:
for profile in profile_list(default_only=True):
if profile in user_profiles:
user_profiles.remove(profile)
return list(set(user_profiles)) | [
"def",
"profile_get",
"(",
"user",
",",
"default_hidden",
"=",
"True",
")",
":",
"user_profiles",
"=",
"[",
"]",
"## read user_attr file (user:qualifier:res1:res2:attr)",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/etc/user_attr'",
",",
"'r'"... | List profiles for user
user : string
username
default_hidden : boolean
hide default profiles
CLI Example:
.. code-block:: bash
salt '*' rbac.profile_get leo
salt '*' rbac.profile_get leo default_hidden=False | [
"List",
"profiles",
"for",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbac_solaris.py#L79-L128 | train |
saltstack/salt | salt/modules/rbac_solaris.py | profile_add | def profile_add(user, profile):
'''
Add profile to user
user : string
username
profile : string
profile name
CLI Example:
.. code-block:: bash
salt '*' rbac.profile_add martine 'Primary Administrator'
salt '*' rbac.profile_add martine 'User Management,User Security'
'''
ret = {}
## validate profiles
profiles = profile.split(',')
known_profiles = profile_list().keys()
valid_profiles = [p for p in profiles if p in known_profiles]
log.debug(
'rbac.profile_add - profiles=%s, known_profiles=%s, valid_profiles=%s',
profiles,
known_profiles,
valid_profiles,
)
## update user profiles
if valid_profiles:
res = __salt__['cmd.run_all']('usermod -P "{profiles}" {login}'.format(
login=user,
profiles=','.join(set(profile_get(user) + valid_profiles)),
))
if res['retcode'] > 0:
ret['Error'] = {
'retcode': res['retcode'],
'message': res['stderr'] if 'stderr' in res else res['stdout']
}
return ret
## update return value
active_profiles = profile_get(user, False)
for p in profiles:
if p not in valid_profiles:
ret[p] = 'Unknown'
elif p in active_profiles:
ret[p] = 'Added'
else:
ret[p] = 'Failed'
return ret | python | def profile_add(user, profile):
'''
Add profile to user
user : string
username
profile : string
profile name
CLI Example:
.. code-block:: bash
salt '*' rbac.profile_add martine 'Primary Administrator'
salt '*' rbac.profile_add martine 'User Management,User Security'
'''
ret = {}
## validate profiles
profiles = profile.split(',')
known_profiles = profile_list().keys()
valid_profiles = [p for p in profiles if p in known_profiles]
log.debug(
'rbac.profile_add - profiles=%s, known_profiles=%s, valid_profiles=%s',
profiles,
known_profiles,
valid_profiles,
)
## update user profiles
if valid_profiles:
res = __salt__['cmd.run_all']('usermod -P "{profiles}" {login}'.format(
login=user,
profiles=','.join(set(profile_get(user) + valid_profiles)),
))
if res['retcode'] > 0:
ret['Error'] = {
'retcode': res['retcode'],
'message': res['stderr'] if 'stderr' in res else res['stdout']
}
return ret
## update return value
active_profiles = profile_get(user, False)
for p in profiles:
if p not in valid_profiles:
ret[p] = 'Unknown'
elif p in active_profiles:
ret[p] = 'Added'
else:
ret[p] = 'Failed'
return ret | [
"def",
"profile_add",
"(",
"user",
",",
"profile",
")",
":",
"ret",
"=",
"{",
"}",
"## validate profiles",
"profiles",
"=",
"profile",
".",
"split",
"(",
"','",
")",
"known_profiles",
"=",
"profile_list",
"(",
")",
".",
"keys",
"(",
")",
"valid_profiles",
... | Add profile to user
user : string
username
profile : string
profile name
CLI Example:
.. code-block:: bash
salt '*' rbac.profile_add martine 'Primary Administrator'
salt '*' rbac.profile_add martine 'User Management,User Security' | [
"Add",
"profile",
"to",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbac_solaris.py#L131-L183 | train |
saltstack/salt | salt/modules/rbac_solaris.py | role_list | def role_list():
'''
List all available roles
CLI Example:
.. code-block:: bash
salt '*' rbac.role_list
'''
roles = {}
## read user_attr file (user:qualifier:res1:res2:attr)
with salt.utils.files.fopen('/etc/user_attr', 'r') as user_attr:
for role in user_attr:
role = salt.utils.stringutils.to_unicode(role)
role = role.split(':')
# skip comments and non complaint lines
if len(role) != 5:
continue
# parse attr
attrs = {}
for attr in role[4].split(';'):
attr_key, attr_val = attr.split('=')
if attr_key in ['auths', 'profiles', 'roles']:
attrs[attr_key] = attr_val.split(',')
else:
attrs[attr_key] = attr_val
role[4] = attrs
# add role info to dict
if 'type' in role[4] and role[4]['type'] == 'role':
del role[4]['type']
roles[role[0]] = role[4]
return roles | python | def role_list():
'''
List all available roles
CLI Example:
.. code-block:: bash
salt '*' rbac.role_list
'''
roles = {}
## read user_attr file (user:qualifier:res1:res2:attr)
with salt.utils.files.fopen('/etc/user_attr', 'r') as user_attr:
for role in user_attr:
role = salt.utils.stringutils.to_unicode(role)
role = role.split(':')
# skip comments and non complaint lines
if len(role) != 5:
continue
# parse attr
attrs = {}
for attr in role[4].split(';'):
attr_key, attr_val = attr.split('=')
if attr_key in ['auths', 'profiles', 'roles']:
attrs[attr_key] = attr_val.split(',')
else:
attrs[attr_key] = attr_val
role[4] = attrs
# add role info to dict
if 'type' in role[4] and role[4]['type'] == 'role':
del role[4]['type']
roles[role[0]] = role[4]
return roles | [
"def",
"role_list",
"(",
")",
":",
"roles",
"=",
"{",
"}",
"## read user_attr file (user:qualifier:res1:res2:attr)",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/etc/user_attr'",
",",
"'r'",
")",
"as",
"user_attr",
":",
"for",
"role",
"in"... | List all available roles
CLI Example:
.. code-block:: bash
salt '*' rbac.role_list | [
"List",
"all",
"available",
"roles"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbac_solaris.py#L241-L278 | train |
saltstack/salt | salt/modules/rbac_solaris.py | role_get | def role_get(user):
'''
List roles for user
user : string
username
CLI Example:
.. code-block:: bash
salt '*' rbac.role_get leo
'''
user_roles = []
## read user_attr file (user:qualifier:res1:res2:attr)
with salt.utils.files.fopen('/etc/user_attr', 'r') as user_attr:
for role in user_attr:
role = salt.utils.stringutils.to_unicode(role)
role = role.strip().strip().split(':')
# skip comments and non complaint lines
if len(role) != 5:
continue
# skip other users
if role[0] != user:
continue
# parse attr
attrs = {}
for attr in role[4].strip().split(';'):
attr_key, attr_val = attr.strip().split('=')
if attr_key in ['auths', 'profiles', 'roles']:
attrs[attr_key] = attr_val.strip().split(',')
else:
attrs[attr_key] = attr_val
if 'roles' in attrs:
user_roles.extend(attrs['roles'])
return list(set(user_roles)) | python | def role_get(user):
'''
List roles for user
user : string
username
CLI Example:
.. code-block:: bash
salt '*' rbac.role_get leo
'''
user_roles = []
## read user_attr file (user:qualifier:res1:res2:attr)
with salt.utils.files.fopen('/etc/user_attr', 'r') as user_attr:
for role in user_attr:
role = salt.utils.stringutils.to_unicode(role)
role = role.strip().strip().split(':')
# skip comments and non complaint lines
if len(role) != 5:
continue
# skip other users
if role[0] != user:
continue
# parse attr
attrs = {}
for attr in role[4].strip().split(';'):
attr_key, attr_val = attr.strip().split('=')
if attr_key in ['auths', 'profiles', 'roles']:
attrs[attr_key] = attr_val.strip().split(',')
else:
attrs[attr_key] = attr_val
if 'roles' in attrs:
user_roles.extend(attrs['roles'])
return list(set(user_roles)) | [
"def",
"role_get",
"(",
"user",
")",
":",
"user_roles",
"=",
"[",
"]",
"## read user_attr file (user:qualifier:res1:res2:attr)",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/etc/user_attr'",
",",
"'r'",
")",
"as",
"user_attr",
":",
"for",
... | List roles for user
user : string
username
CLI Example:
.. code-block:: bash
salt '*' rbac.role_get leo | [
"List",
"roles",
"for",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbac_solaris.py#L281-L321 | train |
saltstack/salt | salt/modules/rbac_solaris.py | role_add | def role_add(user, role):
'''
Add role to user
user : string
username
role : string
role name
CLI Example:
.. code-block:: bash
salt '*' rbac.role_add martine netcfg
salt '*' rbac.role_add martine netcfg,zfssnap
'''
ret = {}
## validate roles
roles = role.split(',')
known_roles = role_list().keys()
valid_roles = [r for r in roles if r in known_roles]
log.debug(
'rbac.role_add - roles=%s, known_roles=%s, valid_roles=%s',
roles,
known_roles,
valid_roles,
)
## update user roles
if valid_roles:
res = __salt__['cmd.run_all']('usermod -R "{roles}" {login}'.format(
login=user,
roles=','.join(set(role_get(user) + valid_roles)),
))
if res['retcode'] > 0:
ret['Error'] = {
'retcode': res['retcode'],
'message': res['stderr'] if 'stderr' in res else res['stdout']
}
return ret
## update return value
active_roles = role_get(user)
for r in roles:
if r not in valid_roles:
ret[r] = 'Unknown'
elif r in active_roles:
ret[r] = 'Added'
else:
ret[r] = 'Failed'
return ret | python | def role_add(user, role):
'''
Add role to user
user : string
username
role : string
role name
CLI Example:
.. code-block:: bash
salt '*' rbac.role_add martine netcfg
salt '*' rbac.role_add martine netcfg,zfssnap
'''
ret = {}
## validate roles
roles = role.split(',')
known_roles = role_list().keys()
valid_roles = [r for r in roles if r in known_roles]
log.debug(
'rbac.role_add - roles=%s, known_roles=%s, valid_roles=%s',
roles,
known_roles,
valid_roles,
)
## update user roles
if valid_roles:
res = __salt__['cmd.run_all']('usermod -R "{roles}" {login}'.format(
login=user,
roles=','.join(set(role_get(user) + valid_roles)),
))
if res['retcode'] > 0:
ret['Error'] = {
'retcode': res['retcode'],
'message': res['stderr'] if 'stderr' in res else res['stdout']
}
return ret
## update return value
active_roles = role_get(user)
for r in roles:
if r not in valid_roles:
ret[r] = 'Unknown'
elif r in active_roles:
ret[r] = 'Added'
else:
ret[r] = 'Failed'
return ret | [
"def",
"role_add",
"(",
"user",
",",
"role",
")",
":",
"ret",
"=",
"{",
"}",
"## validate roles",
"roles",
"=",
"role",
".",
"split",
"(",
"','",
")",
"known_roles",
"=",
"role_list",
"(",
")",
".",
"keys",
"(",
")",
"valid_roles",
"=",
"[",
"r",
"... | Add role to user
user : string
username
role : string
role name
CLI Example:
.. code-block:: bash
salt '*' rbac.role_add martine netcfg
salt '*' rbac.role_add martine netcfg,zfssnap | [
"Add",
"role",
"to",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbac_solaris.py#L324-L376 | train |
saltstack/salt | salt/modules/rbac_solaris.py | auth_list | def auth_list():
'''
List all available authorization
CLI Example:
.. code-block:: bash
salt '*' rbac.auth_list
'''
auths = {}
## read auth_attr file (name:res1:res2:short_desc:long_desc:attr)
with salt.utils.files.fopen('/etc/security/auth_attr', 'r') as auth_attr:
for auth in auth_attr:
auth = salt.utils.stringutils.to_unicode(auth)
auth = auth.split(':')
# skip comments and non complaint lines
if len(auth) != 6:
continue
# add auth info to dict
if auth[0][-1:] == '.':
auth[0] = '{0}*'.format(auth[0])
auths[auth[0]] = auth[3]
return auths | python | def auth_list():
'''
List all available authorization
CLI Example:
.. code-block:: bash
salt '*' rbac.auth_list
'''
auths = {}
## read auth_attr file (name:res1:res2:short_desc:long_desc:attr)
with salt.utils.files.fopen('/etc/security/auth_attr', 'r') as auth_attr:
for auth in auth_attr:
auth = salt.utils.stringutils.to_unicode(auth)
auth = auth.split(':')
# skip comments and non complaint lines
if len(auth) != 6:
continue
# add auth info to dict
if auth[0][-1:] == '.':
auth[0] = '{0}*'.format(auth[0])
auths[auth[0]] = auth[3]
return auths | [
"def",
"auth_list",
"(",
")",
":",
"auths",
"=",
"{",
"}",
"## read auth_attr file (name:res1:res2:short_desc:long_desc:attr)",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/etc/security/auth_attr'",
",",
"'r'",
")",
"as",
"auth_attr",
":",
"fo... | List all available authorization
CLI Example:
.. code-block:: bash
salt '*' rbac.auth_list | [
"List",
"all",
"available",
"authorization"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbac_solaris.py#L434-L461 | train |
saltstack/salt | salt/modules/rbac_solaris.py | auth_get | def auth_get(user, computed=True):
'''
List authorization for user
user : string
username
computed : boolean
merge results from `auths` command into data from user_attr
CLI Example:
.. code-block:: bash
salt '*' rbac.auth_get leo
'''
user_auths = []
## read user_attr file (user:qualifier:res1:res2:attr)
with salt.utils.files.fopen('/etc/user_attr', 'r') as user_attr:
for auth in user_attr:
auth = salt.utils.stringutils.to_unicode(auth)
auth = auth.strip().split(':')
# skip comments and non complaint lines
if len(auth) != 5:
continue
# skip other users
if auth[0] != user:
continue
# parse attr
attrs = {}
for attr in auth[4].strip().split(';'):
attr_key, attr_val = attr.strip().split('=')
if attr_key in ['auths', 'profiles', 'roles']:
attrs[attr_key] = attr_val.strip().split(',')
else:
attrs[attr_key] = attr_val
if 'auths' in attrs:
user_auths.extend(attrs['auths'])
## also parse auths command
if computed:
res = __salt__['cmd.run_all']('auths {0}'.format(user))
if res['retcode'] == 0:
for auth in res['stdout'].splitlines():
if ',' in auth:
user_auths.extend(auth.strip().split(','))
else:
user_auths.append(auth.strip())
return list(set(user_auths)) | python | def auth_get(user, computed=True):
'''
List authorization for user
user : string
username
computed : boolean
merge results from `auths` command into data from user_attr
CLI Example:
.. code-block:: bash
salt '*' rbac.auth_get leo
'''
user_auths = []
## read user_attr file (user:qualifier:res1:res2:attr)
with salt.utils.files.fopen('/etc/user_attr', 'r') as user_attr:
for auth in user_attr:
auth = salt.utils.stringutils.to_unicode(auth)
auth = auth.strip().split(':')
# skip comments and non complaint lines
if len(auth) != 5:
continue
# skip other users
if auth[0] != user:
continue
# parse attr
attrs = {}
for attr in auth[4].strip().split(';'):
attr_key, attr_val = attr.strip().split('=')
if attr_key in ['auths', 'profiles', 'roles']:
attrs[attr_key] = attr_val.strip().split(',')
else:
attrs[attr_key] = attr_val
if 'auths' in attrs:
user_auths.extend(attrs['auths'])
## also parse auths command
if computed:
res = __salt__['cmd.run_all']('auths {0}'.format(user))
if res['retcode'] == 0:
for auth in res['stdout'].splitlines():
if ',' in auth:
user_auths.extend(auth.strip().split(','))
else:
user_auths.append(auth.strip())
return list(set(user_auths)) | [
"def",
"auth_get",
"(",
"user",
",",
"computed",
"=",
"True",
")",
":",
"user_auths",
"=",
"[",
"]",
"## read user_attr file (user:qualifier:res1:res2:attr)",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/etc/user_attr'",
",",
"'r'",
")",
"... | List authorization for user
user : string
username
computed : boolean
merge results from `auths` command into data from user_attr
CLI Example:
.. code-block:: bash
salt '*' rbac.auth_get leo | [
"List",
"authorization",
"for",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbac_solaris.py#L464-L516 | train |
saltstack/salt | salt/modules/rbac_solaris.py | auth_add | def auth_add(user, auth):
'''
Add authorization to user
user : string
username
auth : string
authorization name
CLI Example:
.. code-block:: bash
salt '*' rbac.auth_add martine solaris.zone.manage
salt '*' rbac.auth_add martine solaris.zone.manage,solaris.mail.mailq
'''
ret = {}
## validate auths
auths = auth.split(',')
known_auths = auth_list().keys()
valid_auths = [r for r in auths if r in known_auths]
log.debug(
'rbac.auth_add - auths=%s, known_auths=%s, valid_auths=%s',
auths,
known_auths,
valid_auths,
)
## update user auths
if valid_auths:
res = __salt__['cmd.run_all']('usermod -A "{auths}" {login}'.format(
login=user,
auths=','.join(set(auth_get(user, False) + valid_auths)),
))
if res['retcode'] > 0:
ret['Error'] = {
'retcode': res['retcode'],
'message': res['stderr'] if 'stderr' in res else res['stdout']
}
return ret
## update return value
active_auths = auth_get(user, False)
for a in auths:
if a not in valid_auths:
ret[a] = 'Unknown'
elif a in active_auths:
ret[a] = 'Added'
else:
ret[a] = 'Failed'
return ret | python | def auth_add(user, auth):
'''
Add authorization to user
user : string
username
auth : string
authorization name
CLI Example:
.. code-block:: bash
salt '*' rbac.auth_add martine solaris.zone.manage
salt '*' rbac.auth_add martine solaris.zone.manage,solaris.mail.mailq
'''
ret = {}
## validate auths
auths = auth.split(',')
known_auths = auth_list().keys()
valid_auths = [r for r in auths if r in known_auths]
log.debug(
'rbac.auth_add - auths=%s, known_auths=%s, valid_auths=%s',
auths,
known_auths,
valid_auths,
)
## update user auths
if valid_auths:
res = __salt__['cmd.run_all']('usermod -A "{auths}" {login}'.format(
login=user,
auths=','.join(set(auth_get(user, False) + valid_auths)),
))
if res['retcode'] > 0:
ret['Error'] = {
'retcode': res['retcode'],
'message': res['stderr'] if 'stderr' in res else res['stdout']
}
return ret
## update return value
active_auths = auth_get(user, False)
for a in auths:
if a not in valid_auths:
ret[a] = 'Unknown'
elif a in active_auths:
ret[a] = 'Added'
else:
ret[a] = 'Failed'
return ret | [
"def",
"auth_add",
"(",
"user",
",",
"auth",
")",
":",
"ret",
"=",
"{",
"}",
"## validate auths",
"auths",
"=",
"auth",
".",
"split",
"(",
"','",
")",
"known_auths",
"=",
"auth_list",
"(",
")",
".",
"keys",
"(",
")",
"valid_auths",
"=",
"[",
"r",
"... | Add authorization to user
user : string
username
auth : string
authorization name
CLI Example:
.. code-block:: bash
salt '*' rbac.auth_add martine solaris.zone.manage
salt '*' rbac.auth_add martine solaris.zone.manage,solaris.mail.mailq | [
"Add",
"authorization",
"to",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rbac_solaris.py#L519-L571 | train |
saltstack/salt | salt/states/netacl.py | term | def term(name,
filter_name,
term_name,
filter_options=None,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=False,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d',
test=False,
commit=True,
debug=False,
source_service=None,
destination_service=None,
**term_fields):
'''
Manage the configuration of a specific policy term.
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.
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``.
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: ``False``
Merge the CLI variables with the pillar. Default: ``False``.
The properties specified through the state arguments have higher priority than the pillar.
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>).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
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 'edge01.bjm01' state.sls router.acl
Output Example:
.. code-block:: text
edge01.bjm01:
----------
ID: update_icmp_first_term
Function: netacl.term
Result: None
Comment: Testing mode: Configuration discarded.
Started: 12:49:09.174179
Duration: 5751.882 ms
Changes:
----------
diff:
[edit firewall]
+ family inet {
+ /*
+ ** $Id: update_icmp_first_term $
+ ** $Date: 2017/02/30 $
+ **
+ */
+ filter block-icmp {
+ term first-term {
+ from {
+ protocol icmp;
+ }
+ then {
+ reject;
+ }
+ }
+ }
+ }
Summary for edge01.bjm01
------------
Succeeded: 1 (unchanged=1, changed=1)
Failed: 0
------------
Total states run: 1
Total run time: 5.752 s
Pillar example:
.. code-block:: yaml
firewall:
- block-icmp:
terms:
- first-term:
protocol:
- icmp
action: reject
State SLS example:
.. code-block:: jinja
{%- set filter_name = 'block-icmp' -%}
{%- set term_name = 'first-term' -%}
{%- set my_term_cfg = salt.netacl.get_term_pillar(filter_name, term_name) -%}
update_icmp_first_term:
netacl.term:
- filter_name: {{ filter_name }}
- filter_options:
- not-interface-specific
- term_name: {{ term_name }}
- {{ my_term_cfg | json }}
Or directly referencing the pillar keys:
.. code-block:: yaml
update_icmp_first_term:
netacl.term:
- filter_name: block-icmp
- filter_options:
- not-interface-specific
- term_name: first-term
- merge_pillar: true
.. note::
The first method allows the user to eventually apply complex manipulation
and / or retrieve the data from external services before passing the
data to the state. The second one is more straightforward, for less
complex cases when loading the data directly from the pillar is sufficient.
.. note::
When passing retrieved pillar data into the state file, it is strongly
recommended to use the json serializer explicitly (`` | json``),
instead of relying on the default Python serializer.
'''
ret = salt.utils.napalm.default_ret(name)
test = __opts__['test'] or test
if not filter_options:
filter_options = []
loaded = __salt__['netacl.load_term_config'](filter_name,
term_name,
filter_options=filter_options,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar,
revision_id=revision_id if revision_id else name,
revision_no=revision_no,
revision_date=revision_date,
revision_date_format=revision_date_format,
source_service=source_service,
destination_service=destination_service,
test=test,
commit=commit,
debug=debug,
**term_fields)
return salt.utils.napalm.loaded_ret(ret, loaded, test, debug) | python | def term(name,
filter_name,
term_name,
filter_options=None,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=False,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d',
test=False,
commit=True,
debug=False,
source_service=None,
destination_service=None,
**term_fields):
'''
Manage the configuration of a specific policy term.
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.
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``.
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: ``False``
Merge the CLI variables with the pillar. Default: ``False``.
The properties specified through the state arguments have higher priority than the pillar.
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>).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
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 'edge01.bjm01' state.sls router.acl
Output Example:
.. code-block:: text
edge01.bjm01:
----------
ID: update_icmp_first_term
Function: netacl.term
Result: None
Comment: Testing mode: Configuration discarded.
Started: 12:49:09.174179
Duration: 5751.882 ms
Changes:
----------
diff:
[edit firewall]
+ family inet {
+ /*
+ ** $Id: update_icmp_first_term $
+ ** $Date: 2017/02/30 $
+ **
+ */
+ filter block-icmp {
+ term first-term {
+ from {
+ protocol icmp;
+ }
+ then {
+ reject;
+ }
+ }
+ }
+ }
Summary for edge01.bjm01
------------
Succeeded: 1 (unchanged=1, changed=1)
Failed: 0
------------
Total states run: 1
Total run time: 5.752 s
Pillar example:
.. code-block:: yaml
firewall:
- block-icmp:
terms:
- first-term:
protocol:
- icmp
action: reject
State SLS example:
.. code-block:: jinja
{%- set filter_name = 'block-icmp' -%}
{%- set term_name = 'first-term' -%}
{%- set my_term_cfg = salt.netacl.get_term_pillar(filter_name, term_name) -%}
update_icmp_first_term:
netacl.term:
- filter_name: {{ filter_name }}
- filter_options:
- not-interface-specific
- term_name: {{ term_name }}
- {{ my_term_cfg | json }}
Or directly referencing the pillar keys:
.. code-block:: yaml
update_icmp_first_term:
netacl.term:
- filter_name: block-icmp
- filter_options:
- not-interface-specific
- term_name: first-term
- merge_pillar: true
.. note::
The first method allows the user to eventually apply complex manipulation
and / or retrieve the data from external services before passing the
data to the state. The second one is more straightforward, for less
complex cases when loading the data directly from the pillar is sufficient.
.. note::
When passing retrieved pillar data into the state file, it is strongly
recommended to use the json serializer explicitly (`` | json``),
instead of relying on the default Python serializer.
'''
ret = salt.utils.napalm.default_ret(name)
test = __opts__['test'] or test
if not filter_options:
filter_options = []
loaded = __salt__['netacl.load_term_config'](filter_name,
term_name,
filter_options=filter_options,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar,
revision_id=revision_id if revision_id else name,
revision_no=revision_no,
revision_date=revision_date,
revision_date_format=revision_date_format,
source_service=source_service,
destination_service=destination_service,
test=test,
commit=commit,
debug=debug,
**term_fields)
return salt.utils.napalm.loaded_ret(ret, loaded, test, debug) | [
"def",
"term",
"(",
"name",
",",
"filter_name",
",",
"term_name",
",",
"filter_options",
"=",
"None",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",
"=",
"None",
",",
"merge_pillar",
"=",
"False",
",",
"revision_id",
"=",
... | Manage the configuration of a specific policy term.
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.
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``.
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: ``False``
Merge the CLI variables with the pillar. Default: ``False``.
The properties specified through the state arguments have higher priority than the pillar.
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>).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
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 'edge01.bjm01' state.sls router.acl
Output Example:
.. code-block:: text
edge01.bjm01:
----------
ID: update_icmp_first_term
Function: netacl.term
Result: None
Comment: Testing mode: Configuration discarded.
Started: 12:49:09.174179
Duration: 5751.882 ms
Changes:
----------
diff:
[edit firewall]
+ family inet {
+ /*
+ ** $Id: update_icmp_first_term $
+ ** $Date: 2017/02/30 $
+ **
+ */
+ filter block-icmp {
+ term first-term {
+ from {
+ protocol icmp;
+ }
+ then {
+ reject;
+ }
+ }
+ }
+ }
Summary for edge01.bjm01
------------
Succeeded: 1 (unchanged=1, changed=1)
Failed: 0
------------
Total states run: 1
Total run time: 5.752 s
Pillar example:
.. code-block:: yaml
firewall:
- block-icmp:
terms:
- first-term:
protocol:
- icmp
action: reject
State SLS example:
.. code-block:: jinja
{%- set filter_name = 'block-icmp' -%}
{%- set term_name = 'first-term' -%}
{%- set my_term_cfg = salt.netacl.get_term_pillar(filter_name, term_name) -%}
update_icmp_first_term:
netacl.term:
- filter_name: {{ filter_name }}
- filter_options:
- not-interface-specific
- term_name: {{ term_name }}
- {{ my_term_cfg | json }}
Or directly referencing the pillar keys:
.. code-block:: yaml
update_icmp_first_term:
netacl.term:
- filter_name: block-icmp
- filter_options:
- not-interface-specific
- term_name: first-term
- merge_pillar: true
.. note::
The first method allows the user to eventually apply complex manipulation
and / or retrieve the data from external services before passing the
data to the state. The second one is more straightforward, for less
complex cases when loading the data directly from the pillar is sufficient.
.. note::
When passing retrieved pillar data into the state file, it is strongly
recommended to use the json serializer explicitly (`` | json``),
instead of relying on the default Python serializer. | [
"Manage",
"the",
"configuration",
"of",
"a",
"specific",
"policy",
"term",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/netacl.py#L89-L441 | train |
saltstack/salt | salt/states/netacl.py | filter | def filter(name, # pylint: disable=redefined-builtin
filter_name,
filter_options=None,
terms=None,
prepend=True,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=False,
only_lower_merge=False,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d',
test=False,
commit=True,
debug=False):
'''
Generate and load the configuration of a policy filter.
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
Dictionary 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: ``False``
Merge ``terms`` with the corresponding value from the pillar. Default: ``False``.
.. note::
By default this state does not merge, to avoid any unexpected behaviours.
The merge logic depends on the ``prepend`` argument.
The terms specified through the ``terms`` argument have higher priority
than the pillar.
only_lower_merge: ``False``
Specify if it should merge only the terms fields. Otherwise it will try
to merge also filters fields. Default: ``False``.
This option requires ``merge_pillar``, otherwise it is ignored.
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>).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
CLI Example:
.. code-block:: bash
salt 'edge01.flw01' state.sls router.acl test=True
Output Example:
.. code-block:: text
edge01.flw01:
----------
ID: my-filter
Function: netacl.filter
Result: None
Comment: Testing mode: Configuration discarded.
Started: 12:24:40.598232
Duration: 2437.139 ms
Changes:
----------
diff:
---
+++
@@ -1228,9 +1228,24 @@
!
+ipv4 access-list my-filter
+ 10 remark $Id: my-filter_state $
+ 20 remark $Revision: 5 $
+ 30 remark my-other-term
+ 40 permit tcp any range 5678 5680 any
+!
+!
loaded:
! $Id: my-filter_state $
! $Revision: 5 $
no ipv6 access-list my-filter
ipv6 access-list my-filter
remark $Id: my-filter_state $
remark $Revision: 5 $
remark my-other-term
permit tcp any range 5678 5680 any
exit
Summary for edge01.flw01
------------
Succeeded: 1 (unchanged=1, changed=1)
Failed: 0
------------
Total states run: 1
Total run time: 2.437 s
Pillar example:
.. code-block:: yaml
acl:
- my-filter:
options:
- inet6
terms:
- my-term:
source_port: [1234, 1235]
protocol:
- tcp
- udp
source_address: 1.2.3.4
action: reject
- my-other-term:
source_port:
- [5678, 5680]
protocol: tcp
action: accept
State SLS Example:
.. code-block:: jinja
{%- set filter_name = 'my-filter' -%}
{%- set my_filter_cfg = salt.netacl.get_filter_pillar(filter_name, pillar_key='firewall') -%}
my_first_filter_state:
netacl.filter:
- filter_name: {{ filter_name }}
- options: {{ my_filter_cfg['options'] | json }}
- terms: {{ my_filter_cfg['terms'] | json }}
- revision_date: false
- revision_no: 5
- debug: true
Or:
.. code-block:: yaml
my_first_filter_state:
netacl.filter:
- filter_name: my-filter
- merge_pillar: true
- pillar_key: firewall
- revision_date: false
- revision_no: 5
- debug: true
In the example above, as ``inet6`` has been specified in the ``filter_options``,
the configuration chunk referring to ``my-term`` has been ignored as it referred to
IPv4 only (from ``source_address`` field).
.. note::
The first method allows the user to eventually apply complex manipulation
and / or retrieve the data from external services before passing the
data to the state. The second one is more straightforward, for less
complex cases when loading the data directly from the pillar is sufficient.
.. note::
When passing retrieved pillar data into the state file, it is strongly
recommended to use the json serializer explicitly (`` | json``),
instead of relying on the default Python serializer.
'''
ret = salt.utils.napalm.default_ret(name)
test = __opts__['test'] or test
if not filter_options:
filter_options = []
if not terms:
terms = []
loaded = __salt__['netacl.load_filter_config'](filter_name,
filter_options=filter_options,
terms=terms,
prepend=prepend,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar,
only_lower_merge=only_lower_merge,
revision_id=revision_id if revision_id else name,
revision_no=revision_no,
revision_date=revision_date,
revision_date_format=revision_date_format,
test=test,
commit=commit,
debug=debug)
return salt.utils.napalm.loaded_ret(ret, loaded, test, debug) | python | def filter(name, # pylint: disable=redefined-builtin
filter_name,
filter_options=None,
terms=None,
prepend=True,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=False,
only_lower_merge=False,
revision_id=None,
revision_no=None,
revision_date=True,
revision_date_format='%Y/%m/%d',
test=False,
commit=True,
debug=False):
'''
Generate and load the configuration of a policy filter.
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
Dictionary 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: ``False``
Merge ``terms`` with the corresponding value from the pillar. Default: ``False``.
.. note::
By default this state does not merge, to avoid any unexpected behaviours.
The merge logic depends on the ``prepend`` argument.
The terms specified through the ``terms`` argument have higher priority
than the pillar.
only_lower_merge: ``False``
Specify if it should merge only the terms fields. Otherwise it will try
to merge also filters fields. Default: ``False``.
This option requires ``merge_pillar``, otherwise it is ignored.
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>).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
CLI Example:
.. code-block:: bash
salt 'edge01.flw01' state.sls router.acl test=True
Output Example:
.. code-block:: text
edge01.flw01:
----------
ID: my-filter
Function: netacl.filter
Result: None
Comment: Testing mode: Configuration discarded.
Started: 12:24:40.598232
Duration: 2437.139 ms
Changes:
----------
diff:
---
+++
@@ -1228,9 +1228,24 @@
!
+ipv4 access-list my-filter
+ 10 remark $Id: my-filter_state $
+ 20 remark $Revision: 5 $
+ 30 remark my-other-term
+ 40 permit tcp any range 5678 5680 any
+!
+!
loaded:
! $Id: my-filter_state $
! $Revision: 5 $
no ipv6 access-list my-filter
ipv6 access-list my-filter
remark $Id: my-filter_state $
remark $Revision: 5 $
remark my-other-term
permit tcp any range 5678 5680 any
exit
Summary for edge01.flw01
------------
Succeeded: 1 (unchanged=1, changed=1)
Failed: 0
------------
Total states run: 1
Total run time: 2.437 s
Pillar example:
.. code-block:: yaml
acl:
- my-filter:
options:
- inet6
terms:
- my-term:
source_port: [1234, 1235]
protocol:
- tcp
- udp
source_address: 1.2.3.4
action: reject
- my-other-term:
source_port:
- [5678, 5680]
protocol: tcp
action: accept
State SLS Example:
.. code-block:: jinja
{%- set filter_name = 'my-filter' -%}
{%- set my_filter_cfg = salt.netacl.get_filter_pillar(filter_name, pillar_key='firewall') -%}
my_first_filter_state:
netacl.filter:
- filter_name: {{ filter_name }}
- options: {{ my_filter_cfg['options'] | json }}
- terms: {{ my_filter_cfg['terms'] | json }}
- revision_date: false
- revision_no: 5
- debug: true
Or:
.. code-block:: yaml
my_first_filter_state:
netacl.filter:
- filter_name: my-filter
- merge_pillar: true
- pillar_key: firewall
- revision_date: false
- revision_no: 5
- debug: true
In the example above, as ``inet6`` has been specified in the ``filter_options``,
the configuration chunk referring to ``my-term`` has been ignored as it referred to
IPv4 only (from ``source_address`` field).
.. note::
The first method allows the user to eventually apply complex manipulation
and / or retrieve the data from external services before passing the
data to the state. The second one is more straightforward, for less
complex cases when loading the data directly from the pillar is sufficient.
.. note::
When passing retrieved pillar data into the state file, it is strongly
recommended to use the json serializer explicitly (`` | json``),
instead of relying on the default Python serializer.
'''
ret = salt.utils.napalm.default_ret(name)
test = __opts__['test'] or test
if not filter_options:
filter_options = []
if not terms:
terms = []
loaded = __salt__['netacl.load_filter_config'](filter_name,
filter_options=filter_options,
terms=terms,
prepend=prepend,
pillar_key=pillar_key,
pillarenv=pillarenv,
saltenv=saltenv,
merge_pillar=merge_pillar,
only_lower_merge=only_lower_merge,
revision_id=revision_id if revision_id else name,
revision_no=revision_no,
revision_date=revision_date,
revision_date_format=revision_date_format,
test=test,
commit=commit,
debug=debug)
return salt.utils.napalm.loaded_ret(ret, loaded, test, debug) | [
"def",
"filter",
"(",
"name",
",",
"# pylint: disable=redefined-builtin",
"filter_name",
",",
"filter_options",
"=",
"None",
",",
"terms",
"=",
"None",
",",
"prepend",
"=",
"True",
",",
"pillar_key",
"=",
"'acl'",
",",
"pillarenv",
"=",
"None",
",",
"saltenv",... | Generate and load the configuration of a policy filter.
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
Dictionary 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: ``False``
Merge ``terms`` with the corresponding value from the pillar. Default: ``False``.
.. note::
By default this state does not merge, to avoid any unexpected behaviours.
The merge logic depends on the ``prepend`` argument.
The terms specified through the ``terms`` argument have higher priority
than the pillar.
only_lower_merge: ``False``
Specify if it should merge only the terms fields. Otherwise it will try
to merge also filters fields. Default: ``False``.
This option requires ``merge_pillar``, otherwise it is ignored.
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>).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard and return the changes.
Default: ``False`` and will commit the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
CLI Example:
.. code-block:: bash
salt 'edge01.flw01' state.sls router.acl test=True
Output Example:
.. code-block:: text
edge01.flw01:
----------
ID: my-filter
Function: netacl.filter
Result: None
Comment: Testing mode: Configuration discarded.
Started: 12:24:40.598232
Duration: 2437.139 ms
Changes:
----------
diff:
---
+++
@@ -1228,9 +1228,24 @@
!
+ipv4 access-list my-filter
+ 10 remark $Id: my-filter_state $
+ 20 remark $Revision: 5 $
+ 30 remark my-other-term
+ 40 permit tcp any range 5678 5680 any
+!
+!
loaded:
! $Id: my-filter_state $
! $Revision: 5 $
no ipv6 access-list my-filter
ipv6 access-list my-filter
remark $Id: my-filter_state $
remark $Revision: 5 $
remark my-other-term
permit tcp any range 5678 5680 any
exit
Summary for edge01.flw01
------------
Succeeded: 1 (unchanged=1, changed=1)
Failed: 0
------------
Total states run: 1
Total run time: 2.437 s
Pillar example:
.. code-block:: yaml
acl:
- my-filter:
options:
- inet6
terms:
- my-term:
source_port: [1234, 1235]
protocol:
- tcp
- udp
source_address: 1.2.3.4
action: reject
- my-other-term:
source_port:
- [5678, 5680]
protocol: tcp
action: accept
State SLS Example:
.. code-block:: jinja
{%- set filter_name = 'my-filter' -%}
{%- set my_filter_cfg = salt.netacl.get_filter_pillar(filter_name, pillar_key='firewall') -%}
my_first_filter_state:
netacl.filter:
- filter_name: {{ filter_name }}
- options: {{ my_filter_cfg['options'] | json }}
- terms: {{ my_filter_cfg['terms'] | json }}
- revision_date: false
- revision_no: 5
- debug: true
Or:
.. code-block:: yaml
my_first_filter_state:
netacl.filter:
- filter_name: my-filter
- merge_pillar: true
- pillar_key: firewall
- revision_date: false
- revision_no: 5
- debug: true
In the example above, as ``inet6`` has been specified in the ``filter_options``,
the configuration chunk referring to ``my-term`` has been ignored as it referred to
IPv4 only (from ``source_address`` field).
.. note::
The first method allows the user to eventually apply complex manipulation
and / or retrieve the data from external services before passing the
data to the state. The second one is more straightforward, for less
complex cases when loading the data directly from the pillar is sufficient.
.. note::
When passing retrieved pillar data into the state file, it is strongly
recommended to use the json serializer explicitly (`` | json``),
instead of relying on the default Python serializer. | [
"Generate",
"and",
"load",
"the",
"configuration",
"of",
"a",
"policy",
"filter",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/netacl.py#L444-L672 | train |
saltstack/salt | salt/modules/keyboard.py | get_sys | def get_sys():
'''
Get current system keyboard setting
CLI Example:
.. code-block:: bash
salt '*' keyboard.get_sys
'''
cmd = ''
if salt.utils.path.which('localectl'):
cmd = 'localectl | grep Keymap | sed -e"s/: /=/" -e"s/^[ \t]*//"'
elif 'RedHat' in __grains__['os_family']:
cmd = 'grep LAYOUT /etc/sysconfig/keyboard | grep -vE "^#"'
elif 'Debian' in __grains__['os_family']:
cmd = 'grep XKBLAYOUT /etc/default/keyboard | grep -vE "^#"'
elif 'Gentoo' in __grains__['os_family']:
cmd = 'grep "^keymap" /etc/conf.d/keymaps | grep -vE "^#"'
out = __salt__['cmd.run'](cmd, python_shell=True).split('=')
ret = out[1].replace('"', '')
return ret | python | def get_sys():
'''
Get current system keyboard setting
CLI Example:
.. code-block:: bash
salt '*' keyboard.get_sys
'''
cmd = ''
if salt.utils.path.which('localectl'):
cmd = 'localectl | grep Keymap | sed -e"s/: /=/" -e"s/^[ \t]*//"'
elif 'RedHat' in __grains__['os_family']:
cmd = 'grep LAYOUT /etc/sysconfig/keyboard | grep -vE "^#"'
elif 'Debian' in __grains__['os_family']:
cmd = 'grep XKBLAYOUT /etc/default/keyboard | grep -vE "^#"'
elif 'Gentoo' in __grains__['os_family']:
cmd = 'grep "^keymap" /etc/conf.d/keymaps | grep -vE "^#"'
out = __salt__['cmd.run'](cmd, python_shell=True).split('=')
ret = out[1].replace('"', '')
return ret | [
"def",
"get_sys",
"(",
")",
":",
"cmd",
"=",
"''",
"if",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'localectl'",
")",
":",
"cmd",
"=",
"'localectl | grep Keymap | sed -e\"s/: /=/\" -e\"s/^[ \\t]*//\"'",
"elif",
"'RedHat'",
"in",
"__grains__",
"[",
... | Get current system keyboard setting
CLI Example:
.. code-block:: bash
salt '*' keyboard.get_sys | [
"Get",
"current",
"system",
"keyboard",
"setting"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keyboard.py#L28-L49 | train |
saltstack/salt | salt/modules/keyboard.py | set_sys | def set_sys(layout):
'''
Set current system keyboard setting
CLI Example:
.. code-block:: bash
salt '*' keyboard.set_sys dvorak
'''
if salt.utils.path.which('localectl'):
__salt__['cmd.run']('localectl set-keymap {0}'.format(layout))
elif 'RedHat' in __grains__['os_family']:
__salt__['file.sed']('/etc/sysconfig/keyboard',
'^LAYOUT=.*',
'LAYOUT={0}'.format(layout))
elif 'Debian' in __grains__['os_family']:
__salt__['file.sed']('/etc/default/keyboard',
'^XKBLAYOUT=.*',
'XKBLAYOUT={0}'.format(layout))
elif 'Gentoo' in __grains__['os_family']:
__salt__['file.sed']('/etc/conf.d/keymaps',
'^keymap=.*',
'keymap={0}'.format(layout))
return layout | python | def set_sys(layout):
'''
Set current system keyboard setting
CLI Example:
.. code-block:: bash
salt '*' keyboard.set_sys dvorak
'''
if salt.utils.path.which('localectl'):
__salt__['cmd.run']('localectl set-keymap {0}'.format(layout))
elif 'RedHat' in __grains__['os_family']:
__salt__['file.sed']('/etc/sysconfig/keyboard',
'^LAYOUT=.*',
'LAYOUT={0}'.format(layout))
elif 'Debian' in __grains__['os_family']:
__salt__['file.sed']('/etc/default/keyboard',
'^XKBLAYOUT=.*',
'XKBLAYOUT={0}'.format(layout))
elif 'Gentoo' in __grains__['os_family']:
__salt__['file.sed']('/etc/conf.d/keymaps',
'^keymap=.*',
'keymap={0}'.format(layout))
return layout | [
"def",
"set_sys",
"(",
"layout",
")",
":",
"if",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'localectl'",
")",
":",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'localectl set-keymap {0}'",
".",
"format",
"(",
"layout",
")",
")",
"elif",
"'RedHat... | Set current system keyboard setting
CLI Example:
.. code-block:: bash
salt '*' keyboard.set_sys dvorak | [
"Set",
"current",
"system",
"keyboard",
"setting"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keyboard.py#L52-L76 | train |
saltstack/salt | salt/modules/keyboard.py | get_x | def get_x():
'''
Get current X keyboard setting
CLI Example:
.. code-block:: bash
salt '*' keyboard.get_x
'''
cmd = 'setxkbmap -query | grep layout'
out = __salt__['cmd.run'](cmd, python_shell=True).split(':')
return out[1].strip() | python | def get_x():
'''
Get current X keyboard setting
CLI Example:
.. code-block:: bash
salt '*' keyboard.get_x
'''
cmd = 'setxkbmap -query | grep layout'
out = __salt__['cmd.run'](cmd, python_shell=True).split(':')
return out[1].strip() | [
"def",
"get_x",
"(",
")",
":",
"cmd",
"=",
"'setxkbmap -query | grep layout'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"True",
")",
".",
"split",
"(",
"':'",
")",
"return",
"out",
"[",
"1",
"]",
".",
"strip"... | Get current X keyboard setting
CLI Example:
.. code-block:: bash
salt '*' keyboard.get_x | [
"Get",
"current",
"X",
"keyboard",
"setting"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keyboard.py#L79-L91 | train |
saltstack/salt | salt/utils/pycrypto.py | secure_password | def secure_password(length=20, use_random=True):
'''
Generate a secure password.
'''
try:
length = int(length)
pw = ''
while len(pw) < length:
if HAS_RANDOM and use_random:
while True:
try:
char = salt.utils.stringutils.to_str(get_random_bytes(1))
break
except UnicodeDecodeError:
continue
pw += re.sub(
salt.utils.stringutils.to_str(r'\W'),
str(), # future lint: disable=blacklisted-function
char
)
else:
pw += random.SystemRandom().choice(string.ascii_letters + string.digits)
return pw
except Exception as exc:
log.exception('Failed to generate secure passsword')
raise CommandExecutionError(six.text_type(exc)) | python | def secure_password(length=20, use_random=True):
'''
Generate a secure password.
'''
try:
length = int(length)
pw = ''
while len(pw) < length:
if HAS_RANDOM and use_random:
while True:
try:
char = salt.utils.stringutils.to_str(get_random_bytes(1))
break
except UnicodeDecodeError:
continue
pw += re.sub(
salt.utils.stringutils.to_str(r'\W'),
str(), # future lint: disable=blacklisted-function
char
)
else:
pw += random.SystemRandom().choice(string.ascii_letters + string.digits)
return pw
except Exception as exc:
log.exception('Failed to generate secure passsword')
raise CommandExecutionError(six.text_type(exc)) | [
"def",
"secure_password",
"(",
"length",
"=",
"20",
",",
"use_random",
"=",
"True",
")",
":",
"try",
":",
"length",
"=",
"int",
"(",
"length",
")",
"pw",
"=",
"''",
"while",
"len",
"(",
"pw",
")",
"<",
"length",
":",
"if",
"HAS_RANDOM",
"and",
"use... | Generate a secure password. | [
"Generate",
"a",
"secure",
"password",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pycrypto.py#L41-L66 | train |
saltstack/salt | salt/utils/pycrypto.py | gen_hash | def gen_hash(crypt_salt=None, password=None, algorithm='sha512'):
'''
Generate /etc/shadow hash
'''
if not HAS_CRYPT:
raise SaltInvocationError('No crypt module for windows')
hash_algorithms = dict(
md5='$1$', blowfish='$2a$', sha256='$5$', sha512='$6$'
)
if algorithm not in hash_algorithms:
raise SaltInvocationError(
'Algorithm \'{0}\' is not supported'.format(algorithm)
)
if password is None:
password = secure_password()
if crypt_salt is None:
crypt_salt = secure_password(8)
crypt_salt = hash_algorithms[algorithm] + crypt_salt
return crypt.crypt(password, crypt_salt) | python | def gen_hash(crypt_salt=None, password=None, algorithm='sha512'):
'''
Generate /etc/shadow hash
'''
if not HAS_CRYPT:
raise SaltInvocationError('No crypt module for windows')
hash_algorithms = dict(
md5='$1$', blowfish='$2a$', sha256='$5$', sha512='$6$'
)
if algorithm not in hash_algorithms:
raise SaltInvocationError(
'Algorithm \'{0}\' is not supported'.format(algorithm)
)
if password is None:
password = secure_password()
if crypt_salt is None:
crypt_salt = secure_password(8)
crypt_salt = hash_algorithms[algorithm] + crypt_salt
return crypt.crypt(password, crypt_salt) | [
"def",
"gen_hash",
"(",
"crypt_salt",
"=",
"None",
",",
"password",
"=",
"None",
",",
"algorithm",
"=",
"'sha512'",
")",
":",
"if",
"not",
"HAS_CRYPT",
":",
"raise",
"SaltInvocationError",
"(",
"'No crypt module for windows'",
")",
"hash_algorithms",
"=",
"dict"... | Generate /etc/shadow hash | [
"Generate",
"/",
"etc",
"/",
"shadow",
"hash"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pycrypto.py#L69-L92 | train |
saltstack/salt | salt/executors/splay.py | _get_hash | def _get_hash():
'''
Jenkins One-At-A-Time Hash Function
More Info: http://en.wikipedia.org/wiki/Jenkins_hash_function#one-at-a-time
'''
# Using bitmask to emulate rollover behavior of C unsigned 32 bit int
bitmask = 0xffffffff
h = 0
for i in bytearray(salt.utils.stringutils.to_bytes(__grains__['id'])):
h = (h + i) & bitmask
h = (h + (h << 10)) & bitmask
h = (h ^ (h >> 6)) & bitmask
h = (h + (h << 3)) & bitmask
h = (h ^ (h >> 11)) & bitmask
h = (h + (h << 15)) & bitmask
return (h & (_HASH_SIZE - 1)) & bitmask | python | def _get_hash():
'''
Jenkins One-At-A-Time Hash Function
More Info: http://en.wikipedia.org/wiki/Jenkins_hash_function#one-at-a-time
'''
# Using bitmask to emulate rollover behavior of C unsigned 32 bit int
bitmask = 0xffffffff
h = 0
for i in bytearray(salt.utils.stringutils.to_bytes(__grains__['id'])):
h = (h + i) & bitmask
h = (h + (h << 10)) & bitmask
h = (h ^ (h >> 6)) & bitmask
h = (h + (h << 3)) & bitmask
h = (h ^ (h >> 11)) & bitmask
h = (h + (h << 15)) & bitmask
return (h & (_HASH_SIZE - 1)) & bitmask | [
"def",
"_get_hash",
"(",
")",
":",
"# Using bitmask to emulate rollover behavior of C unsigned 32 bit int",
"bitmask",
"=",
"0xffffffff",
"h",
"=",
"0",
"for",
"i",
"in",
"bytearray",
"(",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_bytes",
"(",
"__grains__",... | Jenkins One-At-A-Time Hash Function
More Info: http://en.wikipedia.org/wiki/Jenkins_hash_function#one-at-a-time | [
"Jenkins",
"One",
"-",
"At",
"-",
"A",
"-",
"Time",
"Hash",
"Function",
"More",
"Info",
":",
"http",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Jenkins_hash_function#one",
"-",
"at",
"-",
"a",
"-",
"time"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/executors/splay.py#L24-L42 | train |
saltstack/salt | salt/executors/splay.py | execute | def execute(opts, data, func, args, kwargs):
'''
Splay a salt function call execution time across minions over
a number of seconds (default: 300)
.. note::
You *probably* want to use --async here and look up the job results later.
If you're dead set on getting the output from the CLI command, then make
sure to set the timeout (with the -t flag) to something greater than the
splaytime (max splaytime + time to execute job).
Otherwise, it's very likely that the cli will time out before the job returns.
CLI Example:
.. code-block:: bash
# With default splaytime
salt --async --module-executors='[splay, direct_call]' '*' pkg.install cowsay version=3.03-8.el6
.. code-block:: bash
# With specified splaytime (5 minutes) and timeout with 10 second buffer
salt -t 310 --module-executors='[splay, direct_call]' --executor-opts='{splaytime: 300}' '*' pkg.version cowsay
'''
if 'executor_opts' in data and 'splaytime' in data['executor_opts']:
splaytime = data['executor_opts']['splaytime']
else:
splaytime = opts.get('splaytime', _DEFAULT_SPLAYTIME)
if splaytime <= 0:
raise ValueError('splaytime must be a positive integer')
fun_name = data.get('fun')
my_delay = _calc_splay(splaytime)
log.debug("Splay is sleeping %s secs on %s", my_delay, fun_name)
time.sleep(my_delay)
return None | python | def execute(opts, data, func, args, kwargs):
'''
Splay a salt function call execution time across minions over
a number of seconds (default: 300)
.. note::
You *probably* want to use --async here and look up the job results later.
If you're dead set on getting the output from the CLI command, then make
sure to set the timeout (with the -t flag) to something greater than the
splaytime (max splaytime + time to execute job).
Otherwise, it's very likely that the cli will time out before the job returns.
CLI Example:
.. code-block:: bash
# With default splaytime
salt --async --module-executors='[splay, direct_call]' '*' pkg.install cowsay version=3.03-8.el6
.. code-block:: bash
# With specified splaytime (5 minutes) and timeout with 10 second buffer
salt -t 310 --module-executors='[splay, direct_call]' --executor-opts='{splaytime: 300}' '*' pkg.version cowsay
'''
if 'executor_opts' in data and 'splaytime' in data['executor_opts']:
splaytime = data['executor_opts']['splaytime']
else:
splaytime = opts.get('splaytime', _DEFAULT_SPLAYTIME)
if splaytime <= 0:
raise ValueError('splaytime must be a positive integer')
fun_name = data.get('fun')
my_delay = _calc_splay(splaytime)
log.debug("Splay is sleeping %s secs on %s", my_delay, fun_name)
time.sleep(my_delay)
return None | [
"def",
"execute",
"(",
"opts",
",",
"data",
",",
"func",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"'executor_opts'",
"in",
"data",
"and",
"'splaytime'",
"in",
"data",
"[",
"'executor_opts'",
"]",
":",
"splaytime",
"=",
"data",
"[",
"'executor_opts'",
... | Splay a salt function call execution time across minions over
a number of seconds (default: 300)
.. note::
You *probably* want to use --async here and look up the job results later.
If you're dead set on getting the output from the CLI command, then make
sure to set the timeout (with the -t flag) to something greater than the
splaytime (max splaytime + time to execute job).
Otherwise, it's very likely that the cli will time out before the job returns.
CLI Example:
.. code-block:: bash
# With default splaytime
salt --async --module-executors='[splay, direct_call]' '*' pkg.install cowsay version=3.03-8.el6
.. code-block:: bash
# With specified splaytime (5 minutes) and timeout with 10 second buffer
salt -t 310 --module-executors='[splay, direct_call]' --executor-opts='{splaytime: 300}' '*' pkg.version cowsay | [
"Splay",
"a",
"salt",
"function",
"call",
"execution",
"time",
"across",
"minions",
"over",
"a",
"number",
"of",
"seconds",
"(",
"default",
":",
"300",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/executors/splay.py#L49-L84 | train |
saltstack/salt | salt/states/elasticsearch_index.py | absent | def absent(name):
'''
Ensure that the named index is absent.
name
Name of the index to remove
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
try:
index = __salt__['elasticsearch.index_get'](index=name)
if index and name in index:
if __opts__['test']:
ret['comment'] = 'Index {0} will be removed'.format(name)
ret['changes']['old'] = index[name]
ret['result'] = None
else:
ret['result'] = __salt__['elasticsearch.index_delete'](index=name)
if ret['result']:
ret['comment'] = 'Successfully removed index {0}'.format(name)
ret['changes']['old'] = index[name]
else:
ret['comment'] = 'Failed to remove index {0} for unknown reasons'.format(name)
else:
ret['comment'] = 'Index {0} is already absent'.format(name)
except Exception as err:
ret['result'] = False
ret['comment'] = six.text_type(err)
return ret | python | def absent(name):
'''
Ensure that the named index is absent.
name
Name of the index to remove
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
try:
index = __salt__['elasticsearch.index_get'](index=name)
if index and name in index:
if __opts__['test']:
ret['comment'] = 'Index {0} will be removed'.format(name)
ret['changes']['old'] = index[name]
ret['result'] = None
else:
ret['result'] = __salt__['elasticsearch.index_delete'](index=name)
if ret['result']:
ret['comment'] = 'Successfully removed index {0}'.format(name)
ret['changes']['old'] = index[name]
else:
ret['comment'] = 'Failed to remove index {0} for unknown reasons'.format(name)
else:
ret['comment'] = 'Index {0} is already absent'.format(name)
except Exception as err:
ret['result'] = False
ret['comment'] = six.text_type(err)
return ret | [
"def",
"absent",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"try",
":",
"index",
"=",
"__salt__",
"[",
"'elasticsearch.index_get'",
"... | Ensure that the named index is absent.
name
Name of the index to remove | [
"Ensure",
"that",
"the",
"named",
"index",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/elasticsearch_index.py#L19-L49 | train |
saltstack/salt | salt/states/elasticsearch_index.py | present | def present(name, definition=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2017.3.0
Marked ``definition`` as optional.
Ensure that the named index is present.
name
Name of the index to add
definition
Optional dict for creation parameters as per https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
**Example:**
.. code-block:: yaml
# Default settings
mytestindex:
elasticsearch_index.present
# Extra settings
mytestindex2:
elasticsearch_index.present:
- definition:
settings:
index:
number_of_shards: 10
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
try:
index_exists = __salt__['elasticsearch.index_exists'](index=name)
if not index_exists:
if __opts__['test']:
ret['comment'] = 'Index {0} does not exist and will be created'.format(name)
ret['changes'] = {'new': definition}
ret['result'] = None
else:
output = __salt__['elasticsearch.index_create'](index=name, body=definition)
if output:
ret['comment'] = 'Successfully created index {0}'.format(name)
ret['changes'] = {'new': __salt__['elasticsearch.index_get'](index=name)[name]}
else:
ret['result'] = False
ret['comment'] = 'Cannot create index {0}, {1}'.format(name, output)
else:
ret['comment'] = 'Index {0} is already present'.format(name)
except Exception as err:
ret['result'] = False
ret['comment'] = six.text_type(err)
return ret | python | def present(name, definition=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2017.3.0
Marked ``definition`` as optional.
Ensure that the named index is present.
name
Name of the index to add
definition
Optional dict for creation parameters as per https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
**Example:**
.. code-block:: yaml
# Default settings
mytestindex:
elasticsearch_index.present
# Extra settings
mytestindex2:
elasticsearch_index.present:
- definition:
settings:
index:
number_of_shards: 10
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
try:
index_exists = __salt__['elasticsearch.index_exists'](index=name)
if not index_exists:
if __opts__['test']:
ret['comment'] = 'Index {0} does not exist and will be created'.format(name)
ret['changes'] = {'new': definition}
ret['result'] = None
else:
output = __salt__['elasticsearch.index_create'](index=name, body=definition)
if output:
ret['comment'] = 'Successfully created index {0}'.format(name)
ret['changes'] = {'new': __salt__['elasticsearch.index_get'](index=name)[name]}
else:
ret['result'] = False
ret['comment'] = 'Cannot create index {0}, {1}'.format(name, output)
else:
ret['comment'] = 'Index {0} is already present'.format(name)
except Exception as err:
ret['result'] = False
ret['comment'] = six.text_type(err)
return ret | [
"def",
"present",
"(",
"name",
",",
"definition",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"try",
":",
"index_exists",
"=",
"__sa... | .. versionadded:: 2015.8.0
.. versionchanged:: 2017.3.0
Marked ``definition`` as optional.
Ensure that the named index is present.
name
Name of the index to add
definition
Optional dict for creation parameters as per https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
**Example:**
.. code-block:: yaml
# Default settings
mytestindex:
elasticsearch_index.present
# Extra settings
mytestindex2:
elasticsearch_index.present:
- definition:
settings:
index:
number_of_shards: 10 | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2017",
".",
"3",
".",
"0",
"Marked",
"definition",
"as",
"optional",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/elasticsearch_index.py#L52-L106 | train |
saltstack/salt | salt/modules/freebsdservice.py | _cmd | def _cmd(jail=None):
'''
Return full path to service command
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
'''
service = salt.utils.path.which('service')
if not service:
raise CommandNotFoundError('\'service\' command not found')
if jail:
jexec = salt.utils.path.which('jexec')
if not jexec:
raise CommandNotFoundError('\'jexec\' command not found')
service = '{0} {1} {2}'.format(jexec, jail, service)
return service | python | def _cmd(jail=None):
'''
Return full path to service command
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
'''
service = salt.utils.path.which('service')
if not service:
raise CommandNotFoundError('\'service\' command not found')
if jail:
jexec = salt.utils.path.which('jexec')
if not jexec:
raise CommandNotFoundError('\'jexec\' command not found')
service = '{0} {1} {2}'.format(jexec, jail, service)
return service | [
"def",
"_cmd",
"(",
"jail",
"=",
"None",
")",
":",
"service",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'service'",
")",
"if",
"not",
"service",
":",
"raise",
"CommandNotFoundError",
"(",
"'\\'service\\' command not found'",
")",
"if",
"j... | Return full path to service command
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs | [
"Return",
"full",
"path",
"to",
"service",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdservice.py#L46-L62 | train |
saltstack/salt | salt/modules/freebsdservice.py | _get_jail_path | def _get_jail_path(jail):
'''
.. versionadded:: 2016.3.4
Return the jail's root directory (path) as shown in jls
jail
The jid or jail name
'''
jls = salt.utils.path.which('jls')
if not jls:
raise CommandNotFoundError('\'jls\' command not found')
jails = __salt__['cmd.run_stdout']('{0} -n jid name path'.format(jls))
for j in jails.splitlines():
jid, jname, path = (x.split('=')[1].strip() for x in j.split())
if jid == jail or jname == jail:
return path.rstrip('/')
# XΧΧ, TODO, not sure how to handle nonexistent jail
return '' | python | def _get_jail_path(jail):
'''
.. versionadded:: 2016.3.4
Return the jail's root directory (path) as shown in jls
jail
The jid or jail name
'''
jls = salt.utils.path.which('jls')
if not jls:
raise CommandNotFoundError('\'jls\' command not found')
jails = __salt__['cmd.run_stdout']('{0} -n jid name path'.format(jls))
for j in jails.splitlines():
jid, jname, path = (x.split('=')[1].strip() for x in j.split())
if jid == jail or jname == jail:
return path.rstrip('/')
# XΧΧ, TODO, not sure how to handle nonexistent jail
return '' | [
"def",
"_get_jail_path",
"(",
"jail",
")",
":",
"jls",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'jls'",
")",
"if",
"not",
"jls",
":",
"raise",
"CommandNotFoundError",
"(",
"'\\'jls\\' command not found'",
")",
"jails",
"=",
"__salt__",
"... | .. versionadded:: 2016.3.4
Return the jail's root directory (path) as shown in jls
jail
The jid or jail name | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"4"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdservice.py#L65-L83 | train |
saltstack/salt | salt/modules/freebsdservice.py | _get_rcscript | def _get_rcscript(name, jail=None):
'''
Return full path to service rc script
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
'''
cmd = '{0} -r'.format(_cmd(jail))
prf = _get_jail_path(jail) if jail else ''
for line in __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines():
if line.endswith('{0}{1}'.format(os.path.sep, name)):
return os.path.join(prf, line.lstrip(os.path.sep))
return None | python | def _get_rcscript(name, jail=None):
'''
Return full path to service rc script
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
'''
cmd = '{0} -r'.format(_cmd(jail))
prf = _get_jail_path(jail) if jail else ''
for line in __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines():
if line.endswith('{0}{1}'.format(os.path.sep, name)):
return os.path.join(prf, line.lstrip(os.path.sep))
return None | [
"def",
"_get_rcscript",
"(",
"name",
",",
"jail",
"=",
"None",
")",
":",
"cmd",
"=",
"'{0} -r'",
".",
"format",
"(",
"_cmd",
"(",
"jail",
")",
")",
"prf",
"=",
"_get_jail_path",
"(",
"jail",
")",
"if",
"jail",
"else",
"''",
"for",
"line",
"in",
"__... | Return full path to service rc script
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs | [
"Return",
"full",
"path",
"to",
"service",
"rc",
"script"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdservice.py#L86-L99 | train |
saltstack/salt | salt/modules/freebsdservice.py | _get_rcvar | def _get_rcvar(name, jail=None):
'''
Return rcvar
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
'''
if not available(name, jail):
log.error('Service %s not found', name)
return False
cmd = '{0} {1} rcvar'.format(_cmd(jail), name)
for line in __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines():
if '_enable="' not in line:
continue
rcvar, _ = line.split('=', 1)
return rcvar
return None | python | def _get_rcvar(name, jail=None):
'''
Return rcvar
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
'''
if not available(name, jail):
log.error('Service %s not found', name)
return False
cmd = '{0} {1} rcvar'.format(_cmd(jail), name)
for line in __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines():
if '_enable="' not in line:
continue
rcvar, _ = line.split('=', 1)
return rcvar
return None | [
"def",
"_get_rcvar",
"(",
"name",
",",
"jail",
"=",
"None",
")",
":",
"if",
"not",
"available",
"(",
"name",
",",
"jail",
")",
":",
"log",
".",
"error",
"(",
"'Service %s not found'",
",",
"name",
")",
"return",
"False",
"cmd",
"=",
"'{0} {1} rcvar'",
... | Return rcvar
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs | [
"Return",
"rcvar"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdservice.py#L102-L122 | train |
saltstack/salt | salt/modules/freebsdservice.py | get_enabled | def get_enabled(jail=None):
'''
Return what services are set to run on boot
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
ret = []
service = _cmd(jail)
prf = _get_jail_path(jail) if jail else ''
for svc in __salt__['cmd.run']('{0} -e'.format(service)).splitlines():
ret.append(os.path.basename(svc))
# This is workaround for bin/173454 bug
for svc in get_all(jail):
if svc in ret:
continue
if not os.path.exists('{0}/etc/rc.conf.d/{1}'.format(prf, svc)):
continue
if enabled(svc, jail=jail):
ret.append(svc)
return sorted(ret) | python | def get_enabled(jail=None):
'''
Return what services are set to run on boot
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
ret = []
service = _cmd(jail)
prf = _get_jail_path(jail) if jail else ''
for svc in __salt__['cmd.run']('{0} -e'.format(service)).splitlines():
ret.append(os.path.basename(svc))
# This is workaround for bin/173454 bug
for svc in get_all(jail):
if svc in ret:
continue
if not os.path.exists('{0}/etc/rc.conf.d/{1}'.format(prf, svc)):
continue
if enabled(svc, jail=jail):
ret.append(svc)
return sorted(ret) | [
"def",
"get_enabled",
"(",
"jail",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"service",
"=",
"_cmd",
"(",
"jail",
")",
"prf",
"=",
"_get_jail_path",
"(",
"jail",
")",
"if",
"jail",
"else",
"''",
"for",
"svc",
"in",
"__salt__",
"[",
"'cmd.run'",
... | Return what services are set to run on boot
.. versionchanged:: 2016.3.4
Support for jail (representing jid or jail name) keyword argument in kwargs
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled | [
"Return",
"what",
"services",
"are",
"set",
"to",
"run",
"on",
"boot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdservice.py#L125-L154 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.