repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
sequencelengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/returners/highstate_return.py | _lookup_style | python | def _lookup_style(element, names):
'''
Lookup style by either element name or the list of classes
'''
return _STYLES.get('_'+element, '') + \
''.join([_STYLES.get(name, '') for name in names]) | Lookup style by either element name or the list of classes | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/highstate_return.py#L168-L173 | null | # -*- coding: utf-8 -*-
'''
Return the results of a highstate (or any other state function that returns
data in a compatible format) via an HTML email or HTML file.
.. versionadded:: 2017.7.0
Similar results can be achieved by using the smtp returner with a custom template,
except an attempt at writing such a template for the complex data structure
returned by highstate function had proven to be a challenge, not to mention
that the smtp module doesn't support sending HTML mail at the moment.
The main goal of this returner was to produce an easy to read email similar
to the output of highstate outputter used by the CLI.
This returner could be very useful during scheduled executions,
but could also be useful for communicating the results of a manual execution.
Returner configuration is controlled in a standard fashion either via
highstate group or an alternatively named group.
.. code-block:: bash
salt '*' state.highstate --return highstate
To use the alternative configuration, append '--return_config config-name'
.. code-block:: bash
salt '*' state.highstate --return highstate --return_config simple
Here is an example of what the configuration might look like:
.. code-block:: yaml
simple.highstate:
report_failures: True
report_changes: True
report_everything: False
failure_function: pillar.items
success_function: pillar.items
report_format: html
report_delivery: smtp
smtp_success_subject: 'success minion {id} on host {host}'
smtp_failure_subject: 'failure minion {id} on host {host}'
smtp_server: smtp.example.com
smtp_port: 25
smtp_tls: False
smtp_username: username
smtp_password: password
smtp_recipients: [email protected], [email protected]
smtp_sender: [email protected]
The *report_failures*, *report_changes*, and *report_everything* flags provide
filtering of the results. If you want an email to be sent every time, then
*report_everything* is your choice. If you want to be notified only when
changes were successfully made use *report_changes*. And *report_failures* will
generate an email if there were failures.
The configuration allows you to run a salt module function in case of
success (*success_function*) or failure (*failure_function*).
Any salt function, including ones defined in the _module folder of your salt
repo, could be used here and its output will be displayed under the 'extra'
heading of the email.
Supported values for *report_format* are html, json, and yaml. The latter two
are typically used for debugging purposes, but could be used for applying
a template at some later stage.
The values for *report_delivery* are smtp or file. In case of file delivery
the only other applicable option is *file_output*.
In case of smtp delivery, smtp_* options demonstrated by the example above
could be used to customize the email.
As you might have noticed, the success and failure subjects contain {id} and {host}
values. Any other grain name could be used. As opposed to using
{{grains['id']}}, which will be rendered by the master and contain master's
values at the time of pillar generation, these will contain minion values at
the time of execution.
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import smtplib
import cgi
from email.mime.text import MIMEText
from salt.ext.six.moves import range
from salt.ext.six.moves import StringIO
from salt.ext import six
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.yaml
import salt.returners
log = logging.getLogger(__name__)
__virtualname__ = 'highstate'
def __virtual__():
'''
Return our name
'''
return __virtualname__
def _get_options(ret):
'''
Return options
'''
attrs = {
'report_everything': 'report_everything',
'report_changes': 'report_changes',
'report_failures': 'report_failures',
'failure_function': 'failure_function',
'success_function': 'success_function',
'report_format': 'report_format',
'report_delivery': 'report_delivery',
'file_output': 'file_output',
'smtp_sender': 'smtp_sender',
'smtp_recipients': 'smtp_recipients',
'smtp_failure_subject': 'smtp_failure_subject',
'smtp_success_subject': 'smtp_success_subject',
'smtp_server': 'smtp_server',
'smtp_port': 'smtp_port',
'smtp_tls': 'smtp_tls',
'smtp_username': 'smtp_username',
'smtp_password': 'smtp_password'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
#
# Most email readers to not support <style> tag.
# The following dict and a function provide a primitive styler
# sufficient for our needs.
#
_STYLES = {
'_table': 'border-collapse:collapse;width:100%;',
'_td': 'vertical-align:top;'
'font-family:Helvetica,Arial,sans-serif;font-size:9pt;',
'unchanged': 'color:blue;',
'changed': 'color:green',
'failed': 'color:red;',
'first': 'border-top:0;border-left:1px solid #9e9e9e;',
'first_first': 'border-top:0;border-left:0;',
'notfirst_first': 'border-left:0;border-top:1px solid #9e9e9e;',
'other': 'border-top:1px solid #9e9e9e;border-left:1px solid #9e9e9e;',
'name': 'width:70pt;',
'container': 'padding:0;'
}
def _generate_html_table(data, out, level=0, extra_style=''):
'''
Generate a single table of data
'''
print('<table style="{0}">'.format(
_lookup_style('table', ['table' + six.text_type(level)])), file=out)
firstone = True
row_style = 'row' + six.text_type(level)
cell_style = 'cell' + six.text_type(level)
for subdata in data:
first_style = 'first_first' if firstone else 'notfirst_first'
second_style = 'first' if firstone else 'other'
if isinstance(subdata, dict):
if '__style__' in subdata:
new_extra_style = subdata['__style__']
del subdata['__style__']
else:
new_extra_style = extra_style
if len(subdata) == 1:
name, value = next(six.iteritems(subdata))
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'name', new_extra_style]
),
name
), file=out)
if isinstance(value, list):
print('<td style="{0}">'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'container',
new_extra_style
]
)
), file=out)
_generate_html_table(
value,
out,
level + 1,
new_extra_style
)
print('</td>', file=out)
else:
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'value',
new_extra_style
]
),
cgi.escape(six.text_type(value))
), file=out)
print('</tr>', file=out)
elif isinstance(subdata, list):
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">'.format(
_lookup_style(
'td',
[cell_style, first_style, 'container', extra_style]
)
), file=out)
_generate_html_table(subdata, out, level + 1, extra_style)
print('</td>', file=out)
print('</tr>', file=out)
else:
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'value', extra_style]
),
cgi.escape(six.text_type(subdata))
), file=out)
print('</tr>', file=out)
firstone = False
print('</table>', file=out)
def _generate_html(data, out):
'''
Generate report data as HTML
'''
print('<html>', file=out)
print('<body>', file=out)
_generate_html_table(data, out, 0)
print('</body>', file=out)
print('</html>', file=out)
def _dict_to_name_value(data):
'''
Convert a dictionary to a list of dictionaries to facilitate ordering
'''
if isinstance(data, dict):
sorted_data = sorted(data.items(), key=lambda s: s[0])
result = []
for name, value in sorted_data:
if isinstance(value, dict):
result.append({name: _dict_to_name_value(value)})
else:
result.append({name: value})
else:
result = data
return result
def _generate_states_report(sorted_data):
'''
Generate states report
'''
states = []
for state, data in sorted_data:
module, stateid, name, function = state.split('_|-')
module_function = '.'.join((module, function))
result = data.get('result', '')
single = [
{'function': module_function},
{'name': name},
{'result': result},
{'duration': data.get('duration', 0.0)},
{'comment': data.get('comment', '')}
]
if not result:
style = 'failed'
else:
changes = data.get('changes', {})
if changes and isinstance(changes, dict):
single.append({'changes': _dict_to_name_value(changes)})
style = 'changed'
else:
style = 'unchanged'
started = data.get('start_time', '')
if started:
single.append({'started': started})
states.append({stateid: single, '__style__': style})
return states
def _generate_report(ret, setup):
'''
Generate report dictionary
'''
retdata = ret.get('return', {})
sorted_data = sorted(
retdata.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
# gather stats
for _, data in sorted_data:
if not data.get('result', True):
failed += 1
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
if data.get('changes', {}):
changed += 1
unchanged = total - failed - changed
log.debug('highstate total: %s', total)
log.debug('highstate failed: %s', failed)
log.debug('highstate unchanged: %s', unchanged)
log.debug('highstate changed: %s', changed)
# generate report if required
if setup.get('report_everything', False) or \
(setup.get('report_changes', True) and changed != 0) or \
(setup.get('report_failures', True) and failed != 0):
report = [
{'stats': [
{'total': total},
{'failed': failed, '__style__': 'failed'},
{'unchanged': unchanged, '__style__': 'unchanged'},
{'changed': changed, '__style__': 'changed'},
{'duration': duration}
]},
{'job': [
{'function': ret.get('fun', '')},
{'arguments': ret.get('fun_args', '')},
{'jid': ret.get('jid', '')},
{'success': ret.get('success', True)},
{'retcode': ret.get('retcode', 0)}
]},
{'states': _generate_states_report(sorted_data)}
]
if failed:
function = setup.get('failure_function', None)
else:
function = setup.get('success_function', None)
if function:
func_result = __salt__[function]()
report.insert(
0,
{'extra': [{function: _dict_to_name_value(func_result)}]}
)
else:
report = []
return report, failed
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def _produce_output(report, failed, setup):
'''
Produce output from the report dictionary generated by _generate_report
'''
report_format = setup.get('report_format', 'yaml')
log.debug('highstate output format: %s', report_format)
if report_format == 'json':
report_text = salt.utils.json.dumps(report)
elif report_format == 'yaml':
string_file = StringIO()
salt.utils.yaml.safe_dump(report, string_file, default_flow_style=False)
string_file.seek(0)
report_text = string_file.read()
else:
string_file = StringIO()
_generate_html(report, string_file)
string_file.seek(0)
report_text = string_file.read()
report_delivery = setup.get('report_delivery', 'file')
log.debug('highstate report_delivery: %s', report_delivery)
if report_delivery == 'file':
output_file = _sprinkle(setup.get('file_output', '/tmp/test.rpt'))
with salt.utils.files.fopen(output_file, 'w') as out:
out.write(salt.utils.stringutils.to_str(report_text))
else:
msg = MIMEText(report_text, report_format)
sender = setup.get('smtp_sender', '')
recipients = setup.get('smtp_recipients', '')
host = setup.get('smtp_server', '')
port = int(setup.get('smtp_port', 25))
tls = setup.get('smtp_tls')
username = setup.get('smtp_username')
password = setup.get('smtp_password')
if failed:
subject = setup.get('smtp_failure_subject', 'Installation failure')
else:
subject = setup.get('smtp_success_subject', 'Installation success')
subject = _sprinkle(subject)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
log.debug('highstate smtp port: %d', port)
smtp = smtplib.SMTP(host=host, port=port)
if tls is True:
smtp.starttls()
log.debug('highstate smtp tls enabled')
if username and password:
smtp.login(username, password)
log.debug('highstate smtp authenticated')
smtp.sendmail(
sender,
[x.strip() for x in recipients.split(',')], msg.as_string())
log.debug('highstate message sent.')
smtp.quit()
def returner(ret):
'''
Check highstate return information and possibly fire off an email
or save a file.
'''
setup = _get_options(ret)
log.debug('highstate setup %s', setup)
report, failed = _generate_report(ret, setup)
if report:
_produce_output(report, failed, setup)
def __test_html():
'''
HTML generation test only used when called from the command line:
python ./highstate.py
Typical options for generating the report file:
highstate:
report_format: yaml
report_delivery: file
file_output: '/srv/salt/_returners/test.rpt'
'''
with salt.utils.files.fopen('test.rpt', 'r') as input_file:
data_text = salt.utils.stringutils.to_unicode(input_file.read())
data = salt.utils.yaml.safe_load(data_text)
string_file = StringIO()
_generate_html(data, string_file)
string_file.seek(0)
result = string_file.read()
with salt.utils.files.fopen('test.html', 'w') as output:
output.write(salt.utils.stringutils.to_str(result))
if __name__ == '__main__':
__test_html()
|
saltstack/salt | salt/returners/highstate_return.py | _generate_html_table | python | def _generate_html_table(data, out, level=0, extra_style=''):
'''
Generate a single table of data
'''
print('<table style="{0}">'.format(
_lookup_style('table', ['table' + six.text_type(level)])), file=out)
firstone = True
row_style = 'row' + six.text_type(level)
cell_style = 'cell' + six.text_type(level)
for subdata in data:
first_style = 'first_first' if firstone else 'notfirst_first'
second_style = 'first' if firstone else 'other'
if isinstance(subdata, dict):
if '__style__' in subdata:
new_extra_style = subdata['__style__']
del subdata['__style__']
else:
new_extra_style = extra_style
if len(subdata) == 1:
name, value = next(six.iteritems(subdata))
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'name', new_extra_style]
),
name
), file=out)
if isinstance(value, list):
print('<td style="{0}">'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'container',
new_extra_style
]
)
), file=out)
_generate_html_table(
value,
out,
level + 1,
new_extra_style
)
print('</td>', file=out)
else:
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'value',
new_extra_style
]
),
cgi.escape(six.text_type(value))
), file=out)
print('</tr>', file=out)
elif isinstance(subdata, list):
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">'.format(
_lookup_style(
'td',
[cell_style, first_style, 'container', extra_style]
)
), file=out)
_generate_html_table(subdata, out, level + 1, extra_style)
print('</td>', file=out)
print('</tr>', file=out)
else:
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'value', extra_style]
),
cgi.escape(six.text_type(subdata))
), file=out)
print('</tr>', file=out)
firstone = False
print('</table>', file=out) | Generate a single table of data | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/highstate_return.py#L176-L269 | null | # -*- coding: utf-8 -*-
'''
Return the results of a highstate (or any other state function that returns
data in a compatible format) via an HTML email or HTML file.
.. versionadded:: 2017.7.0
Similar results can be achieved by using the smtp returner with a custom template,
except an attempt at writing such a template for the complex data structure
returned by highstate function had proven to be a challenge, not to mention
that the smtp module doesn't support sending HTML mail at the moment.
The main goal of this returner was to produce an easy to read email similar
to the output of highstate outputter used by the CLI.
This returner could be very useful during scheduled executions,
but could also be useful for communicating the results of a manual execution.
Returner configuration is controlled in a standard fashion either via
highstate group or an alternatively named group.
.. code-block:: bash
salt '*' state.highstate --return highstate
To use the alternative configuration, append '--return_config config-name'
.. code-block:: bash
salt '*' state.highstate --return highstate --return_config simple
Here is an example of what the configuration might look like:
.. code-block:: yaml
simple.highstate:
report_failures: True
report_changes: True
report_everything: False
failure_function: pillar.items
success_function: pillar.items
report_format: html
report_delivery: smtp
smtp_success_subject: 'success minion {id} on host {host}'
smtp_failure_subject: 'failure minion {id} on host {host}'
smtp_server: smtp.example.com
smtp_port: 25
smtp_tls: False
smtp_username: username
smtp_password: password
smtp_recipients: [email protected], [email protected]
smtp_sender: [email protected]
The *report_failures*, *report_changes*, and *report_everything* flags provide
filtering of the results. If you want an email to be sent every time, then
*report_everything* is your choice. If you want to be notified only when
changes were successfully made use *report_changes*. And *report_failures* will
generate an email if there were failures.
The configuration allows you to run a salt module function in case of
success (*success_function*) or failure (*failure_function*).
Any salt function, including ones defined in the _module folder of your salt
repo, could be used here and its output will be displayed under the 'extra'
heading of the email.
Supported values for *report_format* are html, json, and yaml. The latter two
are typically used for debugging purposes, but could be used for applying
a template at some later stage.
The values for *report_delivery* are smtp or file. In case of file delivery
the only other applicable option is *file_output*.
In case of smtp delivery, smtp_* options demonstrated by the example above
could be used to customize the email.
As you might have noticed, the success and failure subjects contain {id} and {host}
values. Any other grain name could be used. As opposed to using
{{grains['id']}}, which will be rendered by the master and contain master's
values at the time of pillar generation, these will contain minion values at
the time of execution.
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import smtplib
import cgi
from email.mime.text import MIMEText
from salt.ext.six.moves import range
from salt.ext.six.moves import StringIO
from salt.ext import six
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.yaml
import salt.returners
log = logging.getLogger(__name__)
__virtualname__ = 'highstate'
def __virtual__():
'''
Return our name
'''
return __virtualname__
def _get_options(ret):
'''
Return options
'''
attrs = {
'report_everything': 'report_everything',
'report_changes': 'report_changes',
'report_failures': 'report_failures',
'failure_function': 'failure_function',
'success_function': 'success_function',
'report_format': 'report_format',
'report_delivery': 'report_delivery',
'file_output': 'file_output',
'smtp_sender': 'smtp_sender',
'smtp_recipients': 'smtp_recipients',
'smtp_failure_subject': 'smtp_failure_subject',
'smtp_success_subject': 'smtp_success_subject',
'smtp_server': 'smtp_server',
'smtp_port': 'smtp_port',
'smtp_tls': 'smtp_tls',
'smtp_username': 'smtp_username',
'smtp_password': 'smtp_password'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
#
# Most email readers to not support <style> tag.
# The following dict and a function provide a primitive styler
# sufficient for our needs.
#
_STYLES = {
'_table': 'border-collapse:collapse;width:100%;',
'_td': 'vertical-align:top;'
'font-family:Helvetica,Arial,sans-serif;font-size:9pt;',
'unchanged': 'color:blue;',
'changed': 'color:green',
'failed': 'color:red;',
'first': 'border-top:0;border-left:1px solid #9e9e9e;',
'first_first': 'border-top:0;border-left:0;',
'notfirst_first': 'border-left:0;border-top:1px solid #9e9e9e;',
'other': 'border-top:1px solid #9e9e9e;border-left:1px solid #9e9e9e;',
'name': 'width:70pt;',
'container': 'padding:0;'
}
def _lookup_style(element, names):
'''
Lookup style by either element name or the list of classes
'''
return _STYLES.get('_'+element, '') + \
''.join([_STYLES.get(name, '') for name in names])
def _generate_html(data, out):
'''
Generate report data as HTML
'''
print('<html>', file=out)
print('<body>', file=out)
_generate_html_table(data, out, 0)
print('</body>', file=out)
print('</html>', file=out)
def _dict_to_name_value(data):
'''
Convert a dictionary to a list of dictionaries to facilitate ordering
'''
if isinstance(data, dict):
sorted_data = sorted(data.items(), key=lambda s: s[0])
result = []
for name, value in sorted_data:
if isinstance(value, dict):
result.append({name: _dict_to_name_value(value)})
else:
result.append({name: value})
else:
result = data
return result
def _generate_states_report(sorted_data):
'''
Generate states report
'''
states = []
for state, data in sorted_data:
module, stateid, name, function = state.split('_|-')
module_function = '.'.join((module, function))
result = data.get('result', '')
single = [
{'function': module_function},
{'name': name},
{'result': result},
{'duration': data.get('duration', 0.0)},
{'comment': data.get('comment', '')}
]
if not result:
style = 'failed'
else:
changes = data.get('changes', {})
if changes and isinstance(changes, dict):
single.append({'changes': _dict_to_name_value(changes)})
style = 'changed'
else:
style = 'unchanged'
started = data.get('start_time', '')
if started:
single.append({'started': started})
states.append({stateid: single, '__style__': style})
return states
def _generate_report(ret, setup):
'''
Generate report dictionary
'''
retdata = ret.get('return', {})
sorted_data = sorted(
retdata.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
# gather stats
for _, data in sorted_data:
if not data.get('result', True):
failed += 1
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
if data.get('changes', {}):
changed += 1
unchanged = total - failed - changed
log.debug('highstate total: %s', total)
log.debug('highstate failed: %s', failed)
log.debug('highstate unchanged: %s', unchanged)
log.debug('highstate changed: %s', changed)
# generate report if required
if setup.get('report_everything', False) or \
(setup.get('report_changes', True) and changed != 0) or \
(setup.get('report_failures', True) and failed != 0):
report = [
{'stats': [
{'total': total},
{'failed': failed, '__style__': 'failed'},
{'unchanged': unchanged, '__style__': 'unchanged'},
{'changed': changed, '__style__': 'changed'},
{'duration': duration}
]},
{'job': [
{'function': ret.get('fun', '')},
{'arguments': ret.get('fun_args', '')},
{'jid': ret.get('jid', '')},
{'success': ret.get('success', True)},
{'retcode': ret.get('retcode', 0)}
]},
{'states': _generate_states_report(sorted_data)}
]
if failed:
function = setup.get('failure_function', None)
else:
function = setup.get('success_function', None)
if function:
func_result = __salt__[function]()
report.insert(
0,
{'extra': [{function: _dict_to_name_value(func_result)}]}
)
else:
report = []
return report, failed
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def _produce_output(report, failed, setup):
'''
Produce output from the report dictionary generated by _generate_report
'''
report_format = setup.get('report_format', 'yaml')
log.debug('highstate output format: %s', report_format)
if report_format == 'json':
report_text = salt.utils.json.dumps(report)
elif report_format == 'yaml':
string_file = StringIO()
salt.utils.yaml.safe_dump(report, string_file, default_flow_style=False)
string_file.seek(0)
report_text = string_file.read()
else:
string_file = StringIO()
_generate_html(report, string_file)
string_file.seek(0)
report_text = string_file.read()
report_delivery = setup.get('report_delivery', 'file')
log.debug('highstate report_delivery: %s', report_delivery)
if report_delivery == 'file':
output_file = _sprinkle(setup.get('file_output', '/tmp/test.rpt'))
with salt.utils.files.fopen(output_file, 'w') as out:
out.write(salt.utils.stringutils.to_str(report_text))
else:
msg = MIMEText(report_text, report_format)
sender = setup.get('smtp_sender', '')
recipients = setup.get('smtp_recipients', '')
host = setup.get('smtp_server', '')
port = int(setup.get('smtp_port', 25))
tls = setup.get('smtp_tls')
username = setup.get('smtp_username')
password = setup.get('smtp_password')
if failed:
subject = setup.get('smtp_failure_subject', 'Installation failure')
else:
subject = setup.get('smtp_success_subject', 'Installation success')
subject = _sprinkle(subject)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
log.debug('highstate smtp port: %d', port)
smtp = smtplib.SMTP(host=host, port=port)
if tls is True:
smtp.starttls()
log.debug('highstate smtp tls enabled')
if username and password:
smtp.login(username, password)
log.debug('highstate smtp authenticated')
smtp.sendmail(
sender,
[x.strip() for x in recipients.split(',')], msg.as_string())
log.debug('highstate message sent.')
smtp.quit()
def returner(ret):
'''
Check highstate return information and possibly fire off an email
or save a file.
'''
setup = _get_options(ret)
log.debug('highstate setup %s', setup)
report, failed = _generate_report(ret, setup)
if report:
_produce_output(report, failed, setup)
def __test_html():
'''
HTML generation test only used when called from the command line:
python ./highstate.py
Typical options for generating the report file:
highstate:
report_format: yaml
report_delivery: file
file_output: '/srv/salt/_returners/test.rpt'
'''
with salt.utils.files.fopen('test.rpt', 'r') as input_file:
data_text = salt.utils.stringutils.to_unicode(input_file.read())
data = salt.utils.yaml.safe_load(data_text)
string_file = StringIO()
_generate_html(data, string_file)
string_file.seek(0)
result = string_file.read()
with salt.utils.files.fopen('test.html', 'w') as output:
output.write(salt.utils.stringutils.to_str(result))
if __name__ == '__main__':
__test_html()
|
saltstack/salt | salt/returners/highstate_return.py | _generate_html | python | def _generate_html(data, out):
'''
Generate report data as HTML
'''
print('<html>', file=out)
print('<body>', file=out)
_generate_html_table(data, out, 0)
print('</body>', file=out)
print('</html>', file=out) | Generate report data as HTML | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/highstate_return.py#L272-L280 | null | # -*- coding: utf-8 -*-
'''
Return the results of a highstate (or any other state function that returns
data in a compatible format) via an HTML email or HTML file.
.. versionadded:: 2017.7.0
Similar results can be achieved by using the smtp returner with a custom template,
except an attempt at writing such a template for the complex data structure
returned by highstate function had proven to be a challenge, not to mention
that the smtp module doesn't support sending HTML mail at the moment.
The main goal of this returner was to produce an easy to read email similar
to the output of highstate outputter used by the CLI.
This returner could be very useful during scheduled executions,
but could also be useful for communicating the results of a manual execution.
Returner configuration is controlled in a standard fashion either via
highstate group or an alternatively named group.
.. code-block:: bash
salt '*' state.highstate --return highstate
To use the alternative configuration, append '--return_config config-name'
.. code-block:: bash
salt '*' state.highstate --return highstate --return_config simple
Here is an example of what the configuration might look like:
.. code-block:: yaml
simple.highstate:
report_failures: True
report_changes: True
report_everything: False
failure_function: pillar.items
success_function: pillar.items
report_format: html
report_delivery: smtp
smtp_success_subject: 'success minion {id} on host {host}'
smtp_failure_subject: 'failure minion {id} on host {host}'
smtp_server: smtp.example.com
smtp_port: 25
smtp_tls: False
smtp_username: username
smtp_password: password
smtp_recipients: [email protected], [email protected]
smtp_sender: [email protected]
The *report_failures*, *report_changes*, and *report_everything* flags provide
filtering of the results. If you want an email to be sent every time, then
*report_everything* is your choice. If you want to be notified only when
changes were successfully made use *report_changes*. And *report_failures* will
generate an email if there were failures.
The configuration allows you to run a salt module function in case of
success (*success_function*) or failure (*failure_function*).
Any salt function, including ones defined in the _module folder of your salt
repo, could be used here and its output will be displayed under the 'extra'
heading of the email.
Supported values for *report_format* are html, json, and yaml. The latter two
are typically used for debugging purposes, but could be used for applying
a template at some later stage.
The values for *report_delivery* are smtp or file. In case of file delivery
the only other applicable option is *file_output*.
In case of smtp delivery, smtp_* options demonstrated by the example above
could be used to customize the email.
As you might have noticed, the success and failure subjects contain {id} and {host}
values. Any other grain name could be used. As opposed to using
{{grains['id']}}, which will be rendered by the master and contain master's
values at the time of pillar generation, these will contain minion values at
the time of execution.
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import smtplib
import cgi
from email.mime.text import MIMEText
from salt.ext.six.moves import range
from salt.ext.six.moves import StringIO
from salt.ext import six
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.yaml
import salt.returners
log = logging.getLogger(__name__)
__virtualname__ = 'highstate'
def __virtual__():
'''
Return our name
'''
return __virtualname__
def _get_options(ret):
'''
Return options
'''
attrs = {
'report_everything': 'report_everything',
'report_changes': 'report_changes',
'report_failures': 'report_failures',
'failure_function': 'failure_function',
'success_function': 'success_function',
'report_format': 'report_format',
'report_delivery': 'report_delivery',
'file_output': 'file_output',
'smtp_sender': 'smtp_sender',
'smtp_recipients': 'smtp_recipients',
'smtp_failure_subject': 'smtp_failure_subject',
'smtp_success_subject': 'smtp_success_subject',
'smtp_server': 'smtp_server',
'smtp_port': 'smtp_port',
'smtp_tls': 'smtp_tls',
'smtp_username': 'smtp_username',
'smtp_password': 'smtp_password'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
#
# Most email readers to not support <style> tag.
# The following dict and a function provide a primitive styler
# sufficient for our needs.
#
_STYLES = {
'_table': 'border-collapse:collapse;width:100%;',
'_td': 'vertical-align:top;'
'font-family:Helvetica,Arial,sans-serif;font-size:9pt;',
'unchanged': 'color:blue;',
'changed': 'color:green',
'failed': 'color:red;',
'first': 'border-top:0;border-left:1px solid #9e9e9e;',
'first_first': 'border-top:0;border-left:0;',
'notfirst_first': 'border-left:0;border-top:1px solid #9e9e9e;',
'other': 'border-top:1px solid #9e9e9e;border-left:1px solid #9e9e9e;',
'name': 'width:70pt;',
'container': 'padding:0;'
}
def _lookup_style(element, names):
'''
Lookup style by either element name or the list of classes
'''
return _STYLES.get('_'+element, '') + \
''.join([_STYLES.get(name, '') for name in names])
def _generate_html_table(data, out, level=0, extra_style=''):
'''
Generate a single table of data
'''
print('<table style="{0}">'.format(
_lookup_style('table', ['table' + six.text_type(level)])), file=out)
firstone = True
row_style = 'row' + six.text_type(level)
cell_style = 'cell' + six.text_type(level)
for subdata in data:
first_style = 'first_first' if firstone else 'notfirst_first'
second_style = 'first' if firstone else 'other'
if isinstance(subdata, dict):
if '__style__' in subdata:
new_extra_style = subdata['__style__']
del subdata['__style__']
else:
new_extra_style = extra_style
if len(subdata) == 1:
name, value = next(six.iteritems(subdata))
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'name', new_extra_style]
),
name
), file=out)
if isinstance(value, list):
print('<td style="{0}">'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'container',
new_extra_style
]
)
), file=out)
_generate_html_table(
value,
out,
level + 1,
new_extra_style
)
print('</td>', file=out)
else:
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'value',
new_extra_style
]
),
cgi.escape(six.text_type(value))
), file=out)
print('</tr>', file=out)
elif isinstance(subdata, list):
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">'.format(
_lookup_style(
'td',
[cell_style, first_style, 'container', extra_style]
)
), file=out)
_generate_html_table(subdata, out, level + 1, extra_style)
print('</td>', file=out)
print('</tr>', file=out)
else:
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'value', extra_style]
),
cgi.escape(six.text_type(subdata))
), file=out)
print('</tr>', file=out)
firstone = False
print('</table>', file=out)
def _dict_to_name_value(data):
'''
Convert a dictionary to a list of dictionaries to facilitate ordering
'''
if isinstance(data, dict):
sorted_data = sorted(data.items(), key=lambda s: s[0])
result = []
for name, value in sorted_data:
if isinstance(value, dict):
result.append({name: _dict_to_name_value(value)})
else:
result.append({name: value})
else:
result = data
return result
def _generate_states_report(sorted_data):
'''
Generate states report
'''
states = []
for state, data in sorted_data:
module, stateid, name, function = state.split('_|-')
module_function = '.'.join((module, function))
result = data.get('result', '')
single = [
{'function': module_function},
{'name': name},
{'result': result},
{'duration': data.get('duration', 0.0)},
{'comment': data.get('comment', '')}
]
if not result:
style = 'failed'
else:
changes = data.get('changes', {})
if changes and isinstance(changes, dict):
single.append({'changes': _dict_to_name_value(changes)})
style = 'changed'
else:
style = 'unchanged'
started = data.get('start_time', '')
if started:
single.append({'started': started})
states.append({stateid: single, '__style__': style})
return states
def _generate_report(ret, setup):
'''
Generate report dictionary
'''
retdata = ret.get('return', {})
sorted_data = sorted(
retdata.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
# gather stats
for _, data in sorted_data:
if not data.get('result', True):
failed += 1
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
if data.get('changes', {}):
changed += 1
unchanged = total - failed - changed
log.debug('highstate total: %s', total)
log.debug('highstate failed: %s', failed)
log.debug('highstate unchanged: %s', unchanged)
log.debug('highstate changed: %s', changed)
# generate report if required
if setup.get('report_everything', False) or \
(setup.get('report_changes', True) and changed != 0) or \
(setup.get('report_failures', True) and failed != 0):
report = [
{'stats': [
{'total': total},
{'failed': failed, '__style__': 'failed'},
{'unchanged': unchanged, '__style__': 'unchanged'},
{'changed': changed, '__style__': 'changed'},
{'duration': duration}
]},
{'job': [
{'function': ret.get('fun', '')},
{'arguments': ret.get('fun_args', '')},
{'jid': ret.get('jid', '')},
{'success': ret.get('success', True)},
{'retcode': ret.get('retcode', 0)}
]},
{'states': _generate_states_report(sorted_data)}
]
if failed:
function = setup.get('failure_function', None)
else:
function = setup.get('success_function', None)
if function:
func_result = __salt__[function]()
report.insert(
0,
{'extra': [{function: _dict_to_name_value(func_result)}]}
)
else:
report = []
return report, failed
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def _produce_output(report, failed, setup):
'''
Produce output from the report dictionary generated by _generate_report
'''
report_format = setup.get('report_format', 'yaml')
log.debug('highstate output format: %s', report_format)
if report_format == 'json':
report_text = salt.utils.json.dumps(report)
elif report_format == 'yaml':
string_file = StringIO()
salt.utils.yaml.safe_dump(report, string_file, default_flow_style=False)
string_file.seek(0)
report_text = string_file.read()
else:
string_file = StringIO()
_generate_html(report, string_file)
string_file.seek(0)
report_text = string_file.read()
report_delivery = setup.get('report_delivery', 'file')
log.debug('highstate report_delivery: %s', report_delivery)
if report_delivery == 'file':
output_file = _sprinkle(setup.get('file_output', '/tmp/test.rpt'))
with salt.utils.files.fopen(output_file, 'w') as out:
out.write(salt.utils.stringutils.to_str(report_text))
else:
msg = MIMEText(report_text, report_format)
sender = setup.get('smtp_sender', '')
recipients = setup.get('smtp_recipients', '')
host = setup.get('smtp_server', '')
port = int(setup.get('smtp_port', 25))
tls = setup.get('smtp_tls')
username = setup.get('smtp_username')
password = setup.get('smtp_password')
if failed:
subject = setup.get('smtp_failure_subject', 'Installation failure')
else:
subject = setup.get('smtp_success_subject', 'Installation success')
subject = _sprinkle(subject)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
log.debug('highstate smtp port: %d', port)
smtp = smtplib.SMTP(host=host, port=port)
if tls is True:
smtp.starttls()
log.debug('highstate smtp tls enabled')
if username and password:
smtp.login(username, password)
log.debug('highstate smtp authenticated')
smtp.sendmail(
sender,
[x.strip() for x in recipients.split(',')], msg.as_string())
log.debug('highstate message sent.')
smtp.quit()
def returner(ret):
'''
Check highstate return information and possibly fire off an email
or save a file.
'''
setup = _get_options(ret)
log.debug('highstate setup %s', setup)
report, failed = _generate_report(ret, setup)
if report:
_produce_output(report, failed, setup)
def __test_html():
'''
HTML generation test only used when called from the command line:
python ./highstate.py
Typical options for generating the report file:
highstate:
report_format: yaml
report_delivery: file
file_output: '/srv/salt/_returners/test.rpt'
'''
with salt.utils.files.fopen('test.rpt', 'r') as input_file:
data_text = salt.utils.stringutils.to_unicode(input_file.read())
data = salt.utils.yaml.safe_load(data_text)
string_file = StringIO()
_generate_html(data, string_file)
string_file.seek(0)
result = string_file.read()
with salt.utils.files.fopen('test.html', 'w') as output:
output.write(salt.utils.stringutils.to_str(result))
if __name__ == '__main__':
__test_html()
|
saltstack/salt | salt/returners/highstate_return.py | _dict_to_name_value | python | def _dict_to_name_value(data):
'''
Convert a dictionary to a list of dictionaries to facilitate ordering
'''
if isinstance(data, dict):
sorted_data = sorted(data.items(), key=lambda s: s[0])
result = []
for name, value in sorted_data:
if isinstance(value, dict):
result.append({name: _dict_to_name_value(value)})
else:
result.append({name: value})
else:
result = data
return result | Convert a dictionary to a list of dictionaries to facilitate ordering | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/highstate_return.py#L283-L297 | null | # -*- coding: utf-8 -*-
'''
Return the results of a highstate (or any other state function that returns
data in a compatible format) via an HTML email or HTML file.
.. versionadded:: 2017.7.0
Similar results can be achieved by using the smtp returner with a custom template,
except an attempt at writing such a template for the complex data structure
returned by highstate function had proven to be a challenge, not to mention
that the smtp module doesn't support sending HTML mail at the moment.
The main goal of this returner was to produce an easy to read email similar
to the output of highstate outputter used by the CLI.
This returner could be very useful during scheduled executions,
but could also be useful for communicating the results of a manual execution.
Returner configuration is controlled in a standard fashion either via
highstate group or an alternatively named group.
.. code-block:: bash
salt '*' state.highstate --return highstate
To use the alternative configuration, append '--return_config config-name'
.. code-block:: bash
salt '*' state.highstate --return highstate --return_config simple
Here is an example of what the configuration might look like:
.. code-block:: yaml
simple.highstate:
report_failures: True
report_changes: True
report_everything: False
failure_function: pillar.items
success_function: pillar.items
report_format: html
report_delivery: smtp
smtp_success_subject: 'success minion {id} on host {host}'
smtp_failure_subject: 'failure minion {id} on host {host}'
smtp_server: smtp.example.com
smtp_port: 25
smtp_tls: False
smtp_username: username
smtp_password: password
smtp_recipients: [email protected], [email protected]
smtp_sender: [email protected]
The *report_failures*, *report_changes*, and *report_everything* flags provide
filtering of the results. If you want an email to be sent every time, then
*report_everything* is your choice. If you want to be notified only when
changes were successfully made use *report_changes*. And *report_failures* will
generate an email if there were failures.
The configuration allows you to run a salt module function in case of
success (*success_function*) or failure (*failure_function*).
Any salt function, including ones defined in the _module folder of your salt
repo, could be used here and its output will be displayed under the 'extra'
heading of the email.
Supported values for *report_format* are html, json, and yaml. The latter two
are typically used for debugging purposes, but could be used for applying
a template at some later stage.
The values for *report_delivery* are smtp or file. In case of file delivery
the only other applicable option is *file_output*.
In case of smtp delivery, smtp_* options demonstrated by the example above
could be used to customize the email.
As you might have noticed, the success and failure subjects contain {id} and {host}
values. Any other grain name could be used. As opposed to using
{{grains['id']}}, which will be rendered by the master and contain master's
values at the time of pillar generation, these will contain minion values at
the time of execution.
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import smtplib
import cgi
from email.mime.text import MIMEText
from salt.ext.six.moves import range
from salt.ext.six.moves import StringIO
from salt.ext import six
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.yaml
import salt.returners
log = logging.getLogger(__name__)
__virtualname__ = 'highstate'
def __virtual__():
'''
Return our name
'''
return __virtualname__
def _get_options(ret):
'''
Return options
'''
attrs = {
'report_everything': 'report_everything',
'report_changes': 'report_changes',
'report_failures': 'report_failures',
'failure_function': 'failure_function',
'success_function': 'success_function',
'report_format': 'report_format',
'report_delivery': 'report_delivery',
'file_output': 'file_output',
'smtp_sender': 'smtp_sender',
'smtp_recipients': 'smtp_recipients',
'smtp_failure_subject': 'smtp_failure_subject',
'smtp_success_subject': 'smtp_success_subject',
'smtp_server': 'smtp_server',
'smtp_port': 'smtp_port',
'smtp_tls': 'smtp_tls',
'smtp_username': 'smtp_username',
'smtp_password': 'smtp_password'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
#
# Most email readers to not support <style> tag.
# The following dict and a function provide a primitive styler
# sufficient for our needs.
#
_STYLES = {
'_table': 'border-collapse:collapse;width:100%;',
'_td': 'vertical-align:top;'
'font-family:Helvetica,Arial,sans-serif;font-size:9pt;',
'unchanged': 'color:blue;',
'changed': 'color:green',
'failed': 'color:red;',
'first': 'border-top:0;border-left:1px solid #9e9e9e;',
'first_first': 'border-top:0;border-left:0;',
'notfirst_first': 'border-left:0;border-top:1px solid #9e9e9e;',
'other': 'border-top:1px solid #9e9e9e;border-left:1px solid #9e9e9e;',
'name': 'width:70pt;',
'container': 'padding:0;'
}
def _lookup_style(element, names):
'''
Lookup style by either element name or the list of classes
'''
return _STYLES.get('_'+element, '') + \
''.join([_STYLES.get(name, '') for name in names])
def _generate_html_table(data, out, level=0, extra_style=''):
'''
Generate a single table of data
'''
print('<table style="{0}">'.format(
_lookup_style('table', ['table' + six.text_type(level)])), file=out)
firstone = True
row_style = 'row' + six.text_type(level)
cell_style = 'cell' + six.text_type(level)
for subdata in data:
first_style = 'first_first' if firstone else 'notfirst_first'
second_style = 'first' if firstone else 'other'
if isinstance(subdata, dict):
if '__style__' in subdata:
new_extra_style = subdata['__style__']
del subdata['__style__']
else:
new_extra_style = extra_style
if len(subdata) == 1:
name, value = next(six.iteritems(subdata))
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'name', new_extra_style]
),
name
), file=out)
if isinstance(value, list):
print('<td style="{0}">'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'container',
new_extra_style
]
)
), file=out)
_generate_html_table(
value,
out,
level + 1,
new_extra_style
)
print('</td>', file=out)
else:
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'value',
new_extra_style
]
),
cgi.escape(six.text_type(value))
), file=out)
print('</tr>', file=out)
elif isinstance(subdata, list):
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">'.format(
_lookup_style(
'td',
[cell_style, first_style, 'container', extra_style]
)
), file=out)
_generate_html_table(subdata, out, level + 1, extra_style)
print('</td>', file=out)
print('</tr>', file=out)
else:
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'value', extra_style]
),
cgi.escape(six.text_type(subdata))
), file=out)
print('</tr>', file=out)
firstone = False
print('</table>', file=out)
def _generate_html(data, out):
'''
Generate report data as HTML
'''
print('<html>', file=out)
print('<body>', file=out)
_generate_html_table(data, out, 0)
print('</body>', file=out)
print('</html>', file=out)
def _generate_states_report(sorted_data):
'''
Generate states report
'''
states = []
for state, data in sorted_data:
module, stateid, name, function = state.split('_|-')
module_function = '.'.join((module, function))
result = data.get('result', '')
single = [
{'function': module_function},
{'name': name},
{'result': result},
{'duration': data.get('duration', 0.0)},
{'comment': data.get('comment', '')}
]
if not result:
style = 'failed'
else:
changes = data.get('changes', {})
if changes and isinstance(changes, dict):
single.append({'changes': _dict_to_name_value(changes)})
style = 'changed'
else:
style = 'unchanged'
started = data.get('start_time', '')
if started:
single.append({'started': started})
states.append({stateid: single, '__style__': style})
return states
def _generate_report(ret, setup):
'''
Generate report dictionary
'''
retdata = ret.get('return', {})
sorted_data = sorted(
retdata.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
# gather stats
for _, data in sorted_data:
if not data.get('result', True):
failed += 1
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
if data.get('changes', {}):
changed += 1
unchanged = total - failed - changed
log.debug('highstate total: %s', total)
log.debug('highstate failed: %s', failed)
log.debug('highstate unchanged: %s', unchanged)
log.debug('highstate changed: %s', changed)
# generate report if required
if setup.get('report_everything', False) or \
(setup.get('report_changes', True) and changed != 0) or \
(setup.get('report_failures', True) and failed != 0):
report = [
{'stats': [
{'total': total},
{'failed': failed, '__style__': 'failed'},
{'unchanged': unchanged, '__style__': 'unchanged'},
{'changed': changed, '__style__': 'changed'},
{'duration': duration}
]},
{'job': [
{'function': ret.get('fun', '')},
{'arguments': ret.get('fun_args', '')},
{'jid': ret.get('jid', '')},
{'success': ret.get('success', True)},
{'retcode': ret.get('retcode', 0)}
]},
{'states': _generate_states_report(sorted_data)}
]
if failed:
function = setup.get('failure_function', None)
else:
function = setup.get('success_function', None)
if function:
func_result = __salt__[function]()
report.insert(
0,
{'extra': [{function: _dict_to_name_value(func_result)}]}
)
else:
report = []
return report, failed
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def _produce_output(report, failed, setup):
'''
Produce output from the report dictionary generated by _generate_report
'''
report_format = setup.get('report_format', 'yaml')
log.debug('highstate output format: %s', report_format)
if report_format == 'json':
report_text = salt.utils.json.dumps(report)
elif report_format == 'yaml':
string_file = StringIO()
salt.utils.yaml.safe_dump(report, string_file, default_flow_style=False)
string_file.seek(0)
report_text = string_file.read()
else:
string_file = StringIO()
_generate_html(report, string_file)
string_file.seek(0)
report_text = string_file.read()
report_delivery = setup.get('report_delivery', 'file')
log.debug('highstate report_delivery: %s', report_delivery)
if report_delivery == 'file':
output_file = _sprinkle(setup.get('file_output', '/tmp/test.rpt'))
with salt.utils.files.fopen(output_file, 'w') as out:
out.write(salt.utils.stringutils.to_str(report_text))
else:
msg = MIMEText(report_text, report_format)
sender = setup.get('smtp_sender', '')
recipients = setup.get('smtp_recipients', '')
host = setup.get('smtp_server', '')
port = int(setup.get('smtp_port', 25))
tls = setup.get('smtp_tls')
username = setup.get('smtp_username')
password = setup.get('smtp_password')
if failed:
subject = setup.get('smtp_failure_subject', 'Installation failure')
else:
subject = setup.get('smtp_success_subject', 'Installation success')
subject = _sprinkle(subject)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
log.debug('highstate smtp port: %d', port)
smtp = smtplib.SMTP(host=host, port=port)
if tls is True:
smtp.starttls()
log.debug('highstate smtp tls enabled')
if username and password:
smtp.login(username, password)
log.debug('highstate smtp authenticated')
smtp.sendmail(
sender,
[x.strip() for x in recipients.split(',')], msg.as_string())
log.debug('highstate message sent.')
smtp.quit()
def returner(ret):
'''
Check highstate return information and possibly fire off an email
or save a file.
'''
setup = _get_options(ret)
log.debug('highstate setup %s', setup)
report, failed = _generate_report(ret, setup)
if report:
_produce_output(report, failed, setup)
def __test_html():
'''
HTML generation test only used when called from the command line:
python ./highstate.py
Typical options for generating the report file:
highstate:
report_format: yaml
report_delivery: file
file_output: '/srv/salt/_returners/test.rpt'
'''
with salt.utils.files.fopen('test.rpt', 'r') as input_file:
data_text = salt.utils.stringutils.to_unicode(input_file.read())
data = salt.utils.yaml.safe_load(data_text)
string_file = StringIO()
_generate_html(data, string_file)
string_file.seek(0)
result = string_file.read()
with salt.utils.files.fopen('test.html', 'w') as output:
output.write(salt.utils.stringutils.to_str(result))
if __name__ == '__main__':
__test_html()
|
saltstack/salt | salt/returners/highstate_return.py | _generate_states_report | python | def _generate_states_report(sorted_data):
'''
Generate states report
'''
states = []
for state, data in sorted_data:
module, stateid, name, function = state.split('_|-')
module_function = '.'.join((module, function))
result = data.get('result', '')
single = [
{'function': module_function},
{'name': name},
{'result': result},
{'duration': data.get('duration', 0.0)},
{'comment': data.get('comment', '')}
]
if not result:
style = 'failed'
else:
changes = data.get('changes', {})
if changes and isinstance(changes, dict):
single.append({'changes': _dict_to_name_value(changes)})
style = 'changed'
else:
style = 'unchanged'
started = data.get('start_time', '')
if started:
single.append({'started': started})
states.append({stateid: single, '__style__': style})
return states | Generate states report | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/highstate_return.py#L300-L332 | null | # -*- coding: utf-8 -*-
'''
Return the results of a highstate (or any other state function that returns
data in a compatible format) via an HTML email or HTML file.
.. versionadded:: 2017.7.0
Similar results can be achieved by using the smtp returner with a custom template,
except an attempt at writing such a template for the complex data structure
returned by highstate function had proven to be a challenge, not to mention
that the smtp module doesn't support sending HTML mail at the moment.
The main goal of this returner was to produce an easy to read email similar
to the output of highstate outputter used by the CLI.
This returner could be very useful during scheduled executions,
but could also be useful for communicating the results of a manual execution.
Returner configuration is controlled in a standard fashion either via
highstate group or an alternatively named group.
.. code-block:: bash
salt '*' state.highstate --return highstate
To use the alternative configuration, append '--return_config config-name'
.. code-block:: bash
salt '*' state.highstate --return highstate --return_config simple
Here is an example of what the configuration might look like:
.. code-block:: yaml
simple.highstate:
report_failures: True
report_changes: True
report_everything: False
failure_function: pillar.items
success_function: pillar.items
report_format: html
report_delivery: smtp
smtp_success_subject: 'success minion {id} on host {host}'
smtp_failure_subject: 'failure minion {id} on host {host}'
smtp_server: smtp.example.com
smtp_port: 25
smtp_tls: False
smtp_username: username
smtp_password: password
smtp_recipients: [email protected], [email protected]
smtp_sender: [email protected]
The *report_failures*, *report_changes*, and *report_everything* flags provide
filtering of the results. If you want an email to be sent every time, then
*report_everything* is your choice. If you want to be notified only when
changes were successfully made use *report_changes*. And *report_failures* will
generate an email if there were failures.
The configuration allows you to run a salt module function in case of
success (*success_function*) or failure (*failure_function*).
Any salt function, including ones defined in the _module folder of your salt
repo, could be used here and its output will be displayed under the 'extra'
heading of the email.
Supported values for *report_format* are html, json, and yaml. The latter two
are typically used for debugging purposes, but could be used for applying
a template at some later stage.
The values for *report_delivery* are smtp or file. In case of file delivery
the only other applicable option is *file_output*.
In case of smtp delivery, smtp_* options demonstrated by the example above
could be used to customize the email.
As you might have noticed, the success and failure subjects contain {id} and {host}
values. Any other grain name could be used. As opposed to using
{{grains['id']}}, which will be rendered by the master and contain master's
values at the time of pillar generation, these will contain minion values at
the time of execution.
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import smtplib
import cgi
from email.mime.text import MIMEText
from salt.ext.six.moves import range
from salt.ext.six.moves import StringIO
from salt.ext import six
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.yaml
import salt.returners
log = logging.getLogger(__name__)
__virtualname__ = 'highstate'
def __virtual__():
'''
Return our name
'''
return __virtualname__
def _get_options(ret):
'''
Return options
'''
attrs = {
'report_everything': 'report_everything',
'report_changes': 'report_changes',
'report_failures': 'report_failures',
'failure_function': 'failure_function',
'success_function': 'success_function',
'report_format': 'report_format',
'report_delivery': 'report_delivery',
'file_output': 'file_output',
'smtp_sender': 'smtp_sender',
'smtp_recipients': 'smtp_recipients',
'smtp_failure_subject': 'smtp_failure_subject',
'smtp_success_subject': 'smtp_success_subject',
'smtp_server': 'smtp_server',
'smtp_port': 'smtp_port',
'smtp_tls': 'smtp_tls',
'smtp_username': 'smtp_username',
'smtp_password': 'smtp_password'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
#
# Most email readers to not support <style> tag.
# The following dict and a function provide a primitive styler
# sufficient for our needs.
#
_STYLES = {
'_table': 'border-collapse:collapse;width:100%;',
'_td': 'vertical-align:top;'
'font-family:Helvetica,Arial,sans-serif;font-size:9pt;',
'unchanged': 'color:blue;',
'changed': 'color:green',
'failed': 'color:red;',
'first': 'border-top:0;border-left:1px solid #9e9e9e;',
'first_first': 'border-top:0;border-left:0;',
'notfirst_first': 'border-left:0;border-top:1px solid #9e9e9e;',
'other': 'border-top:1px solid #9e9e9e;border-left:1px solid #9e9e9e;',
'name': 'width:70pt;',
'container': 'padding:0;'
}
def _lookup_style(element, names):
'''
Lookup style by either element name or the list of classes
'''
return _STYLES.get('_'+element, '') + \
''.join([_STYLES.get(name, '') for name in names])
def _generate_html_table(data, out, level=0, extra_style=''):
'''
Generate a single table of data
'''
print('<table style="{0}">'.format(
_lookup_style('table', ['table' + six.text_type(level)])), file=out)
firstone = True
row_style = 'row' + six.text_type(level)
cell_style = 'cell' + six.text_type(level)
for subdata in data:
first_style = 'first_first' if firstone else 'notfirst_first'
second_style = 'first' if firstone else 'other'
if isinstance(subdata, dict):
if '__style__' in subdata:
new_extra_style = subdata['__style__']
del subdata['__style__']
else:
new_extra_style = extra_style
if len(subdata) == 1:
name, value = next(six.iteritems(subdata))
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'name', new_extra_style]
),
name
), file=out)
if isinstance(value, list):
print('<td style="{0}">'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'container',
new_extra_style
]
)
), file=out)
_generate_html_table(
value,
out,
level + 1,
new_extra_style
)
print('</td>', file=out)
else:
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'value',
new_extra_style
]
),
cgi.escape(six.text_type(value))
), file=out)
print('</tr>', file=out)
elif isinstance(subdata, list):
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">'.format(
_lookup_style(
'td',
[cell_style, first_style, 'container', extra_style]
)
), file=out)
_generate_html_table(subdata, out, level + 1, extra_style)
print('</td>', file=out)
print('</tr>', file=out)
else:
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'value', extra_style]
),
cgi.escape(six.text_type(subdata))
), file=out)
print('</tr>', file=out)
firstone = False
print('</table>', file=out)
def _generate_html(data, out):
'''
Generate report data as HTML
'''
print('<html>', file=out)
print('<body>', file=out)
_generate_html_table(data, out, 0)
print('</body>', file=out)
print('</html>', file=out)
def _dict_to_name_value(data):
'''
Convert a dictionary to a list of dictionaries to facilitate ordering
'''
if isinstance(data, dict):
sorted_data = sorted(data.items(), key=lambda s: s[0])
result = []
for name, value in sorted_data:
if isinstance(value, dict):
result.append({name: _dict_to_name_value(value)})
else:
result.append({name: value})
else:
result = data
return result
def _generate_report(ret, setup):
'''
Generate report dictionary
'''
retdata = ret.get('return', {})
sorted_data = sorted(
retdata.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
# gather stats
for _, data in sorted_data:
if not data.get('result', True):
failed += 1
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
if data.get('changes', {}):
changed += 1
unchanged = total - failed - changed
log.debug('highstate total: %s', total)
log.debug('highstate failed: %s', failed)
log.debug('highstate unchanged: %s', unchanged)
log.debug('highstate changed: %s', changed)
# generate report if required
if setup.get('report_everything', False) or \
(setup.get('report_changes', True) and changed != 0) or \
(setup.get('report_failures', True) and failed != 0):
report = [
{'stats': [
{'total': total},
{'failed': failed, '__style__': 'failed'},
{'unchanged': unchanged, '__style__': 'unchanged'},
{'changed': changed, '__style__': 'changed'},
{'duration': duration}
]},
{'job': [
{'function': ret.get('fun', '')},
{'arguments': ret.get('fun_args', '')},
{'jid': ret.get('jid', '')},
{'success': ret.get('success', True)},
{'retcode': ret.get('retcode', 0)}
]},
{'states': _generate_states_report(sorted_data)}
]
if failed:
function = setup.get('failure_function', None)
else:
function = setup.get('success_function', None)
if function:
func_result = __salt__[function]()
report.insert(
0,
{'extra': [{function: _dict_to_name_value(func_result)}]}
)
else:
report = []
return report, failed
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def _produce_output(report, failed, setup):
'''
Produce output from the report dictionary generated by _generate_report
'''
report_format = setup.get('report_format', 'yaml')
log.debug('highstate output format: %s', report_format)
if report_format == 'json':
report_text = salt.utils.json.dumps(report)
elif report_format == 'yaml':
string_file = StringIO()
salt.utils.yaml.safe_dump(report, string_file, default_flow_style=False)
string_file.seek(0)
report_text = string_file.read()
else:
string_file = StringIO()
_generate_html(report, string_file)
string_file.seek(0)
report_text = string_file.read()
report_delivery = setup.get('report_delivery', 'file')
log.debug('highstate report_delivery: %s', report_delivery)
if report_delivery == 'file':
output_file = _sprinkle(setup.get('file_output', '/tmp/test.rpt'))
with salt.utils.files.fopen(output_file, 'w') as out:
out.write(salt.utils.stringutils.to_str(report_text))
else:
msg = MIMEText(report_text, report_format)
sender = setup.get('smtp_sender', '')
recipients = setup.get('smtp_recipients', '')
host = setup.get('smtp_server', '')
port = int(setup.get('smtp_port', 25))
tls = setup.get('smtp_tls')
username = setup.get('smtp_username')
password = setup.get('smtp_password')
if failed:
subject = setup.get('smtp_failure_subject', 'Installation failure')
else:
subject = setup.get('smtp_success_subject', 'Installation success')
subject = _sprinkle(subject)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
log.debug('highstate smtp port: %d', port)
smtp = smtplib.SMTP(host=host, port=port)
if tls is True:
smtp.starttls()
log.debug('highstate smtp tls enabled')
if username and password:
smtp.login(username, password)
log.debug('highstate smtp authenticated')
smtp.sendmail(
sender,
[x.strip() for x in recipients.split(',')], msg.as_string())
log.debug('highstate message sent.')
smtp.quit()
def returner(ret):
'''
Check highstate return information and possibly fire off an email
or save a file.
'''
setup = _get_options(ret)
log.debug('highstate setup %s', setup)
report, failed = _generate_report(ret, setup)
if report:
_produce_output(report, failed, setup)
def __test_html():
'''
HTML generation test only used when called from the command line:
python ./highstate.py
Typical options for generating the report file:
highstate:
report_format: yaml
report_delivery: file
file_output: '/srv/salt/_returners/test.rpt'
'''
with salt.utils.files.fopen('test.rpt', 'r') as input_file:
data_text = salt.utils.stringutils.to_unicode(input_file.read())
data = salt.utils.yaml.safe_load(data_text)
string_file = StringIO()
_generate_html(data, string_file)
string_file.seek(0)
result = string_file.read()
with salt.utils.files.fopen('test.html', 'w') as output:
output.write(salt.utils.stringutils.to_str(result))
if __name__ == '__main__':
__test_html()
|
saltstack/salt | salt/returners/highstate_return.py | _generate_report | python | def _generate_report(ret, setup):
'''
Generate report dictionary
'''
retdata = ret.get('return', {})
sorted_data = sorted(
retdata.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
# gather stats
for _, data in sorted_data:
if not data.get('result', True):
failed += 1
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
if data.get('changes', {}):
changed += 1
unchanged = total - failed - changed
log.debug('highstate total: %s', total)
log.debug('highstate failed: %s', failed)
log.debug('highstate unchanged: %s', unchanged)
log.debug('highstate changed: %s', changed)
# generate report if required
if setup.get('report_everything', False) or \
(setup.get('report_changes', True) and changed != 0) or \
(setup.get('report_failures', True) and failed != 0):
report = [
{'stats': [
{'total': total},
{'failed': failed, '__style__': 'failed'},
{'unchanged': unchanged, '__style__': 'unchanged'},
{'changed': changed, '__style__': 'changed'},
{'duration': duration}
]},
{'job': [
{'function': ret.get('fun', '')},
{'arguments': ret.get('fun_args', '')},
{'jid': ret.get('jid', '')},
{'success': ret.get('success', True)},
{'retcode': ret.get('retcode', 0)}
]},
{'states': _generate_states_report(sorted_data)}
]
if failed:
function = setup.get('failure_function', None)
else:
function = setup.get('success_function', None)
if function:
func_result = __salt__[function]()
report.insert(
0,
{'extra': [{function: _dict_to_name_value(func_result)}]}
)
else:
report = []
return report, failed | Generate report dictionary | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/highstate_return.py#L335-L411 | [
"def _generate_states_report(sorted_data):\n '''\n Generate states report\n '''\n states = []\n for state, data in sorted_data:\n module, stateid, name, function = state.split('_|-')\n module_function = '.'.join((module, function))\n result = data.get('result', '')\n single = [\n {'function': module_function},\n {'name': name},\n {'result': result},\n {'duration': data.get('duration', 0.0)},\n {'comment': data.get('comment', '')}\n ]\n\n if not result:\n style = 'failed'\n else:\n changes = data.get('changes', {})\n if changes and isinstance(changes, dict):\n single.append({'changes': _dict_to_name_value(changes)})\n style = 'changed'\n else:\n style = 'unchanged'\n\n started = data.get('start_time', '')\n if started:\n single.append({'started': started})\n\n states.append({stateid: single, '__style__': style})\n return states\n"
] | # -*- coding: utf-8 -*-
'''
Return the results of a highstate (or any other state function that returns
data in a compatible format) via an HTML email or HTML file.
.. versionadded:: 2017.7.0
Similar results can be achieved by using the smtp returner with a custom template,
except an attempt at writing such a template for the complex data structure
returned by highstate function had proven to be a challenge, not to mention
that the smtp module doesn't support sending HTML mail at the moment.
The main goal of this returner was to produce an easy to read email similar
to the output of highstate outputter used by the CLI.
This returner could be very useful during scheduled executions,
but could also be useful for communicating the results of a manual execution.
Returner configuration is controlled in a standard fashion either via
highstate group or an alternatively named group.
.. code-block:: bash
salt '*' state.highstate --return highstate
To use the alternative configuration, append '--return_config config-name'
.. code-block:: bash
salt '*' state.highstate --return highstate --return_config simple
Here is an example of what the configuration might look like:
.. code-block:: yaml
simple.highstate:
report_failures: True
report_changes: True
report_everything: False
failure_function: pillar.items
success_function: pillar.items
report_format: html
report_delivery: smtp
smtp_success_subject: 'success minion {id} on host {host}'
smtp_failure_subject: 'failure minion {id} on host {host}'
smtp_server: smtp.example.com
smtp_port: 25
smtp_tls: False
smtp_username: username
smtp_password: password
smtp_recipients: [email protected], [email protected]
smtp_sender: [email protected]
The *report_failures*, *report_changes*, and *report_everything* flags provide
filtering of the results. If you want an email to be sent every time, then
*report_everything* is your choice. If you want to be notified only when
changes were successfully made use *report_changes*. And *report_failures* will
generate an email if there were failures.
The configuration allows you to run a salt module function in case of
success (*success_function*) or failure (*failure_function*).
Any salt function, including ones defined in the _module folder of your salt
repo, could be used here and its output will be displayed under the 'extra'
heading of the email.
Supported values for *report_format* are html, json, and yaml. The latter two
are typically used for debugging purposes, but could be used for applying
a template at some later stage.
The values for *report_delivery* are smtp or file. In case of file delivery
the only other applicable option is *file_output*.
In case of smtp delivery, smtp_* options demonstrated by the example above
could be used to customize the email.
As you might have noticed, the success and failure subjects contain {id} and {host}
values. Any other grain name could be used. As opposed to using
{{grains['id']}}, which will be rendered by the master and contain master's
values at the time of pillar generation, these will contain minion values at
the time of execution.
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import smtplib
import cgi
from email.mime.text import MIMEText
from salt.ext.six.moves import range
from salt.ext.six.moves import StringIO
from salt.ext import six
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.yaml
import salt.returners
log = logging.getLogger(__name__)
__virtualname__ = 'highstate'
def __virtual__():
'''
Return our name
'''
return __virtualname__
def _get_options(ret):
'''
Return options
'''
attrs = {
'report_everything': 'report_everything',
'report_changes': 'report_changes',
'report_failures': 'report_failures',
'failure_function': 'failure_function',
'success_function': 'success_function',
'report_format': 'report_format',
'report_delivery': 'report_delivery',
'file_output': 'file_output',
'smtp_sender': 'smtp_sender',
'smtp_recipients': 'smtp_recipients',
'smtp_failure_subject': 'smtp_failure_subject',
'smtp_success_subject': 'smtp_success_subject',
'smtp_server': 'smtp_server',
'smtp_port': 'smtp_port',
'smtp_tls': 'smtp_tls',
'smtp_username': 'smtp_username',
'smtp_password': 'smtp_password'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
#
# Most email readers to not support <style> tag.
# The following dict and a function provide a primitive styler
# sufficient for our needs.
#
_STYLES = {
'_table': 'border-collapse:collapse;width:100%;',
'_td': 'vertical-align:top;'
'font-family:Helvetica,Arial,sans-serif;font-size:9pt;',
'unchanged': 'color:blue;',
'changed': 'color:green',
'failed': 'color:red;',
'first': 'border-top:0;border-left:1px solid #9e9e9e;',
'first_first': 'border-top:0;border-left:0;',
'notfirst_first': 'border-left:0;border-top:1px solid #9e9e9e;',
'other': 'border-top:1px solid #9e9e9e;border-left:1px solid #9e9e9e;',
'name': 'width:70pt;',
'container': 'padding:0;'
}
def _lookup_style(element, names):
'''
Lookup style by either element name or the list of classes
'''
return _STYLES.get('_'+element, '') + \
''.join([_STYLES.get(name, '') for name in names])
def _generate_html_table(data, out, level=0, extra_style=''):
'''
Generate a single table of data
'''
print('<table style="{0}">'.format(
_lookup_style('table', ['table' + six.text_type(level)])), file=out)
firstone = True
row_style = 'row' + six.text_type(level)
cell_style = 'cell' + six.text_type(level)
for subdata in data:
first_style = 'first_first' if firstone else 'notfirst_first'
second_style = 'first' if firstone else 'other'
if isinstance(subdata, dict):
if '__style__' in subdata:
new_extra_style = subdata['__style__']
del subdata['__style__']
else:
new_extra_style = extra_style
if len(subdata) == 1:
name, value = next(six.iteritems(subdata))
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'name', new_extra_style]
),
name
), file=out)
if isinstance(value, list):
print('<td style="{0}">'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'container',
new_extra_style
]
)
), file=out)
_generate_html_table(
value,
out,
level + 1,
new_extra_style
)
print('</td>', file=out)
else:
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'value',
new_extra_style
]
),
cgi.escape(six.text_type(value))
), file=out)
print('</tr>', file=out)
elif isinstance(subdata, list):
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">'.format(
_lookup_style(
'td',
[cell_style, first_style, 'container', extra_style]
)
), file=out)
_generate_html_table(subdata, out, level + 1, extra_style)
print('</td>', file=out)
print('</tr>', file=out)
else:
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'value', extra_style]
),
cgi.escape(six.text_type(subdata))
), file=out)
print('</tr>', file=out)
firstone = False
print('</table>', file=out)
def _generate_html(data, out):
'''
Generate report data as HTML
'''
print('<html>', file=out)
print('<body>', file=out)
_generate_html_table(data, out, 0)
print('</body>', file=out)
print('</html>', file=out)
def _dict_to_name_value(data):
'''
Convert a dictionary to a list of dictionaries to facilitate ordering
'''
if isinstance(data, dict):
sorted_data = sorted(data.items(), key=lambda s: s[0])
result = []
for name, value in sorted_data:
if isinstance(value, dict):
result.append({name: _dict_to_name_value(value)})
else:
result.append({name: value})
else:
result = data
return result
def _generate_states_report(sorted_data):
'''
Generate states report
'''
states = []
for state, data in sorted_data:
module, stateid, name, function = state.split('_|-')
module_function = '.'.join((module, function))
result = data.get('result', '')
single = [
{'function': module_function},
{'name': name},
{'result': result},
{'duration': data.get('duration', 0.0)},
{'comment': data.get('comment', '')}
]
if not result:
style = 'failed'
else:
changes = data.get('changes', {})
if changes and isinstance(changes, dict):
single.append({'changes': _dict_to_name_value(changes)})
style = 'changed'
else:
style = 'unchanged'
started = data.get('start_time', '')
if started:
single.append({'started': started})
states.append({stateid: single, '__style__': style})
return states
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def _produce_output(report, failed, setup):
'''
Produce output from the report dictionary generated by _generate_report
'''
report_format = setup.get('report_format', 'yaml')
log.debug('highstate output format: %s', report_format)
if report_format == 'json':
report_text = salt.utils.json.dumps(report)
elif report_format == 'yaml':
string_file = StringIO()
salt.utils.yaml.safe_dump(report, string_file, default_flow_style=False)
string_file.seek(0)
report_text = string_file.read()
else:
string_file = StringIO()
_generate_html(report, string_file)
string_file.seek(0)
report_text = string_file.read()
report_delivery = setup.get('report_delivery', 'file')
log.debug('highstate report_delivery: %s', report_delivery)
if report_delivery == 'file':
output_file = _sprinkle(setup.get('file_output', '/tmp/test.rpt'))
with salt.utils.files.fopen(output_file, 'w') as out:
out.write(salt.utils.stringutils.to_str(report_text))
else:
msg = MIMEText(report_text, report_format)
sender = setup.get('smtp_sender', '')
recipients = setup.get('smtp_recipients', '')
host = setup.get('smtp_server', '')
port = int(setup.get('smtp_port', 25))
tls = setup.get('smtp_tls')
username = setup.get('smtp_username')
password = setup.get('smtp_password')
if failed:
subject = setup.get('smtp_failure_subject', 'Installation failure')
else:
subject = setup.get('smtp_success_subject', 'Installation success')
subject = _sprinkle(subject)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
log.debug('highstate smtp port: %d', port)
smtp = smtplib.SMTP(host=host, port=port)
if tls is True:
smtp.starttls()
log.debug('highstate smtp tls enabled')
if username and password:
smtp.login(username, password)
log.debug('highstate smtp authenticated')
smtp.sendmail(
sender,
[x.strip() for x in recipients.split(',')], msg.as_string())
log.debug('highstate message sent.')
smtp.quit()
def returner(ret):
'''
Check highstate return information and possibly fire off an email
or save a file.
'''
setup = _get_options(ret)
log.debug('highstate setup %s', setup)
report, failed = _generate_report(ret, setup)
if report:
_produce_output(report, failed, setup)
def __test_html():
'''
HTML generation test only used when called from the command line:
python ./highstate.py
Typical options for generating the report file:
highstate:
report_format: yaml
report_delivery: file
file_output: '/srv/salt/_returners/test.rpt'
'''
with salt.utils.files.fopen('test.rpt', 'r') as input_file:
data_text = salt.utils.stringutils.to_unicode(input_file.read())
data = salt.utils.yaml.safe_load(data_text)
string_file = StringIO()
_generate_html(data, string_file)
string_file.seek(0)
result = string_file.read()
with salt.utils.files.fopen('test.html', 'w') as output:
output.write(salt.utils.stringutils.to_str(result))
if __name__ == '__main__':
__test_html()
|
saltstack/salt | salt/returners/highstate_return.py | _produce_output | python | def _produce_output(report, failed, setup):
'''
Produce output from the report dictionary generated by _generate_report
'''
report_format = setup.get('report_format', 'yaml')
log.debug('highstate output format: %s', report_format)
if report_format == 'json':
report_text = salt.utils.json.dumps(report)
elif report_format == 'yaml':
string_file = StringIO()
salt.utils.yaml.safe_dump(report, string_file, default_flow_style=False)
string_file.seek(0)
report_text = string_file.read()
else:
string_file = StringIO()
_generate_html(report, string_file)
string_file.seek(0)
report_text = string_file.read()
report_delivery = setup.get('report_delivery', 'file')
log.debug('highstate report_delivery: %s', report_delivery)
if report_delivery == 'file':
output_file = _sprinkle(setup.get('file_output', '/tmp/test.rpt'))
with salt.utils.files.fopen(output_file, 'w') as out:
out.write(salt.utils.stringutils.to_str(report_text))
else:
msg = MIMEText(report_text, report_format)
sender = setup.get('smtp_sender', '')
recipients = setup.get('smtp_recipients', '')
host = setup.get('smtp_server', '')
port = int(setup.get('smtp_port', 25))
tls = setup.get('smtp_tls')
username = setup.get('smtp_username')
password = setup.get('smtp_password')
if failed:
subject = setup.get('smtp_failure_subject', 'Installation failure')
else:
subject = setup.get('smtp_success_subject', 'Installation success')
subject = _sprinkle(subject)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
log.debug('highstate smtp port: %d', port)
smtp = smtplib.SMTP(host=host, port=port)
if tls is True:
smtp.starttls()
log.debug('highstate smtp tls enabled')
if username and password:
smtp.login(username, password)
log.debug('highstate smtp authenticated')
smtp.sendmail(
sender,
[x.strip() for x in recipients.split(',')], msg.as_string())
log.debug('highstate message sent.')
smtp.quit() | Produce output from the report dictionary generated by _generate_report | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/highstate_return.py#L425-L493 | null | # -*- coding: utf-8 -*-
'''
Return the results of a highstate (or any other state function that returns
data in a compatible format) via an HTML email or HTML file.
.. versionadded:: 2017.7.0
Similar results can be achieved by using the smtp returner with a custom template,
except an attempt at writing such a template for the complex data structure
returned by highstate function had proven to be a challenge, not to mention
that the smtp module doesn't support sending HTML mail at the moment.
The main goal of this returner was to produce an easy to read email similar
to the output of highstate outputter used by the CLI.
This returner could be very useful during scheduled executions,
but could also be useful for communicating the results of a manual execution.
Returner configuration is controlled in a standard fashion either via
highstate group or an alternatively named group.
.. code-block:: bash
salt '*' state.highstate --return highstate
To use the alternative configuration, append '--return_config config-name'
.. code-block:: bash
salt '*' state.highstate --return highstate --return_config simple
Here is an example of what the configuration might look like:
.. code-block:: yaml
simple.highstate:
report_failures: True
report_changes: True
report_everything: False
failure_function: pillar.items
success_function: pillar.items
report_format: html
report_delivery: smtp
smtp_success_subject: 'success minion {id} on host {host}'
smtp_failure_subject: 'failure minion {id} on host {host}'
smtp_server: smtp.example.com
smtp_port: 25
smtp_tls: False
smtp_username: username
smtp_password: password
smtp_recipients: [email protected], [email protected]
smtp_sender: [email protected]
The *report_failures*, *report_changes*, and *report_everything* flags provide
filtering of the results. If you want an email to be sent every time, then
*report_everything* is your choice. If you want to be notified only when
changes were successfully made use *report_changes*. And *report_failures* will
generate an email if there were failures.
The configuration allows you to run a salt module function in case of
success (*success_function*) or failure (*failure_function*).
Any salt function, including ones defined in the _module folder of your salt
repo, could be used here and its output will be displayed under the 'extra'
heading of the email.
Supported values for *report_format* are html, json, and yaml. The latter two
are typically used for debugging purposes, but could be used for applying
a template at some later stage.
The values for *report_delivery* are smtp or file. In case of file delivery
the only other applicable option is *file_output*.
In case of smtp delivery, smtp_* options demonstrated by the example above
could be used to customize the email.
As you might have noticed, the success and failure subjects contain {id} and {host}
values. Any other grain name could be used. As opposed to using
{{grains['id']}}, which will be rendered by the master and contain master's
values at the time of pillar generation, these will contain minion values at
the time of execution.
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import smtplib
import cgi
from email.mime.text import MIMEText
from salt.ext.six.moves import range
from salt.ext.six.moves import StringIO
from salt.ext import six
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.yaml
import salt.returners
log = logging.getLogger(__name__)
__virtualname__ = 'highstate'
def __virtual__():
'''
Return our name
'''
return __virtualname__
def _get_options(ret):
'''
Return options
'''
attrs = {
'report_everything': 'report_everything',
'report_changes': 'report_changes',
'report_failures': 'report_failures',
'failure_function': 'failure_function',
'success_function': 'success_function',
'report_format': 'report_format',
'report_delivery': 'report_delivery',
'file_output': 'file_output',
'smtp_sender': 'smtp_sender',
'smtp_recipients': 'smtp_recipients',
'smtp_failure_subject': 'smtp_failure_subject',
'smtp_success_subject': 'smtp_success_subject',
'smtp_server': 'smtp_server',
'smtp_port': 'smtp_port',
'smtp_tls': 'smtp_tls',
'smtp_username': 'smtp_username',
'smtp_password': 'smtp_password'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
#
# Most email readers to not support <style> tag.
# The following dict and a function provide a primitive styler
# sufficient for our needs.
#
_STYLES = {
'_table': 'border-collapse:collapse;width:100%;',
'_td': 'vertical-align:top;'
'font-family:Helvetica,Arial,sans-serif;font-size:9pt;',
'unchanged': 'color:blue;',
'changed': 'color:green',
'failed': 'color:red;',
'first': 'border-top:0;border-left:1px solid #9e9e9e;',
'first_first': 'border-top:0;border-left:0;',
'notfirst_first': 'border-left:0;border-top:1px solid #9e9e9e;',
'other': 'border-top:1px solid #9e9e9e;border-left:1px solid #9e9e9e;',
'name': 'width:70pt;',
'container': 'padding:0;'
}
def _lookup_style(element, names):
'''
Lookup style by either element name or the list of classes
'''
return _STYLES.get('_'+element, '') + \
''.join([_STYLES.get(name, '') for name in names])
def _generate_html_table(data, out, level=0, extra_style=''):
'''
Generate a single table of data
'''
print('<table style="{0}">'.format(
_lookup_style('table', ['table' + six.text_type(level)])), file=out)
firstone = True
row_style = 'row' + six.text_type(level)
cell_style = 'cell' + six.text_type(level)
for subdata in data:
first_style = 'first_first' if firstone else 'notfirst_first'
second_style = 'first' if firstone else 'other'
if isinstance(subdata, dict):
if '__style__' in subdata:
new_extra_style = subdata['__style__']
del subdata['__style__']
else:
new_extra_style = extra_style
if len(subdata) == 1:
name, value = next(six.iteritems(subdata))
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'name', new_extra_style]
),
name
), file=out)
if isinstance(value, list):
print('<td style="{0}">'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'container',
new_extra_style
]
)
), file=out)
_generate_html_table(
value,
out,
level + 1,
new_extra_style
)
print('</td>', file=out)
else:
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'value',
new_extra_style
]
),
cgi.escape(six.text_type(value))
), file=out)
print('</tr>', file=out)
elif isinstance(subdata, list):
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">'.format(
_lookup_style(
'td',
[cell_style, first_style, 'container', extra_style]
)
), file=out)
_generate_html_table(subdata, out, level + 1, extra_style)
print('</td>', file=out)
print('</tr>', file=out)
else:
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'value', extra_style]
),
cgi.escape(six.text_type(subdata))
), file=out)
print('</tr>', file=out)
firstone = False
print('</table>', file=out)
def _generate_html(data, out):
'''
Generate report data as HTML
'''
print('<html>', file=out)
print('<body>', file=out)
_generate_html_table(data, out, 0)
print('</body>', file=out)
print('</html>', file=out)
def _dict_to_name_value(data):
'''
Convert a dictionary to a list of dictionaries to facilitate ordering
'''
if isinstance(data, dict):
sorted_data = sorted(data.items(), key=lambda s: s[0])
result = []
for name, value in sorted_data:
if isinstance(value, dict):
result.append({name: _dict_to_name_value(value)})
else:
result.append({name: value})
else:
result = data
return result
def _generate_states_report(sorted_data):
'''
Generate states report
'''
states = []
for state, data in sorted_data:
module, stateid, name, function = state.split('_|-')
module_function = '.'.join((module, function))
result = data.get('result', '')
single = [
{'function': module_function},
{'name': name},
{'result': result},
{'duration': data.get('duration', 0.0)},
{'comment': data.get('comment', '')}
]
if not result:
style = 'failed'
else:
changes = data.get('changes', {})
if changes and isinstance(changes, dict):
single.append({'changes': _dict_to_name_value(changes)})
style = 'changed'
else:
style = 'unchanged'
started = data.get('start_time', '')
if started:
single.append({'started': started})
states.append({stateid: single, '__style__': style})
return states
def _generate_report(ret, setup):
'''
Generate report dictionary
'''
retdata = ret.get('return', {})
sorted_data = sorted(
retdata.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
# gather stats
for _, data in sorted_data:
if not data.get('result', True):
failed += 1
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
if data.get('changes', {}):
changed += 1
unchanged = total - failed - changed
log.debug('highstate total: %s', total)
log.debug('highstate failed: %s', failed)
log.debug('highstate unchanged: %s', unchanged)
log.debug('highstate changed: %s', changed)
# generate report if required
if setup.get('report_everything', False) or \
(setup.get('report_changes', True) and changed != 0) or \
(setup.get('report_failures', True) and failed != 0):
report = [
{'stats': [
{'total': total},
{'failed': failed, '__style__': 'failed'},
{'unchanged': unchanged, '__style__': 'unchanged'},
{'changed': changed, '__style__': 'changed'},
{'duration': duration}
]},
{'job': [
{'function': ret.get('fun', '')},
{'arguments': ret.get('fun_args', '')},
{'jid': ret.get('jid', '')},
{'success': ret.get('success', True)},
{'retcode': ret.get('retcode', 0)}
]},
{'states': _generate_states_report(sorted_data)}
]
if failed:
function = setup.get('failure_function', None)
else:
function = setup.get('success_function', None)
if function:
func_result = __salt__[function]()
report.insert(
0,
{'extra': [{function: _dict_to_name_value(func_result)}]}
)
else:
report = []
return report, failed
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def returner(ret):
'''
Check highstate return information and possibly fire off an email
or save a file.
'''
setup = _get_options(ret)
log.debug('highstate setup %s', setup)
report, failed = _generate_report(ret, setup)
if report:
_produce_output(report, failed, setup)
def __test_html():
'''
HTML generation test only used when called from the command line:
python ./highstate.py
Typical options for generating the report file:
highstate:
report_format: yaml
report_delivery: file
file_output: '/srv/salt/_returners/test.rpt'
'''
with salt.utils.files.fopen('test.rpt', 'r') as input_file:
data_text = salt.utils.stringutils.to_unicode(input_file.read())
data = salt.utils.yaml.safe_load(data_text)
string_file = StringIO()
_generate_html(data, string_file)
string_file.seek(0)
result = string_file.read()
with salt.utils.files.fopen('test.html', 'w') as output:
output.write(salt.utils.stringutils.to_str(result))
if __name__ == '__main__':
__test_html()
|
saltstack/salt | salt/returners/highstate_return.py | returner | python | def returner(ret):
'''
Check highstate return information and possibly fire off an email
or save a file.
'''
setup = _get_options(ret)
log.debug('highstate setup %s', setup)
report, failed = _generate_report(ret, setup)
if report:
_produce_output(report, failed, setup) | Check highstate return information and possibly fire off an email
or save a file. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/highstate_return.py#L496-L507 | [
"def _get_options(ret):\n '''\n Return options\n '''\n attrs = {\n 'report_everything': 'report_everything',\n 'report_changes': 'report_changes',\n 'report_failures': 'report_failures',\n 'failure_function': 'failure_function',\n 'success_function': 'success_function',\n 'report_format': 'report_format',\n 'report_delivery': 'report_delivery',\n 'file_output': 'file_output',\n 'smtp_sender': 'smtp_sender',\n 'smtp_recipients': 'smtp_recipients',\n 'smtp_failure_subject': 'smtp_failure_subject',\n 'smtp_success_subject': 'smtp_success_subject',\n 'smtp_server': 'smtp_server',\n 'smtp_port': 'smtp_port',\n 'smtp_tls': 'smtp_tls',\n 'smtp_username': 'smtp_username',\n 'smtp_password': 'smtp_password'\n }\n\n _options = salt.returners.get_returner_options(\n __virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n\n return _options\n",
"def _generate_report(ret, setup):\n '''\n Generate report dictionary\n '''\n\n retdata = ret.get('return', {})\n\n sorted_data = sorted(\n retdata.items(),\n key=lambda s: s[1].get('__run_num__', 0)\n )\n\n total = 0\n failed = 0\n changed = 0\n duration = 0.0\n\n # gather stats\n for _, data in sorted_data:\n if not data.get('result', True):\n failed += 1\n total += 1\n\n try:\n duration += float(data.get('duration', 0.0))\n except ValueError:\n pass\n\n if data.get('changes', {}):\n changed += 1\n\n unchanged = total - failed - changed\n\n log.debug('highstate total: %s', total)\n log.debug('highstate failed: %s', failed)\n log.debug('highstate unchanged: %s', unchanged)\n log.debug('highstate changed: %s', changed)\n\n # generate report if required\n if setup.get('report_everything', False) or \\\n (setup.get('report_changes', True) and changed != 0) or \\\n (setup.get('report_failures', True) and failed != 0):\n\n report = [\n {'stats': [\n {'total': total},\n {'failed': failed, '__style__': 'failed'},\n {'unchanged': unchanged, '__style__': 'unchanged'},\n {'changed': changed, '__style__': 'changed'},\n {'duration': duration}\n ]},\n {'job': [\n {'function': ret.get('fun', '')},\n {'arguments': ret.get('fun_args', '')},\n {'jid': ret.get('jid', '')},\n {'success': ret.get('success', True)},\n {'retcode': ret.get('retcode', 0)}\n ]},\n {'states': _generate_states_report(sorted_data)}\n ]\n\n if failed:\n function = setup.get('failure_function', None)\n else:\n function = setup.get('success_function', None)\n\n if function:\n func_result = __salt__[function]()\n report.insert(\n 0,\n {'extra': [{function: _dict_to_name_value(func_result)}]}\n )\n\n else:\n report = []\n\n return report, failed\n",
"def _produce_output(report, failed, setup):\n '''\n Produce output from the report dictionary generated by _generate_report\n '''\n report_format = setup.get('report_format', 'yaml')\n\n log.debug('highstate output format: %s', report_format)\n\n if report_format == 'json':\n report_text = salt.utils.json.dumps(report)\n elif report_format == 'yaml':\n string_file = StringIO()\n salt.utils.yaml.safe_dump(report, string_file, default_flow_style=False)\n string_file.seek(0)\n report_text = string_file.read()\n else:\n string_file = StringIO()\n _generate_html(report, string_file)\n string_file.seek(0)\n report_text = string_file.read()\n\n report_delivery = setup.get('report_delivery', 'file')\n\n log.debug('highstate report_delivery: %s', report_delivery)\n\n if report_delivery == 'file':\n output_file = _sprinkle(setup.get('file_output', '/tmp/test.rpt'))\n with salt.utils.files.fopen(output_file, 'w') as out:\n out.write(salt.utils.stringutils.to_str(report_text))\n else:\n msg = MIMEText(report_text, report_format)\n\n sender = setup.get('smtp_sender', '')\n recipients = setup.get('smtp_recipients', '')\n\n host = setup.get('smtp_server', '')\n port = int(setup.get('smtp_port', 25))\n tls = setup.get('smtp_tls')\n username = setup.get('smtp_username')\n password = setup.get('smtp_password')\n\n if failed:\n subject = setup.get('smtp_failure_subject', 'Installation failure')\n else:\n subject = setup.get('smtp_success_subject', 'Installation success')\n\n subject = _sprinkle(subject)\n\n msg['Subject'] = subject\n msg['From'] = sender\n msg['To'] = recipients\n\n log.debug('highstate smtp port: %d', port)\n smtp = smtplib.SMTP(host=host, port=port)\n\n if tls is True:\n smtp.starttls()\n log.debug('highstate smtp tls enabled')\n\n if username and password:\n smtp.login(username, password)\n log.debug('highstate smtp authenticated')\n\n smtp.sendmail(\n sender,\n [x.strip() for x in recipients.split(',')], msg.as_string())\n log.debug('highstate message sent.')\n\n smtp.quit()\n"
] | # -*- coding: utf-8 -*-
'''
Return the results of a highstate (or any other state function that returns
data in a compatible format) via an HTML email or HTML file.
.. versionadded:: 2017.7.0
Similar results can be achieved by using the smtp returner with a custom template,
except an attempt at writing such a template for the complex data structure
returned by highstate function had proven to be a challenge, not to mention
that the smtp module doesn't support sending HTML mail at the moment.
The main goal of this returner was to produce an easy to read email similar
to the output of highstate outputter used by the CLI.
This returner could be very useful during scheduled executions,
but could also be useful for communicating the results of a manual execution.
Returner configuration is controlled in a standard fashion either via
highstate group or an alternatively named group.
.. code-block:: bash
salt '*' state.highstate --return highstate
To use the alternative configuration, append '--return_config config-name'
.. code-block:: bash
salt '*' state.highstate --return highstate --return_config simple
Here is an example of what the configuration might look like:
.. code-block:: yaml
simple.highstate:
report_failures: True
report_changes: True
report_everything: False
failure_function: pillar.items
success_function: pillar.items
report_format: html
report_delivery: smtp
smtp_success_subject: 'success minion {id} on host {host}'
smtp_failure_subject: 'failure minion {id} on host {host}'
smtp_server: smtp.example.com
smtp_port: 25
smtp_tls: False
smtp_username: username
smtp_password: password
smtp_recipients: [email protected], [email protected]
smtp_sender: [email protected]
The *report_failures*, *report_changes*, and *report_everything* flags provide
filtering of the results. If you want an email to be sent every time, then
*report_everything* is your choice. If you want to be notified only when
changes were successfully made use *report_changes*. And *report_failures* will
generate an email if there were failures.
The configuration allows you to run a salt module function in case of
success (*success_function*) or failure (*failure_function*).
Any salt function, including ones defined in the _module folder of your salt
repo, could be used here and its output will be displayed under the 'extra'
heading of the email.
Supported values for *report_format* are html, json, and yaml. The latter two
are typically used for debugging purposes, but could be used for applying
a template at some later stage.
The values for *report_delivery* are smtp or file. In case of file delivery
the only other applicable option is *file_output*.
In case of smtp delivery, smtp_* options demonstrated by the example above
could be used to customize the email.
As you might have noticed, the success and failure subjects contain {id} and {host}
values. Any other grain name could be used. As opposed to using
{{grains['id']}}, which will be rendered by the master and contain master's
values at the time of pillar generation, these will contain minion values at
the time of execution.
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import smtplib
import cgi
from email.mime.text import MIMEText
from salt.ext.six.moves import range
from salt.ext.six.moves import StringIO
from salt.ext import six
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.utils.yaml
import salt.returners
log = logging.getLogger(__name__)
__virtualname__ = 'highstate'
def __virtual__():
'''
Return our name
'''
return __virtualname__
def _get_options(ret):
'''
Return options
'''
attrs = {
'report_everything': 'report_everything',
'report_changes': 'report_changes',
'report_failures': 'report_failures',
'failure_function': 'failure_function',
'success_function': 'success_function',
'report_format': 'report_format',
'report_delivery': 'report_delivery',
'file_output': 'file_output',
'smtp_sender': 'smtp_sender',
'smtp_recipients': 'smtp_recipients',
'smtp_failure_subject': 'smtp_failure_subject',
'smtp_success_subject': 'smtp_success_subject',
'smtp_server': 'smtp_server',
'smtp_port': 'smtp_port',
'smtp_tls': 'smtp_tls',
'smtp_username': 'smtp_username',
'smtp_password': 'smtp_password'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
#
# Most email readers to not support <style> tag.
# The following dict and a function provide a primitive styler
# sufficient for our needs.
#
_STYLES = {
'_table': 'border-collapse:collapse;width:100%;',
'_td': 'vertical-align:top;'
'font-family:Helvetica,Arial,sans-serif;font-size:9pt;',
'unchanged': 'color:blue;',
'changed': 'color:green',
'failed': 'color:red;',
'first': 'border-top:0;border-left:1px solid #9e9e9e;',
'first_first': 'border-top:0;border-left:0;',
'notfirst_first': 'border-left:0;border-top:1px solid #9e9e9e;',
'other': 'border-top:1px solid #9e9e9e;border-left:1px solid #9e9e9e;',
'name': 'width:70pt;',
'container': 'padding:0;'
}
def _lookup_style(element, names):
'''
Lookup style by either element name or the list of classes
'''
return _STYLES.get('_'+element, '') + \
''.join([_STYLES.get(name, '') for name in names])
def _generate_html_table(data, out, level=0, extra_style=''):
'''
Generate a single table of data
'''
print('<table style="{0}">'.format(
_lookup_style('table', ['table' + six.text_type(level)])), file=out)
firstone = True
row_style = 'row' + six.text_type(level)
cell_style = 'cell' + six.text_type(level)
for subdata in data:
first_style = 'first_first' if firstone else 'notfirst_first'
second_style = 'first' if firstone else 'other'
if isinstance(subdata, dict):
if '__style__' in subdata:
new_extra_style = subdata['__style__']
del subdata['__style__']
else:
new_extra_style = extra_style
if len(subdata) == 1:
name, value = next(six.iteritems(subdata))
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'name', new_extra_style]
),
name
), file=out)
if isinstance(value, list):
print('<td style="{0}">'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'container',
new_extra_style
]
)
), file=out)
_generate_html_table(
value,
out,
level + 1,
new_extra_style
)
print('</td>', file=out)
else:
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[
cell_style,
second_style,
'value',
new_extra_style
]
),
cgi.escape(six.text_type(value))
), file=out)
print('</tr>', file=out)
elif isinstance(subdata, list):
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">'.format(
_lookup_style(
'td',
[cell_style, first_style, 'container', extra_style]
)
), file=out)
_generate_html_table(subdata, out, level + 1, extra_style)
print('</td>', file=out)
print('</tr>', file=out)
else:
print('<tr style="{0}">'.format(
_lookup_style('tr', [row_style])
), file=out)
print('<td style="{0}">{1}</td>'.format(
_lookup_style(
'td',
[cell_style, first_style, 'value', extra_style]
),
cgi.escape(six.text_type(subdata))
), file=out)
print('</tr>', file=out)
firstone = False
print('</table>', file=out)
def _generate_html(data, out):
'''
Generate report data as HTML
'''
print('<html>', file=out)
print('<body>', file=out)
_generate_html_table(data, out, 0)
print('</body>', file=out)
print('</html>', file=out)
def _dict_to_name_value(data):
'''
Convert a dictionary to a list of dictionaries to facilitate ordering
'''
if isinstance(data, dict):
sorted_data = sorted(data.items(), key=lambda s: s[0])
result = []
for name, value in sorted_data:
if isinstance(value, dict):
result.append({name: _dict_to_name_value(value)})
else:
result.append({name: value})
else:
result = data
return result
def _generate_states_report(sorted_data):
'''
Generate states report
'''
states = []
for state, data in sorted_data:
module, stateid, name, function = state.split('_|-')
module_function = '.'.join((module, function))
result = data.get('result', '')
single = [
{'function': module_function},
{'name': name},
{'result': result},
{'duration': data.get('duration', 0.0)},
{'comment': data.get('comment', '')}
]
if not result:
style = 'failed'
else:
changes = data.get('changes', {})
if changes and isinstance(changes, dict):
single.append({'changes': _dict_to_name_value(changes)})
style = 'changed'
else:
style = 'unchanged'
started = data.get('start_time', '')
if started:
single.append({'started': started})
states.append({stateid: single, '__style__': style})
return states
def _generate_report(ret, setup):
'''
Generate report dictionary
'''
retdata = ret.get('return', {})
sorted_data = sorted(
retdata.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
# gather stats
for _, data in sorted_data:
if not data.get('result', True):
failed += 1
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
if data.get('changes', {}):
changed += 1
unchanged = total - failed - changed
log.debug('highstate total: %s', total)
log.debug('highstate failed: %s', failed)
log.debug('highstate unchanged: %s', unchanged)
log.debug('highstate changed: %s', changed)
# generate report if required
if setup.get('report_everything', False) or \
(setup.get('report_changes', True) and changed != 0) or \
(setup.get('report_failures', True) and failed != 0):
report = [
{'stats': [
{'total': total},
{'failed': failed, '__style__': 'failed'},
{'unchanged': unchanged, '__style__': 'unchanged'},
{'changed': changed, '__style__': 'changed'},
{'duration': duration}
]},
{'job': [
{'function': ret.get('fun', '')},
{'arguments': ret.get('fun_args', '')},
{'jid': ret.get('jid', '')},
{'success': ret.get('success', True)},
{'retcode': ret.get('retcode', 0)}
]},
{'states': _generate_states_report(sorted_data)}
]
if failed:
function = setup.get('failure_function', None)
else:
function = setup.get('success_function', None)
if function:
func_result = __salt__[function]()
report.insert(
0,
{'extra': [{function: _dict_to_name_value(func_result)}]}
)
else:
report = []
return report, failed
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def _produce_output(report, failed, setup):
'''
Produce output from the report dictionary generated by _generate_report
'''
report_format = setup.get('report_format', 'yaml')
log.debug('highstate output format: %s', report_format)
if report_format == 'json':
report_text = salt.utils.json.dumps(report)
elif report_format == 'yaml':
string_file = StringIO()
salt.utils.yaml.safe_dump(report, string_file, default_flow_style=False)
string_file.seek(0)
report_text = string_file.read()
else:
string_file = StringIO()
_generate_html(report, string_file)
string_file.seek(0)
report_text = string_file.read()
report_delivery = setup.get('report_delivery', 'file')
log.debug('highstate report_delivery: %s', report_delivery)
if report_delivery == 'file':
output_file = _sprinkle(setup.get('file_output', '/tmp/test.rpt'))
with salt.utils.files.fopen(output_file, 'w') as out:
out.write(salt.utils.stringutils.to_str(report_text))
else:
msg = MIMEText(report_text, report_format)
sender = setup.get('smtp_sender', '')
recipients = setup.get('smtp_recipients', '')
host = setup.get('smtp_server', '')
port = int(setup.get('smtp_port', 25))
tls = setup.get('smtp_tls')
username = setup.get('smtp_username')
password = setup.get('smtp_password')
if failed:
subject = setup.get('smtp_failure_subject', 'Installation failure')
else:
subject = setup.get('smtp_success_subject', 'Installation success')
subject = _sprinkle(subject)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
log.debug('highstate smtp port: %d', port)
smtp = smtplib.SMTP(host=host, port=port)
if tls is True:
smtp.starttls()
log.debug('highstate smtp tls enabled')
if username and password:
smtp.login(username, password)
log.debug('highstate smtp authenticated')
smtp.sendmail(
sender,
[x.strip() for x in recipients.split(',')], msg.as_string())
log.debug('highstate message sent.')
smtp.quit()
def __test_html():
'''
HTML generation test only used when called from the command line:
python ./highstate.py
Typical options for generating the report file:
highstate:
report_format: yaml
report_delivery: file
file_output: '/srv/salt/_returners/test.rpt'
'''
with salt.utils.files.fopen('test.rpt', 'r') as input_file:
data_text = salt.utils.stringutils.to_unicode(input_file.read())
data = salt.utils.yaml.safe_load(data_text)
string_file = StringIO()
_generate_html(data, string_file)
string_file.seek(0)
result = string_file.read()
with salt.utils.files.fopen('test.html', 'w') as output:
output.write(salt.utils.stringutils.to_str(result))
if __name__ == '__main__':
__test_html()
|
saltstack/salt | salt/modules/out.py | out_format | python | def out_format(data, out='nested', opts=None, **kwargs):
'''
Return the formatted outputter string for the Python object.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.out_format "{'key': 'value'}"
'''
if not opts:
opts = __opts__
return salt.output.out_format(data, out, opts=opts, **kwargs) | Return the formatted outputter string for the Python object.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.out_format "{'key': 'value'}" | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/out.py#L37-L61 | [
"def out_format(data, out, opts=None, **kwargs):\n '''\n Return the formatted outputter string for the passed data\n '''\n return try_printout(data, out, opts, **kwargs)\n"
] | # -*- coding: utf-8 -*-
'''
Output Module
=============
.. versionadded:: 2018.3.0
Execution module that processes JSON serializable data
and returns string having the format as processed by the outputters.
Although this does not bring much value on the CLI, it turns very handy
in applications that require human readable data rather than Python objects.
For example, inside a Jinja template:
.. code-block:: jinja
{{ salt.out.string_format(complex_object, out='highstate') }}
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
log = logging.getLogger(__name__)
# Import salt modules
import salt.output
__virtualname__ = 'out'
__proxyenabled__ = ['*']
def __virtual__():
return __virtualname__
def string_format(data, out='nested', opts=None, **kwargs):
'''
Return the outputter formatted string, removing the ANSI escape sequences.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.string_format "{'key': 'value'}" out=table
'''
if not opts:
opts = __opts__
return salt.output.string_format(data, out, opts=opts, **kwargs)
def html_format(data, out='nested', opts=None, **kwargs):
'''
Return the formatted string as HTML.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.html_format "{'key': 'value'}" out=yaml
'''
if not opts:
opts = __opts__
return salt.output.html_format(data, out, opts=opts, **kwargs)
|
saltstack/salt | salt/modules/out.py | string_format | python | def string_format(data, out='nested', opts=None, **kwargs):
'''
Return the outputter formatted string, removing the ANSI escape sequences.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.string_format "{'key': 'value'}" out=table
'''
if not opts:
opts = __opts__
return salt.output.string_format(data, out, opts=opts, **kwargs) | Return the outputter formatted string, removing the ANSI escape sequences.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.string_format "{'key': 'value'}" out=table | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/out.py#L64-L88 | [
"def string_format(data, out, opts=None, **kwargs):\n '''\n Return the formatted outputter string, removing the ANSI escape sequences.\n '''\n raw_output = try_printout(data, out, opts, **kwargs)\n ansi_escape = re.compile(r'\\x1b[^m]*m')\n return ansi_escape.sub('', raw_output)\n"
] | # -*- coding: utf-8 -*-
'''
Output Module
=============
.. versionadded:: 2018.3.0
Execution module that processes JSON serializable data
and returns string having the format as processed by the outputters.
Although this does not bring much value on the CLI, it turns very handy
in applications that require human readable data rather than Python objects.
For example, inside a Jinja template:
.. code-block:: jinja
{{ salt.out.string_format(complex_object, out='highstate') }}
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
log = logging.getLogger(__name__)
# Import salt modules
import salt.output
__virtualname__ = 'out'
__proxyenabled__ = ['*']
def __virtual__():
return __virtualname__
def out_format(data, out='nested', opts=None, **kwargs):
'''
Return the formatted outputter string for the Python object.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.out_format "{'key': 'value'}"
'''
if not opts:
opts = __opts__
return salt.output.out_format(data, out, opts=opts, **kwargs)
def html_format(data, out='nested', opts=None, **kwargs):
'''
Return the formatted string as HTML.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.html_format "{'key': 'value'}" out=yaml
'''
if not opts:
opts = __opts__
return salt.output.html_format(data, out, opts=opts, **kwargs)
|
saltstack/salt | salt/modules/out.py | html_format | python | def html_format(data, out='nested', opts=None, **kwargs):
'''
Return the formatted string as HTML.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.html_format "{'key': 'value'}" out=yaml
'''
if not opts:
opts = __opts__
return salt.output.html_format(data, out, opts=opts, **kwargs) | Return the formatted string as HTML.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.html_format "{'key': 'value'}" out=yaml | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/out.py#L91-L115 | [
"def html_format(data, out, opts=None, **kwargs):\n '''\n Return the formatted string as HTML.\n '''\n ansi_escaped_string = string_format(data, out, opts, **kwargs)\n return ansi_escaped_string.replace(' ', ' ').replace('\\n', '<br />')\n"
] | # -*- coding: utf-8 -*-
'''
Output Module
=============
.. versionadded:: 2018.3.0
Execution module that processes JSON serializable data
and returns string having the format as processed by the outputters.
Although this does not bring much value on the CLI, it turns very handy
in applications that require human readable data rather than Python objects.
For example, inside a Jinja template:
.. code-block:: jinja
{{ salt.out.string_format(complex_object, out='highstate') }}
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
log = logging.getLogger(__name__)
# Import salt modules
import salt.output
__virtualname__ = 'out'
__proxyenabled__ = ['*']
def __virtual__():
return __virtualname__
def out_format(data, out='nested', opts=None, **kwargs):
'''
Return the formatted outputter string for the Python object.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.out_format "{'key': 'value'}"
'''
if not opts:
opts = __opts__
return salt.output.out_format(data, out, opts=opts, **kwargs)
def string_format(data, out='nested', opts=None, **kwargs):
'''
Return the outputter formatted string, removing the ANSI escape sequences.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments to sent to the outputter module.
CLI Example:
.. code-block:: bash
salt '*' out.string_format "{'key': 'value'}" out=table
'''
if not opts:
opts = __opts__
return salt.output.string_format(data, out, opts=opts, **kwargs)
|
saltstack/salt | salt/states/zcbuildout.py | installed | python | def installed(name,
config='buildout.cfg',
quiet=False,
parts=None,
user=None,
env=(),
buildout_ver=None,
test_release=False,
distribute=None,
new_st=None,
offline=False,
newest=False,
python=sys.executable,
debug=False,
verbose=False,
unless=None,
onlyif=None,
use_vt=False,
loglevel='debug',
**kwargs):
'''
Install buildout in a specific directory
It is a thin wrapper to modules.buildout.buildout
name
directory to execute in
quiet
do not output console & logs
config
buildout config to use (default: buildout.cfg)
parts
specific buildout parts to run
user
user used to run buildout as
.. versionadded:: 2014.1.4
env
environment variables to set when running
buildout_ver
force a specific buildout version (1 | 2)
test_release
buildout accept test release
new_st
Forcing use of setuptools >= 0.7
distribute
use distribute over setuptools if possible
offline
does buildout run offline
python
python to use
debug
run buildout with -D debug flag
onlyif
Only execute cmd if statement on the host return 0
unless
Do not execute cmd if statement on the host return 0
newest
run buildout in newest mode
verbose
run buildout in verbose mode (-vvvvv)
use_vt
Use the new salt VT to stream output [experimental]
loglevel
loglevel for buildout commands
'''
ret = {}
if 'group' in kwargs:
log.warning("Passing 'group' is deprecated, just remove it")
output_loglevel = kwargs.get('output_loglevel', None)
if output_loglevel and not loglevel:
log.warning("Passing 'output_loglevel' is deprecated,"
' please use loglevel instead')
try:
test_release = int(test_release)
except ValueError:
test_release = None
func = __salt('buildout.buildout')
kwargs = dict(
directory=name,
config=config,
parts=parts,
runas=user,
env=env,
buildout_ver=buildout_ver,
test_release=test_release,
distribute=distribute,
new_st=new_st,
offline=offline,
newest=newest,
python=python,
debug=debug,
verbose=verbose,
onlyif=onlyif,
unless=unless,
use_vt=use_vt,
loglevel=loglevel
)
ret.update(_ret_status(func(**kwargs), name, quiet=quiet))
return ret | Install buildout in a specific directory
It is a thin wrapper to modules.buildout.buildout
name
directory to execute in
quiet
do not output console & logs
config
buildout config to use (default: buildout.cfg)
parts
specific buildout parts to run
user
user used to run buildout as
.. versionadded:: 2014.1.4
env
environment variables to set when running
buildout_ver
force a specific buildout version (1 | 2)
test_release
buildout accept test release
new_st
Forcing use of setuptools >= 0.7
distribute
use distribute over setuptools if possible
offline
does buildout run offline
python
python to use
debug
run buildout with -D debug flag
onlyif
Only execute cmd if statement on the host return 0
unless
Do not execute cmd if statement on the host return 0
newest
run buildout in newest mode
verbose
run buildout in verbose mode (-vvvvv)
use_vt
Use the new salt VT to stream output [experimental]
loglevel
loglevel for buildout commands | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zcbuildout.py#L121-L241 | [
"def __salt(fn):\n if fn not in FN_CACHE:\n FN_CACHE[fn] = __salt__[fn]\n return FN_CACHE[fn]\n",
"def _ret_status(exec_status=None,\n name='',\n comment='',\n result=None,\n quiet=False,\n changes=None):\n if not changes:\n changes = {}\n if exec_status is None:\n exec_status = {}\n if exec_status:\n if result is None:\n result = exec_status['status']\n scomment = exec_status.get('comment', None)\n if scomment:\n comment += '\\n' + scomment\n out = exec_status.get('out', '')\n if not quiet:\n if out:\n if isinstance(out, string_types):\n comment += '\\n' + out\n outlog = exec_status.get('outlog', None)\n if outlog:\n if isinstance(outlog, string_types):\n comment += '\\n' + outlog\n return {\n 'changes': changes,\n 'result': result,\n 'name': name,\n 'comment': comment,\n }\n"
] | # -*- coding: utf-8 -*-
'''
Management of zc.buildout
=========================
This module is inspired from minitage's buildout maker
(https://github.com/minitage/minitage/blob/master/src/minitage/core/makers/buildout.py)
.. versionadded:: 2016.3.0
.. note::
This state module is beta; the API is subject to change and no promise
as to performance or functionality is yet present
Available Functions
-------------------
- built
.. code-block:: yaml
installed1
buildout.installed:
- name: /path/to/buildout
installed2
buildout.installed:
- name: /path/to/buildout
- parts:
- a
- b
- python: /path/to/pythonpath/bin/python
- unless: /bin/test_something_installed
- onlyif: /bin/test_else_installed
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import sys
# Import salt libs
from salt.ext.six import string_types
# Define the module's virtual name
__virtualname__ = 'buildout'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if zc.buildout libs available
'''
return __virtualname__
INVALID_RESPONSE = 'We did not get any expectable answer from docker'
VALID_RESPONSE = ''
NOTSET = object()
MAPPING_CACHE = {}
FN_CACHE = {}
def __salt(fn):
if fn not in FN_CACHE:
FN_CACHE[fn] = __salt__[fn]
return FN_CACHE[fn]
def _ret_status(exec_status=None,
name='',
comment='',
result=None,
quiet=False,
changes=None):
if not changes:
changes = {}
if exec_status is None:
exec_status = {}
if exec_status:
if result is None:
result = exec_status['status']
scomment = exec_status.get('comment', None)
if scomment:
comment += '\n' + scomment
out = exec_status.get('out', '')
if not quiet:
if out:
if isinstance(out, string_types):
comment += '\n' + out
outlog = exec_status.get('outlog', None)
if outlog:
if isinstance(outlog, string_types):
comment += '\n' + outlog
return {
'changes': changes,
'result': result,
'name': name,
'comment': comment,
}
def _valid(exec_status=None, name='', comment='', changes=None):
return _ret_status(exec_status=exec_status,
comment=comment,
name=name,
changes=changes,
result=True)
def _invalid(exec_status=None, name='', comment='', changes=None):
return _ret_status(exec_status=exec_status,
comment=comment,
name=name,
changes=changes,
result=False)
|
saltstack/salt | salt/modules/dummyproxy_pkg.py | version | python | def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
if len(names) == 1:
vers = __proxy__['dummy.package_status'](names[0])
return vers[names[0]]
else:
results = {}
for n in names:
vers = __proxy__['dummy.package_status'](n)
results.update(vers)
return results | Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ... | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dummyproxy_pkg.py#L55-L76 | null | # -*- coding: utf-8 -*-
'''
Package support for the dummy proxy used by the test suite
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import salt.utils.data
import salt.utils.platform
from salt.ext import six
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Only work on systems that are a proxy minion
'''
try:
if salt.utils.platform.is_proxy() \
and __opts__['proxy']['proxytype'] == 'dummy':
return __virtualname__
except KeyError:
return (
False,
'The dummyproxy_package execution module failed to load. Check '
'the proxy key in pillar or /etc/salt/proxy.'
)
return (
False,
'The dummyproxy_package execution module failed to load: only works '
'on a dummy proxy minion.'
)
def list_pkgs(versions_as_list=False, **kwargs):
return __proxy__['dummy.package_list']()
def install(name=None, refresh=False, fromrepo=None,
pkgs=None, sources=None, **kwargs):
return __proxy__['dummy.package_install'](name, **kwargs)
def remove(name=None, pkgs=None, **kwargs):
return __proxy__['dummy.package_remove'](name)
def upgrade(name=None, pkgs=None, refresh=True, skip_verify=True,
normalize=True, **kwargs):
old = __proxy__['dummy.package_list']()
new = __proxy__['dummy.uptodate']()
pkg_installed = __proxy__['dummy.upgrade']()
ret = salt.utils.data.compare_dicts(old, pkg_installed)
return ret
def installed(name,
version=None,
refresh=False,
fromrepo=None,
skip_verify=False,
pkgs=None,
sources=None,
**kwargs):
p = __proxy__['dummy.package_status'](name)
if version is None:
if 'ret' in p:
return six.text_type(p['ret'])
else:
return True
else:
if p is not None:
return version == six.text_type(p)
|
saltstack/salt | salt/platform/win.py | set_user_perm | python | def set_user_perm(obj, perm, sid):
'''
Set an object permission for the given user sid
'''
info = (
win32security.OWNER_SECURITY_INFORMATION |
win32security.GROUP_SECURITY_INFORMATION |
win32security.DACL_SECURITY_INFORMATION
)
sd = win32security.GetUserObjectSecurity(obj, info)
dacl = sd.GetSecurityDescriptorDacl()
ace_cnt = dacl.GetAceCount()
found = False
for idx in range(0, ace_cnt):
(aceType, aceFlags), ace_mask, ace_sid = dacl.GetAce(idx)
ace_exists = (
aceType == ntsecuritycon.ACCESS_ALLOWED_ACE_TYPE and
ace_mask == perm and
ace_sid == sid
)
if ace_exists:
# If the ace already exists, do nothing
break
else:
dacl.AddAccessAllowedAce(dacl.GetAclRevision(), perm, sid)
sd.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetUserObjectSecurity(obj, info, sd) | Set an object permission for the given user sid | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/platform/win.py#L972-L998 | null | # -*- coding: utf-8 -*-
'''
Windows specific utility functions, this module should be imported in a try,
except block because it is only applicable on Windows platforms.
Much of what is here was adapted from the following:
https://stackoverflow.com/a/43233332
http://stackoverflow.com/questions/29566330
'''
from __future__ import absolute_import, unicode_literals
import os
import collections
import logging
import psutil
import ctypes
from ctypes import wintypes
from salt.ext.six.moves import range
from salt.ext.six.moves import zip
import win32con
import win32con
import win32api
import win32process
import win32security
import win32service
import ntsecuritycon
# Set up logging
log = logging.getLogger(__name__)
ntdll = ctypes.WinDLL('ntdll')
secur32 = ctypes.WinDLL('secur32')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
advapi32 = ctypes.WinDLL('advapi32', use_last_error=True)
userenv = ctypes.WinDLL('userenv', use_last_error=True)
SYSTEM_SID = "S-1-5-18"
LOCAL_SRV_SID = "S-1-5-19"
NETWORK_SRV_SID = "S-1-5-19"
LOGON_WITH_PROFILE = 0x00000001
WINSTA_ALL = (
win32con.WINSTA_ACCESSCLIPBOARD |
win32con.WINSTA_ACCESSGLOBALATOMS |
win32con.WINSTA_CREATEDESKTOP |
win32con.WINSTA_ENUMDESKTOPS |
win32con.WINSTA_ENUMERATE |
win32con.WINSTA_EXITWINDOWS |
win32con.WINSTA_READATTRIBUTES |
win32con.WINSTA_READSCREEN |
win32con.WINSTA_WRITEATTRIBUTES |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
DESKTOP_ALL = (
win32con.DESKTOP_CREATEMENU |
win32con.DESKTOP_CREATEWINDOW |
win32con.DESKTOP_ENUMERATE |
win32con.DESKTOP_HOOKCONTROL |
win32con.DESKTOP_JOURNALPLAYBACK |
win32con.DESKTOP_JOURNALRECORD |
win32con.DESKTOP_READOBJECTS |
win32con.DESKTOP_SWITCHDESKTOP |
win32con.DESKTOP_WRITEOBJECTS |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
MAX_COMPUTER_NAME_LENGTH = 15
SECURITY_LOGON_TYPE = wintypes.ULONG
Interactive = 2
Network = 3
Batch = 4
Service = 5
LOGON_SUBMIT_TYPE = wintypes.ULONG
PROFILE_BUFFER_TYPE = wintypes.ULONG
MsV1_0InteractiveLogon = 2
MsV1_0Lm20Logon = 3
MsV1_0NetworkLogon = 4
MsV1_0WorkstationUnlockLogon = 7
MsV1_0S4ULogon = 12
MsV1_0NoElevationLogon = 82
KerbInteractiveLogon = 2
KerbWorkstationUnlockLogon = 7
KerbS4ULogon = 12
MSV1_0_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_IDENTITY = 0x8
TOKEN_SOURCE_LENGTH = 8
NEGOTIATE_PACKAGE_NAME = b'Negotiate'
MICROSOFT_KERBEROS_NAME = b'Kerberos'
MSV1_0_PACKAGE_NAME = b'MICROSOFT_AUTHENTICATION_PACKAGE_V1_0'
DELETE = 0x00010000
READ_CONTROL = 0x00020000
WRITE_DAC = 0x00040000
WRITE_OWNER = 0x00080000
STANDARD_RIGHTS_REQUIRED = (
DELETE |
READ_CONTROL |
WRITE_DAC |
WRITE_OWNER
)
TOKEN_ASSIGN_PRIMARY = 0x0001
TOKEN_DUPLICATE = 0x0002
TOKEN_IMPERSONATE = 0x0004
TOKEN_QUERY = 0x0008
TOKEN_QUERY_SOURCE = 0x0010
TOKEN_ADJUST_PRIVILEGES = 0x0020
TOKEN_ADJUST_GROUPS = 0x0040
TOKEN_ADJUST_DEFAULT = 0x0080
TOKEN_ADJUST_SESSIONID = 0x0100
TOKEN_ALL_ACCESS = (
STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE |
TOKEN_IMPERSONATE |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID
)
DUPLICATE_CLOSE_SOURCE = 0x00000001
DUPLICATE_SAME_ACCESS = 0x00000002
TOKEN_TYPE = wintypes.ULONG
TokenPrimary = 1
TokenImpersonation = 2
SECURITY_IMPERSONATION_LEVEL = wintypes.ULONG
SecurityAnonymous = 0
SecurityIdentification = 1
SecurityImpersonation = 2
SecurityDelegation = 3
class NTSTATUS(wintypes.LONG):
def to_error(self):
return ntdll.RtlNtStatusToDosError(self)
def __repr__(self):
name = self.__class__.__name__
status = wintypes.ULONG.from_buffer(self)
return '{}({})'.format(name, status.value)
PNTSTATUS = ctypes.POINTER(NTSTATUS)
class BOOL(wintypes.BOOL):
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, bool(self))
class HANDLE(wintypes.HANDLE):
__slots__ = 'closed',
def __int__(self):
return self.value or 0
def Detach(self):
if not getattr(self, 'closed', False):
self.closed = True
value = int(self)
self.value = None
return value
raise ValueError("already closed")
def Close(self, CloseHandle=kernel32.CloseHandle):
if self and not getattr(self, 'closed', False):
CloseHandle(self.Detach())
__del__ = Close
def __repr__(self):
return "{}({})".format(self.__class__.__name__, int(self))
class LARGE_INTEGER(wintypes.LARGE_INTEGER):
# https://msdn.microsoft.com/en-us/library/ff553204
ntdll.RtlSecondsSince1970ToTime.restype = None
_unix_epoch = wintypes.LARGE_INTEGER()
ntdll.RtlSecondsSince1970ToTime(0, ctypes.byref(_unix_epoch))
_unix_epoch = _unix_epoch.value
def __int__(self):
return self.value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, self.value)
def as_time(self):
time100ns = self.value - self._unix_epoch
if time100ns >= 0:
return time100ns / 1e7
raise ValueError('value predates the Unix epoch')
@classmethod
def from_time(cls, t):
time100ns = int(t * 10**7)
return cls(time100ns + cls._unix_epoch)
CHAR = ctypes.c_char
WCHAR = ctypes.c_wchar
PCHAR = ctypes.POINTER(CHAR)
PWCHAR = ctypes.POINTER(WCHAR)
class STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PCHAR),
)
LPSTRING = ctypes.POINTER(STRING)
class UNICODE_STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PWCHAR),
)
LPUNICODE_STRING = ctypes.POINTER(UNICODE_STRING)
class LUID(ctypes.Structure):
_fields_ = (
('LowPart', wintypes.DWORD),
('HighPart', wintypes.LONG),
)
def __new__(cls, value=0):
return cls.from_buffer_copy(ctypes.c_ulonglong(value))
def __int__(self):
return ctypes.c_ulonglong.from_buffer(self).value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, int(self))
LPLUID = ctypes.POINTER(LUID)
PSID = wintypes.LPVOID
class SID_AND_ATTRIBUTES(ctypes.Structure):
_fields_ = (
('Sid', PSID),
('Attributes', wintypes.DWORD),
)
LPSID_AND_ATTRIBUTES = ctypes.POINTER(SID_AND_ATTRIBUTES)
class TOKEN_GROUPS(ctypes.Structure):
_fields_ = (
('GroupCount', wintypes.DWORD),
('Groups', SID_AND_ATTRIBUTES * 1),
)
LPTOKEN_GROUPS = ctypes.POINTER(TOKEN_GROUPS)
class TOKEN_SOURCE(ctypes.Structure):
_fields_ = (
('SourceName', CHAR * TOKEN_SOURCE_LENGTH),
('SourceIdentifier', LUID),
)
def __init__(self, SourceName=None, SourceIdentifier=None):
super(TOKEN_SOURCE, self).__init__()
if SourceName is not None:
if not isinstance(SourceName, bytes):
SourceName = SourceName.encode('mbcs')
self.SourceName = SourceName
if SourceIdentifier is None:
luid = self.SourceIdentifier # pylint: disable=access-member-before-definition
ntdll.NtAllocateLocallyUniqueId(ctypes.byref(luid))
else:
self.SourceIdentifier = SourceIdentifier
LPTOKEN_SOURCE = ctypes.POINTER(TOKEN_SOURCE)
py_source_context = TOKEN_SOURCE(b"PYTHON ")
py_origin_name = __name__.encode()
py_logon_process_name = "{}-{}".format(py_origin_name, os.getpid())
SIZE_T = ctypes.c_size_t
class QUOTA_LIMITS(ctypes.Structure):
_fields_ = (('PagedPoolLimit', SIZE_T),
('NonPagedPoolLimit', SIZE_T),
('MinimumWorkingSetSize', SIZE_T),
('MaximumWorkingSetSize', SIZE_T),
('PagefileLimit', SIZE_T),
('TimeLimit', wintypes.LARGE_INTEGER))
LPQUOTA_LIMITS = ctypes.POINTER(QUOTA_LIMITS)
LPULONG = ctypes.POINTER(wintypes.ULONG)
LSA_OPERATIONAL_MODE = wintypes.ULONG
LPLSA_OPERATIONAL_MODE = LPULONG
LPHANDLE = ctypes.POINTER(wintypes.HANDLE)
LPLPVOID = ctypes.POINTER(wintypes.LPVOID)
LPDWORD = ctypes.POINTER(wintypes.DWORD)
class ContiguousUnicode(ctypes.Structure):
# _string_names_: sequence matched to underscore-prefixed fields
def __init__(self, *args, **kwargs):
super(ContiguousUnicode, self).__init__(*args, **kwargs)
def _get_unicode_string(self, name):
wchar_size = ctypes.sizeof(WCHAR)
s = getattr(self, '_{}'.format(name))
length = s.Length // wchar_size
buf = s.Buffer
if buf:
return buf[:length]
return None
def _set_unicode_buffer(self, values):
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
bufsize = (len('\x00'.join(values)) + 1) * wchar_size
ctypes.resize(self, ctypes.sizeof(cls) + bufsize)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for value in values:
bufsize = (len(value) + 1) * wchar_size
ctypes.memmove(addr, value, bufsize)
addr += bufsize
def _set_unicode_string(self, name, value):
values = []
for n in self._string_names_:
if n == name:
values.append(value or '')
else:
values.append(getattr(self, n) or '')
self._set_unicode_buffer(values)
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for n, v in zip(self._string_names_, values):
ptr = ctypes.cast(addr, PWCHAR)
ustr = getattr(self, '_{}'.format(n))
length = ustr.Length = len(v) * wchar_size
full_length = length + wchar_size
if ((n == name and value is None) or
(n != name and not (length or ustr.Buffer))):
ustr.Buffer = None
ustr.MaximumLength = 0
else:
ustr.Buffer = ptr
ustr.MaximumLength = full_length
addr += full_length
def __getattr__(self, name):
if name not in self._string_names_:
raise AttributeError
return self._get_unicode_string(name)
def __setattr__(self, name, value):
if name in self._string_names_:
self._set_unicode_string(name, value)
else:
super(ContiguousUnicode, self).__setattr__(name, value)
@classmethod
def from_address_copy(cls, address, size=None):
x = ctypes.Structure.__new__(cls)
if size is not None:
ctypes.resize(x, size)
ctypes.memmove(ctypes.byref(x), address, ctypes.sizeof(x))
delta = ctypes.addressof(x) - address
for n in cls._string_names_:
ustr = getattr(x, '_{}'.format(n))
addr = ctypes.c_void_p.from_buffer(ustr.Buffer)
if addr:
addr.value += delta
return x
class AuthInfo(ContiguousUnicode):
# _message_type_: from a logon-submit-type enumeration
def __init__(self):
super(AuthInfo, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_LOGON(AuthInfo):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = 'LogonDomainName', 'UserName', 'Password'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('_LogonDomainName', UNICODE_STRING),
('_UserName', UNICODE_STRING),
('_Password', UNICODE_STRING))
def __init__(self, UserName=None, Password=None, LogonDomainName=None):
super(MSV1_0_INTERACTIVE_LOGON, self).__init__()
if LogonDomainName is not None:
self.LogonDomainName = LogonDomainName
if UserName is not None:
self.UserName = UserName
if Password is not None:
self.Password = Password
class S4ULogon(AuthInfo):
_string_names_ = 'UserPrincipalName', 'DomainName'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('Flags', wintypes.ULONG),
('_UserPrincipalName', UNICODE_STRING),
('_DomainName', UNICODE_STRING))
def __init__(self, UserPrincipalName=None, DomainName=None, Flags=0):
super(S4ULogon, self).__init__()
self.Flags = Flags
if UserPrincipalName is not None:
self.UserPrincipalName = UserPrincipalName
if DomainName is not None:
self.DomainName = DomainName
class MSV1_0_S4U_LOGON(S4ULogon):
_message_type_ = MsV1_0S4ULogon
class KERB_S4U_LOGON(S4ULogon):
_message_type_ = KerbS4ULogon
PMSV1_0_S4U_LOGON = ctypes.POINTER(MSV1_0_S4U_LOGON)
PKERB_S4U_LOGON = ctypes.POINTER(KERB_S4U_LOGON)
class ProfileBuffer(ContiguousUnicode):
# _message_type_
def __init__(self):
super(ProfileBuffer, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_PROFILE(ProfileBuffer):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = ('LogonScript', 'HomeDirectory', 'FullName',
'ProfilePath', 'HomeDirectoryDrive', 'LogonServer')
_fields_ = (('MessageType', PROFILE_BUFFER_TYPE),
('LogonCount', wintypes.USHORT),
('BadPasswordCount', wintypes.USHORT),
('LogonTime', LARGE_INTEGER),
('LogoffTime', LARGE_INTEGER),
('KickOffTime', LARGE_INTEGER),
('PasswordLastSet', LARGE_INTEGER),
('PasswordCanChange', LARGE_INTEGER),
('PasswordMustChange', LARGE_INTEGER),
('_LogonScript', UNICODE_STRING),
('_HomeDirectory', UNICODE_STRING),
('_FullName', UNICODE_STRING),
('_ProfilePath', UNICODE_STRING),
('_HomeDirectoryDrive', UNICODE_STRING),
('_LogonServer', UNICODE_STRING),
('UserFlags', wintypes.ULONG))
def _check_status(result, func, args):
if result.value < 0:
raise ctypes.WinError(result.to_error())
return args
def _check_bool(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
INVALID_DWORD_VALUE = wintypes.DWORD(-1).value # ~WinAPI
INFINITE = INVALID_DWORD_VALUE
STD_INPUT_HANDLE = wintypes.DWORD(-10).value
STD_OUTPUT_HANDLE = wintypes.DWORD(-11).value
STD_ERROR_HANDLE = wintypes.DWORD(-12).value
class SECURITY_ATTRIBUTES(ctypes.Structure):
_fields_ = (('nLength', wintypes.DWORD),
('lpSecurityDescriptor', wintypes.LPVOID),
('bInheritHandle', wintypes.BOOL))
def __init__(self, **kwds):
self.nLength = ctypes.sizeof(self)
super(SECURITY_ATTRIBUTES, self).__init__(**kwds)
LPSECURITY_ATTRIBUTES = ctypes.POINTER(SECURITY_ATTRIBUTES)
LPBYTE = ctypes.POINTER(wintypes.BYTE)
LPHANDLE = PHANDLE = ctypes.POINTER(ctypes.c_void_p)
LPDWORD = ctypes.POINTER(ctypes.c_ulong)
class STARTUPINFO(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms686331"""
_fields_ = (('cb', wintypes.DWORD),
('lpReserved', wintypes.LPWSTR),
('lpDesktop', wintypes.LPWSTR),
('lpTitle', wintypes.LPWSTR),
('dwX', wintypes.DWORD),
('dwY', wintypes.DWORD),
('dwXSize', wintypes.DWORD),
('dwYSize', wintypes.DWORD),
('dwXCountChars', wintypes.DWORD),
('dwYCountChars', wintypes.DWORD),
('dwFillAttribute', wintypes.DWORD),
('dwFlags', wintypes.DWORD),
('wShowWindow', wintypes.WORD),
('cbReserved2', wintypes.WORD),
('lpReserved2', LPBYTE),
('hStdInput', wintypes.HANDLE),
('hStdOutput', wintypes.HANDLE),
('hStdError', wintypes.HANDLE))
def __init__(self, **kwds):
self.cb = ctypes.sizeof(self)
super(STARTUPINFO, self).__init__(**kwds)
LPSTARTUPINFO = ctypes.POINTER(STARTUPINFO)
class PROC_THREAD_ATTRIBUTE_LIST(ctypes.Structure):
pass
PPROC_THREAD_ATTRIBUTE_LIST = ctypes.POINTER(PROC_THREAD_ATTRIBUTE_LIST)
class STARTUPINFOEX(STARTUPINFO):
_fields_ = (('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST),)
LPSTARTUPINFOEX = ctypes.POINTER(STARTUPINFOEX)
class PROCESS_INFORMATION(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms684873"""
_fields_ = (('hProcess', wintypes.HANDLE),
('hThread', wintypes.HANDLE),
('dwProcessId', wintypes.DWORD),
('dwThreadId', wintypes.DWORD))
LPPROCESS_INFORMATION = ctypes.POINTER(PROCESS_INFORMATION)
class HANDLE_IHV(wintypes.HANDLE):
pass
def errcheck_ihv(result, func, args):
if result.value == INVALID_HANDLE_VALUE:
raise ctypes.WinError()
return result.value
class DWORD_IDV(wintypes.DWORD):
pass
def errcheck_idv(result, func, args):
if result.value == INVALID_DWORD_VALUE:
raise ctypes.WinError()
return result.value
def errcheck_bool(result, func, args):
if not result:
raise ctypes.WinError()
return args
def _win(func, restype, *argtypes):
func.restype = restype
func.argtypes = argtypes
if issubclass(restype, NTSTATUS):
func.errcheck = _check_status
elif issubclass(restype, BOOL):
func.errcheck = _check_bool
elif issubclass(restype, HANDLE_IHV):
func.errcheck = errcheck_ihv
elif issubclass(restype, DWORD_IDV):
func.errcheck = errcheck_idv
else:
func.errcheck = errcheck_bool
# https://msdn.microsoft.com/en-us/library/ms683231
_win(kernel32.GetStdHandle, HANDLE_IHV,
wintypes.DWORD) # _In_ nStdHandle
# https://msdn.microsoft.com/en-us/library/ms724211
_win(kernel32.CloseHandle, wintypes.BOOL,
wintypes.HANDLE) # _In_ hObject
# https://msdn.microsoft.com/en-us/library/ms724935
_win(kernel32.SetHandleInformation, wintypes.BOOL,
wintypes.HANDLE, # _In_ hObject
wintypes.DWORD, # _In_ dwMask
wintypes.DWORD) # _In_ dwFlags
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, wintypes.BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle,
wintypes.HANDLE, # _In_ hSourceHandle,
wintypes.HANDLE, # _In_ hTargetProcessHandle,
LPHANDLE, # _Out_ lpTargetHandle,
wintypes.DWORD, # _In_ dwDesiredAccess,
wintypes.BOOL, # _In_ bInheritHandle,
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms683189
_win(kernel32.GetExitCodeProcess, wintypes.BOOL,
wintypes.HANDLE, # _In_ hProcess,
LPDWORD) # _Out_ lpExitCode
# https://msdn.microsoft.com/en-us/library/aa365152
_win(kernel32.CreatePipe, wintypes.BOOL,
PHANDLE, # _Out_ hReadPipe,
PHANDLE, # _Out_ hWritePipe,
LPSECURITY_ATTRIBUTES, # _In_opt_ lpPipeAttributes,
wintypes.DWORD) # _In_ nSize
# https://msdn.microsoft.com/en-us/library/ms682431
#_win(advapi32.CreateProcessWithTokenW, wintypes.BOOL,
# PHANDLE, # _In_ lpUsername
# wintypes.DWORD, # _In_ dwLogonFlags
# wintypes.LPCWSTR, # _In_opt_ lpApplicationName
# wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
# wintypes.DWORD, # _In_ dwCreationFlags
# wintypes.LPVOID, # _In_opt_ lpEnvironment
# wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
# LPSTARTUPINFO, # _In_ lpStartupInfo
# LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms682431
_win(advapi32.CreateProcessWithLogonW, wintypes.BOOL,
wintypes.LPCWSTR, # _In_ lpUsername
wintypes.LPCWSTR, # _In_opt_ lpDomain
wintypes.LPCWSTR, # _In_ lpPassword
wintypes.DWORD, # _In_ dwLogonFlags
wintypes.LPCWSTR, # _In_opt_ lpApplicationName
wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
wintypes.DWORD, # _In_ dwCreationFlags
wintypes.LPCWSTR, # _In_opt_ lpEnvironment
wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
LPSTARTUPINFO, # _In_ lpStartupInfo
LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle
wintypes.HANDLE, # _In_ hSourceHandle
wintypes.HANDLE, # _In_ hTargetProcessHandle
LPHANDLE, # _Out_ lpTargetHandle
wintypes.DWORD, # _In_ dwDesiredAccess
wintypes.BOOL, # _In_ bInheritHandle
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms724295
_win(kernel32.GetComputerNameW, BOOL,
wintypes.LPWSTR, # _Out_ lpBuffer
LPDWORD) # _Inout_ lpnSize
# https://msdn.microsoft.com/en-us/library/aa379295
_win(advapi32.OpenProcessToken, BOOL,
wintypes.HANDLE, # _In_ ProcessHandle
wintypes.DWORD, # _In_ DesiredAccess
LPHANDLE) # _Out_ TokenHandle
# https://msdn.microsoft.com/en-us/library/aa446617
_win(advapi32.DuplicateTokenEx, BOOL,
wintypes.HANDLE, # _In_ hExistingToken
wintypes.DWORD, # _In_ dwDesiredAccess
LPSECURITY_ATTRIBUTES, # _In_opt_ lpTokenAttributes
SECURITY_IMPERSONATION_LEVEL, # _In_ ImpersonationLevel
TOKEN_TYPE, # _In_ TokenType
LPHANDLE) # _Out_ phNewToken
# https://msdn.microsoft.com/en-us/library/ff566415
_win(ntdll.NtAllocateLocallyUniqueId, NTSTATUS,
LPLUID) # _Out_ LUID
# https://msdn.microsoft.com/en-us/library/aa378279
_win(secur32.LsaFreeReturnBuffer, NTSTATUS,
wintypes.LPVOID,) # _In_ Buffer
# https://msdn.microsoft.com/en-us/library/aa378265
_win(secur32.LsaConnectUntrusted, NTSTATUS,
LPHANDLE,) # _Out_ LsaHandle
#https://msdn.microsoft.com/en-us/library/aa378318
_win(secur32.LsaRegisterLogonProcess, NTSTATUS,
LPSTRING, # _In_ LogonProcessName
LPHANDLE, # _Out_ LsaHandle
LPLSA_OPERATIONAL_MODE) # _Out_ SecurityMode
# https://msdn.microsoft.com/en-us/library/aa378269
_win(secur32.LsaDeregisterLogonProcess, NTSTATUS,
wintypes.HANDLE) # _In_ LsaHandle
# https://msdn.microsoft.com/en-us/library/aa378297
_win(secur32.LsaLookupAuthenticationPackage, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ PackageName
LPULONG) # _Out_ AuthenticationPackage
# https://msdn.microsoft.com/en-us/library/aa378292
_win(secur32.LsaLogonUser, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ OriginName
SECURITY_LOGON_TYPE, # _In_ LogonType
wintypes.ULONG, # _In_ AuthenticationPackage
wintypes.LPVOID, # _In_ AuthenticationInformation
wintypes.ULONG, # _In_ AuthenticationInformationLength
LPTOKEN_GROUPS, # _In_opt_ LocalGroups
LPTOKEN_SOURCE, # _In_ SourceContext
LPLPVOID, # _Out_ ProfileBuffer
LPULONG, # _Out_ ProfileBufferLength
LPLUID, # _Out_ LogonId
LPHANDLE, # _Out_ Token
LPQUOTA_LIMITS, # _Out_ Quotas
PNTSTATUS) # _Out_ SubStatus
def duplicate_token(source_token=None, access=TOKEN_ALL_ACCESS,
impersonation_level=SecurityImpersonation,
token_type=TokenPrimary, attributes=None):
close_source = False
if source_token is None:
close_source = True
source_token = HANDLE()
advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
TOKEN_ALL_ACCESS, ctypes.byref(source_token))
token = HANDLE()
try:
advapi32.DuplicateTokenEx(source_token, access, attributes,
impersonation_level, token_type, ctypes.byref(token))
finally:
if close_source:
source_token.Close()
return token
def lsa_connect_untrusted():
handle = wintypes.HANDLE()
secur32.LsaConnectUntrusted(ctypes.byref(handle))
return handle.value
def lsa_register_logon_process(logon_process_name):
if not isinstance(logon_process_name, bytes):
logon_process_name = logon_process_name.encode('mbcs')
logon_process_name = logon_process_name[:127]
buf = ctypes.create_string_buffer(logon_process_name, 128)
name = STRING(len(logon_process_name), len(buf), buf)
handle = wintypes.HANDLE()
mode = LSA_OPERATIONAL_MODE()
secur32.LsaRegisterLogonProcess(ctypes.byref(name),
ctypes.byref(handle), ctypes.byref(mode))
return handle.value
def lsa_lookup_authentication_package(lsa_handle, package_name):
if not isinstance(package_name, bytes):
package_name = package_name.encode('mbcs')
package_name = package_name[:127]
buf = ctypes.create_string_buffer(package_name)
name = STRING(len(package_name), len(buf), buf)
package = wintypes.ULONG()
secur32.LsaLookupAuthenticationPackage(lsa_handle, ctypes.byref(name),
ctypes.byref(package))
return package.value
LOGONINFO = collections.namedtuple('LOGONINFO', ('Token', 'LogonId',
'Profile', 'Quotas'))
def lsa_logon_user(auth_info, local_groups=None, origin_name=py_origin_name,
source_context=None, auth_package=None, logon_type=None,
lsa_handle=None):
if local_groups is None:
plocal_groups = LPTOKEN_GROUPS()
else:
plocal_groups = ctypes.byref(local_groups)
if source_context is None:
source_context = py_source_context
if not isinstance(origin_name, bytes):
origin_name = origin_name.encode('mbcs')
buf = ctypes.create_string_buffer(origin_name)
origin_name = STRING(len(origin_name), len(buf), buf)
if auth_package is None:
if isinstance(auth_info, MSV1_0_S4U_LOGON):
auth_package = NEGOTIATE_PACKAGE_NAME
elif isinstance(auth_info, KERB_S4U_LOGON):
auth_package = MICROSOFT_KERBEROS_NAME
else:
auth_package = MSV1_0_PACKAGE_NAME
if logon_type is None:
if isinstance(auth_info, S4ULogon):
logon_type = win32con.LOGON32_LOGON_NETWORK
else:
logon_type = Interactive
profile_buffer = wintypes.LPVOID()
profile_buffer_length = wintypes.ULONG()
profile = None
logonid = LUID()
htoken = HANDLE()
quotas = QUOTA_LIMITS()
substatus = NTSTATUS()
deregister = False
if lsa_handle is None:
lsa_handle = lsa_connect_untrusted()
deregister = True
try:
if isinstance(auth_package, (str, bytes)):
auth_package = lsa_lookup_authentication_package(lsa_handle,
auth_package)
try:
secur32.LsaLogonUser(lsa_handle, ctypes.byref(origin_name),
logon_type, auth_package, ctypes.byref(auth_info),
ctypes.sizeof(auth_info), plocal_groups,
ctypes.byref(source_context), ctypes.byref(profile_buffer),
ctypes.byref(profile_buffer_length), ctypes.byref(logonid),
ctypes.byref(htoken), ctypes.byref(quotas),
ctypes.byref(substatus))
except WindowsError: # pylint: disable=undefined-variable
if substatus.value:
raise ctypes.WinError(substatus.to_error())
raise
finally:
if profile_buffer:
address = profile_buffer.value
buftype = PROFILE_BUFFER_TYPE.from_address(address).value
if buftype == MsV1_0InteractiveLogon:
profile = MSV1_0_INTERACTIVE_PROFILE.from_address_copy(
address, profile_buffer_length.value)
secur32.LsaFreeReturnBuffer(address)
finally:
if deregister:
secur32.LsaDeregisterLogonProcess(lsa_handle)
return LOGONINFO(htoken, logonid, profile, quotas)
def logon_msv1(name, password, domain=None, local_groups=None,
origin_name=py_origin_name, source_context=None):
return lsa_logon_user(MSV1_0_INTERACTIVE_LOGON(name, password, domain),
local_groups, origin_name, source_context)
def logon_msv1_s4u(name, local_groups=None, origin_name=py_origin_name,
source_context=None):
domain = ctypes.create_unicode_buffer(MAX_COMPUTER_NAME_LENGTH + 1)
length = wintypes.DWORD(len(domain))
kernel32.GetComputerNameW(domain, ctypes.byref(length))
return lsa_logon_user(MSV1_0_S4U_LOGON(name, domain.value),
local_groups, origin_name, source_context)
def logon_kerb_s4u(name, realm=None, local_groups=None,
origin_name=py_origin_name,
source_context=None,
logon_process_name=py_logon_process_name):
lsa_handle = lsa_register_logon_process(logon_process_name)
try:
return lsa_logon_user(KERB_S4U_LOGON(name, realm),
local_groups, origin_name, source_context,
lsa_handle=lsa_handle)
finally:
secur32.LsaDeregisterLogonProcess(lsa_handle)
def DuplicateHandle(hsrc=kernel32.GetCurrentProcess(),
srchandle=kernel32.GetCurrentProcess(),
htgt=kernel32.GetCurrentProcess(),
access=0, inherit=False,
options=win32con.DUPLICATE_SAME_ACCESS):
tgthandle = wintypes.HANDLE()
kernel32.DuplicateHandle(hsrc, srchandle,
htgt, ctypes.byref(tgthandle),
access, inherit, options)
return tgthandle.value
def CreatePipe(inherit_read=False, inherit_write=False):
read, write = wintypes.HANDLE(), wintypes.HANDLE()
kernel32.CreatePipe(ctypes.byref(read), ctypes.byref(write), None, 0)
if inherit_read:
kernel32.SetHandleInformation(read, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
if inherit_write:
kernel32.SetHandleInformation(write, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
return read.value, write.value
def grant_winsta_and_desktop(th):
'''
Grant the token's user access to the current process's window station and
desktop.
'''
current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
# Add permissions for the sid to the current windows station and thread id.
# This prevents windows error 0xC0000142.
winsta = win32process.GetProcessWindowStation()
set_user_perm(winsta, WINSTA_ALL, current_sid)
desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId())
set_user_perm(desktop, DESKTOP_ALL, current_sid)
def environment_string(env):
senv = ''
for k, v in env.items():
senv += k + '=' + v + '\0'
senv += '\0'
return ctypes.create_unicode_buffer(senv)
def CreateProcessWithTokenW(token,
logonflags=0,
applicationname=None,
commandline=None,
creationflags=0,
environment=None,
currentdirectory=None,
startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
if currentdirectory is not None:
currentdirectory = ctypes.create_unicode_buffer(currentdirectory)
if environment:
environment = ctypes.pointer(
environment_string(environment)
)
process_info = PROCESS_INFORMATION()
ret = advapi32.CreateProcessWithTokenW(
token,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
if ret == 0:
winerr = win32api.GetLastError()
exc = WindowsError(win32api.FormatMessage(winerr)) # pylint: disable=undefined-variable
exc.winerror = winerr
raise exc
return process_info
def enumerate_tokens(sid=None, session_id=None, privs=None):
'''
Enumerate tokens from any existing processes that can be accessed.
Optionally filter by sid.
'''
for p in psutil.process_iter():
if p.pid == 0:
continue
try:
ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, p.pid)
except win32api.error as exc:
if exc.winerror == 5:
log.debug("Unable to OpenProcess pid=%d name=%s", p.pid, p.name())
continue
raise exc
try:
access = (
win32security.TOKEN_DUPLICATE |
win32security.TOKEN_QUERY |
win32security.TOKEN_IMPERSONATE |
win32security.TOKEN_ASSIGN_PRIMARY
)
th = win32security.OpenProcessToken(ph, access)
except Exception as exc:
log.debug("OpenProcessToken failed pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
try:
process_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
except Exception as exc:
log.exception("GetTokenInformation pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
proc_sid = win32security.ConvertSidToStringSid(process_sid)
if sid and sid != proc_sid:
log.debug("Token for pid does not match user sid: %s", sid)
continue
if session_id and win32security.GetTokenInformation(th, win32security.TokenSessionId) != session_id:
continue
def has_priv(tok, priv):
luid = win32security.LookupPrivilegeValue(None, priv)
for priv_luid, flags in win32security.GetTokenInformation(tok, win32security.TokenPrivileges):
if priv_luid == luid:
return True
return False
if privs:
has_all = True
for name in privs:
if not has_priv(th, name):
has_all = False
if not has_all:
continue
yield dup_token(th)
def impersonate_sid(sid, session_id=None, privs=None):
'''
Find an existing process token for the given sid and impersonate the token.
'''
for tok in enumerate_tokens(sid, session_id, privs):
tok = dup_token(tok)
elevate_token(tok)
if win32security.ImpersonateLoggedOnUser(tok) == 0:
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
return tok
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
def dup_token(th):
'''
duplicate the access token
'''
# TODO: is `duplicate_token` the same?
sec_attr = win32security.SECURITY_ATTRIBUTES()
sec_attr.bInheritHandle = True
return win32security.DuplicateTokenEx(
th,
win32security.SecurityImpersonation,
win32con.MAXIMUM_ALLOWED,
win32security.TokenPrimary,
sec_attr,
)
def elevate_token(th):
'''
Set all token priviledges to enabled
'''
# Get list of privileges this token contains
privileges = win32security.GetTokenInformation(
th, win32security.TokenPrivileges)
# Create a set of all privileges to be enabled
enable_privs = set()
for luid, flags in privileges:
enable_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED))
# Enable the privileges
if win32security.AdjustTokenPrivileges(th, 0, enable_privs) == 0:
raise WindowsError(win32api.FormatMessage(win32api.GetLastError())) # pylint: disable=undefined-variable
def make_inheritable(token):
'''Create an inheritable handle'''
return win32api.DuplicateHandle(
win32api.GetCurrentProcess(),
token,
win32api.GetCurrentProcess(),
0,
1,
win32con.DUPLICATE_SAME_ACCESS
)
def CreateProcessWithLogonW(username=None, domain=None, password=None,
logonflags=0, applicationname=None, commandline=None, creationflags=0,
environment=None, currentdirectory=None, startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
process_info = PROCESS_INFORMATION()
advapi32.CreateProcessWithLogonW(
username,
domain,
password,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
return process_info
|
saltstack/salt | salt/platform/win.py | grant_winsta_and_desktop | python | def grant_winsta_and_desktop(th):
'''
Grant the token's user access to the current process's window station and
desktop.
'''
current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
# Add permissions for the sid to the current windows station and thread id.
# This prevents windows error 0xC0000142.
winsta = win32process.GetProcessWindowStation()
set_user_perm(winsta, WINSTA_ALL, current_sid)
desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId())
set_user_perm(desktop, DESKTOP_ALL, current_sid) | Grant the token's user access to the current process's window station and
desktop. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/platform/win.py#L1001-L1012 | [
"def set_user_perm(obj, perm, sid):\n '''\n Set an object permission for the given user sid\n '''\n info = (\n win32security.OWNER_SECURITY_INFORMATION |\n win32security.GROUP_SECURITY_INFORMATION |\n win32security.DACL_SECURITY_INFORMATION\n )\n sd = win32security.GetUserObjectSecurity(obj, info)\n dacl = sd.GetSecurityDescriptorDacl()\n ace_cnt = dacl.GetAceCount()\n found = False\n for idx in range(0, ace_cnt):\n (aceType, aceFlags), ace_mask, ace_sid = dacl.GetAce(idx)\n ace_exists = (\n aceType == ntsecuritycon.ACCESS_ALLOWED_ACE_TYPE and\n ace_mask == perm and\n ace_sid == sid\n )\n if ace_exists:\n # If the ace already exists, do nothing\n break\n"
] | # -*- coding: utf-8 -*-
'''
Windows specific utility functions, this module should be imported in a try,
except block because it is only applicable on Windows platforms.
Much of what is here was adapted from the following:
https://stackoverflow.com/a/43233332
http://stackoverflow.com/questions/29566330
'''
from __future__ import absolute_import, unicode_literals
import os
import collections
import logging
import psutil
import ctypes
from ctypes import wintypes
from salt.ext.six.moves import range
from salt.ext.six.moves import zip
import win32con
import win32con
import win32api
import win32process
import win32security
import win32service
import ntsecuritycon
# Set up logging
log = logging.getLogger(__name__)
ntdll = ctypes.WinDLL('ntdll')
secur32 = ctypes.WinDLL('secur32')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
advapi32 = ctypes.WinDLL('advapi32', use_last_error=True)
userenv = ctypes.WinDLL('userenv', use_last_error=True)
SYSTEM_SID = "S-1-5-18"
LOCAL_SRV_SID = "S-1-5-19"
NETWORK_SRV_SID = "S-1-5-19"
LOGON_WITH_PROFILE = 0x00000001
WINSTA_ALL = (
win32con.WINSTA_ACCESSCLIPBOARD |
win32con.WINSTA_ACCESSGLOBALATOMS |
win32con.WINSTA_CREATEDESKTOP |
win32con.WINSTA_ENUMDESKTOPS |
win32con.WINSTA_ENUMERATE |
win32con.WINSTA_EXITWINDOWS |
win32con.WINSTA_READATTRIBUTES |
win32con.WINSTA_READSCREEN |
win32con.WINSTA_WRITEATTRIBUTES |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
DESKTOP_ALL = (
win32con.DESKTOP_CREATEMENU |
win32con.DESKTOP_CREATEWINDOW |
win32con.DESKTOP_ENUMERATE |
win32con.DESKTOP_HOOKCONTROL |
win32con.DESKTOP_JOURNALPLAYBACK |
win32con.DESKTOP_JOURNALRECORD |
win32con.DESKTOP_READOBJECTS |
win32con.DESKTOP_SWITCHDESKTOP |
win32con.DESKTOP_WRITEOBJECTS |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
MAX_COMPUTER_NAME_LENGTH = 15
SECURITY_LOGON_TYPE = wintypes.ULONG
Interactive = 2
Network = 3
Batch = 4
Service = 5
LOGON_SUBMIT_TYPE = wintypes.ULONG
PROFILE_BUFFER_TYPE = wintypes.ULONG
MsV1_0InteractiveLogon = 2
MsV1_0Lm20Logon = 3
MsV1_0NetworkLogon = 4
MsV1_0WorkstationUnlockLogon = 7
MsV1_0S4ULogon = 12
MsV1_0NoElevationLogon = 82
KerbInteractiveLogon = 2
KerbWorkstationUnlockLogon = 7
KerbS4ULogon = 12
MSV1_0_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_IDENTITY = 0x8
TOKEN_SOURCE_LENGTH = 8
NEGOTIATE_PACKAGE_NAME = b'Negotiate'
MICROSOFT_KERBEROS_NAME = b'Kerberos'
MSV1_0_PACKAGE_NAME = b'MICROSOFT_AUTHENTICATION_PACKAGE_V1_0'
DELETE = 0x00010000
READ_CONTROL = 0x00020000
WRITE_DAC = 0x00040000
WRITE_OWNER = 0x00080000
STANDARD_RIGHTS_REQUIRED = (
DELETE |
READ_CONTROL |
WRITE_DAC |
WRITE_OWNER
)
TOKEN_ASSIGN_PRIMARY = 0x0001
TOKEN_DUPLICATE = 0x0002
TOKEN_IMPERSONATE = 0x0004
TOKEN_QUERY = 0x0008
TOKEN_QUERY_SOURCE = 0x0010
TOKEN_ADJUST_PRIVILEGES = 0x0020
TOKEN_ADJUST_GROUPS = 0x0040
TOKEN_ADJUST_DEFAULT = 0x0080
TOKEN_ADJUST_SESSIONID = 0x0100
TOKEN_ALL_ACCESS = (
STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE |
TOKEN_IMPERSONATE |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID
)
DUPLICATE_CLOSE_SOURCE = 0x00000001
DUPLICATE_SAME_ACCESS = 0x00000002
TOKEN_TYPE = wintypes.ULONG
TokenPrimary = 1
TokenImpersonation = 2
SECURITY_IMPERSONATION_LEVEL = wintypes.ULONG
SecurityAnonymous = 0
SecurityIdentification = 1
SecurityImpersonation = 2
SecurityDelegation = 3
class NTSTATUS(wintypes.LONG):
def to_error(self):
return ntdll.RtlNtStatusToDosError(self)
def __repr__(self):
name = self.__class__.__name__
status = wintypes.ULONG.from_buffer(self)
return '{}({})'.format(name, status.value)
PNTSTATUS = ctypes.POINTER(NTSTATUS)
class BOOL(wintypes.BOOL):
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, bool(self))
class HANDLE(wintypes.HANDLE):
__slots__ = 'closed',
def __int__(self):
return self.value or 0
def Detach(self):
if not getattr(self, 'closed', False):
self.closed = True
value = int(self)
self.value = None
return value
raise ValueError("already closed")
def Close(self, CloseHandle=kernel32.CloseHandle):
if self and not getattr(self, 'closed', False):
CloseHandle(self.Detach())
__del__ = Close
def __repr__(self):
return "{}({})".format(self.__class__.__name__, int(self))
class LARGE_INTEGER(wintypes.LARGE_INTEGER):
# https://msdn.microsoft.com/en-us/library/ff553204
ntdll.RtlSecondsSince1970ToTime.restype = None
_unix_epoch = wintypes.LARGE_INTEGER()
ntdll.RtlSecondsSince1970ToTime(0, ctypes.byref(_unix_epoch))
_unix_epoch = _unix_epoch.value
def __int__(self):
return self.value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, self.value)
def as_time(self):
time100ns = self.value - self._unix_epoch
if time100ns >= 0:
return time100ns / 1e7
raise ValueError('value predates the Unix epoch')
@classmethod
def from_time(cls, t):
time100ns = int(t * 10**7)
return cls(time100ns + cls._unix_epoch)
CHAR = ctypes.c_char
WCHAR = ctypes.c_wchar
PCHAR = ctypes.POINTER(CHAR)
PWCHAR = ctypes.POINTER(WCHAR)
class STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PCHAR),
)
LPSTRING = ctypes.POINTER(STRING)
class UNICODE_STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PWCHAR),
)
LPUNICODE_STRING = ctypes.POINTER(UNICODE_STRING)
class LUID(ctypes.Structure):
_fields_ = (
('LowPart', wintypes.DWORD),
('HighPart', wintypes.LONG),
)
def __new__(cls, value=0):
return cls.from_buffer_copy(ctypes.c_ulonglong(value))
def __int__(self):
return ctypes.c_ulonglong.from_buffer(self).value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, int(self))
LPLUID = ctypes.POINTER(LUID)
PSID = wintypes.LPVOID
class SID_AND_ATTRIBUTES(ctypes.Structure):
_fields_ = (
('Sid', PSID),
('Attributes', wintypes.DWORD),
)
LPSID_AND_ATTRIBUTES = ctypes.POINTER(SID_AND_ATTRIBUTES)
class TOKEN_GROUPS(ctypes.Structure):
_fields_ = (
('GroupCount', wintypes.DWORD),
('Groups', SID_AND_ATTRIBUTES * 1),
)
LPTOKEN_GROUPS = ctypes.POINTER(TOKEN_GROUPS)
class TOKEN_SOURCE(ctypes.Structure):
_fields_ = (
('SourceName', CHAR * TOKEN_SOURCE_LENGTH),
('SourceIdentifier', LUID),
)
def __init__(self, SourceName=None, SourceIdentifier=None):
super(TOKEN_SOURCE, self).__init__()
if SourceName is not None:
if not isinstance(SourceName, bytes):
SourceName = SourceName.encode('mbcs')
self.SourceName = SourceName
if SourceIdentifier is None:
luid = self.SourceIdentifier # pylint: disable=access-member-before-definition
ntdll.NtAllocateLocallyUniqueId(ctypes.byref(luid))
else:
self.SourceIdentifier = SourceIdentifier
LPTOKEN_SOURCE = ctypes.POINTER(TOKEN_SOURCE)
py_source_context = TOKEN_SOURCE(b"PYTHON ")
py_origin_name = __name__.encode()
py_logon_process_name = "{}-{}".format(py_origin_name, os.getpid())
SIZE_T = ctypes.c_size_t
class QUOTA_LIMITS(ctypes.Structure):
_fields_ = (('PagedPoolLimit', SIZE_T),
('NonPagedPoolLimit', SIZE_T),
('MinimumWorkingSetSize', SIZE_T),
('MaximumWorkingSetSize', SIZE_T),
('PagefileLimit', SIZE_T),
('TimeLimit', wintypes.LARGE_INTEGER))
LPQUOTA_LIMITS = ctypes.POINTER(QUOTA_LIMITS)
LPULONG = ctypes.POINTER(wintypes.ULONG)
LSA_OPERATIONAL_MODE = wintypes.ULONG
LPLSA_OPERATIONAL_MODE = LPULONG
LPHANDLE = ctypes.POINTER(wintypes.HANDLE)
LPLPVOID = ctypes.POINTER(wintypes.LPVOID)
LPDWORD = ctypes.POINTER(wintypes.DWORD)
class ContiguousUnicode(ctypes.Structure):
# _string_names_: sequence matched to underscore-prefixed fields
def __init__(self, *args, **kwargs):
super(ContiguousUnicode, self).__init__(*args, **kwargs)
def _get_unicode_string(self, name):
wchar_size = ctypes.sizeof(WCHAR)
s = getattr(self, '_{}'.format(name))
length = s.Length // wchar_size
buf = s.Buffer
if buf:
return buf[:length]
return None
def _set_unicode_buffer(self, values):
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
bufsize = (len('\x00'.join(values)) + 1) * wchar_size
ctypes.resize(self, ctypes.sizeof(cls) + bufsize)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for value in values:
bufsize = (len(value) + 1) * wchar_size
ctypes.memmove(addr, value, bufsize)
addr += bufsize
def _set_unicode_string(self, name, value):
values = []
for n in self._string_names_:
if n == name:
values.append(value or '')
else:
values.append(getattr(self, n) or '')
self._set_unicode_buffer(values)
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for n, v in zip(self._string_names_, values):
ptr = ctypes.cast(addr, PWCHAR)
ustr = getattr(self, '_{}'.format(n))
length = ustr.Length = len(v) * wchar_size
full_length = length + wchar_size
if ((n == name and value is None) or
(n != name and not (length or ustr.Buffer))):
ustr.Buffer = None
ustr.MaximumLength = 0
else:
ustr.Buffer = ptr
ustr.MaximumLength = full_length
addr += full_length
def __getattr__(self, name):
if name not in self._string_names_:
raise AttributeError
return self._get_unicode_string(name)
def __setattr__(self, name, value):
if name in self._string_names_:
self._set_unicode_string(name, value)
else:
super(ContiguousUnicode, self).__setattr__(name, value)
@classmethod
def from_address_copy(cls, address, size=None):
x = ctypes.Structure.__new__(cls)
if size is not None:
ctypes.resize(x, size)
ctypes.memmove(ctypes.byref(x), address, ctypes.sizeof(x))
delta = ctypes.addressof(x) - address
for n in cls._string_names_:
ustr = getattr(x, '_{}'.format(n))
addr = ctypes.c_void_p.from_buffer(ustr.Buffer)
if addr:
addr.value += delta
return x
class AuthInfo(ContiguousUnicode):
# _message_type_: from a logon-submit-type enumeration
def __init__(self):
super(AuthInfo, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_LOGON(AuthInfo):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = 'LogonDomainName', 'UserName', 'Password'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('_LogonDomainName', UNICODE_STRING),
('_UserName', UNICODE_STRING),
('_Password', UNICODE_STRING))
def __init__(self, UserName=None, Password=None, LogonDomainName=None):
super(MSV1_0_INTERACTIVE_LOGON, self).__init__()
if LogonDomainName is not None:
self.LogonDomainName = LogonDomainName
if UserName is not None:
self.UserName = UserName
if Password is not None:
self.Password = Password
class S4ULogon(AuthInfo):
_string_names_ = 'UserPrincipalName', 'DomainName'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('Flags', wintypes.ULONG),
('_UserPrincipalName', UNICODE_STRING),
('_DomainName', UNICODE_STRING))
def __init__(self, UserPrincipalName=None, DomainName=None, Flags=0):
super(S4ULogon, self).__init__()
self.Flags = Flags
if UserPrincipalName is not None:
self.UserPrincipalName = UserPrincipalName
if DomainName is not None:
self.DomainName = DomainName
class MSV1_0_S4U_LOGON(S4ULogon):
_message_type_ = MsV1_0S4ULogon
class KERB_S4U_LOGON(S4ULogon):
_message_type_ = KerbS4ULogon
PMSV1_0_S4U_LOGON = ctypes.POINTER(MSV1_0_S4U_LOGON)
PKERB_S4U_LOGON = ctypes.POINTER(KERB_S4U_LOGON)
class ProfileBuffer(ContiguousUnicode):
# _message_type_
def __init__(self):
super(ProfileBuffer, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_PROFILE(ProfileBuffer):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = ('LogonScript', 'HomeDirectory', 'FullName',
'ProfilePath', 'HomeDirectoryDrive', 'LogonServer')
_fields_ = (('MessageType', PROFILE_BUFFER_TYPE),
('LogonCount', wintypes.USHORT),
('BadPasswordCount', wintypes.USHORT),
('LogonTime', LARGE_INTEGER),
('LogoffTime', LARGE_INTEGER),
('KickOffTime', LARGE_INTEGER),
('PasswordLastSet', LARGE_INTEGER),
('PasswordCanChange', LARGE_INTEGER),
('PasswordMustChange', LARGE_INTEGER),
('_LogonScript', UNICODE_STRING),
('_HomeDirectory', UNICODE_STRING),
('_FullName', UNICODE_STRING),
('_ProfilePath', UNICODE_STRING),
('_HomeDirectoryDrive', UNICODE_STRING),
('_LogonServer', UNICODE_STRING),
('UserFlags', wintypes.ULONG))
def _check_status(result, func, args):
if result.value < 0:
raise ctypes.WinError(result.to_error())
return args
def _check_bool(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
INVALID_DWORD_VALUE = wintypes.DWORD(-1).value # ~WinAPI
INFINITE = INVALID_DWORD_VALUE
STD_INPUT_HANDLE = wintypes.DWORD(-10).value
STD_OUTPUT_HANDLE = wintypes.DWORD(-11).value
STD_ERROR_HANDLE = wintypes.DWORD(-12).value
class SECURITY_ATTRIBUTES(ctypes.Structure):
_fields_ = (('nLength', wintypes.DWORD),
('lpSecurityDescriptor', wintypes.LPVOID),
('bInheritHandle', wintypes.BOOL))
def __init__(self, **kwds):
self.nLength = ctypes.sizeof(self)
super(SECURITY_ATTRIBUTES, self).__init__(**kwds)
LPSECURITY_ATTRIBUTES = ctypes.POINTER(SECURITY_ATTRIBUTES)
LPBYTE = ctypes.POINTER(wintypes.BYTE)
LPHANDLE = PHANDLE = ctypes.POINTER(ctypes.c_void_p)
LPDWORD = ctypes.POINTER(ctypes.c_ulong)
class STARTUPINFO(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms686331"""
_fields_ = (('cb', wintypes.DWORD),
('lpReserved', wintypes.LPWSTR),
('lpDesktop', wintypes.LPWSTR),
('lpTitle', wintypes.LPWSTR),
('dwX', wintypes.DWORD),
('dwY', wintypes.DWORD),
('dwXSize', wintypes.DWORD),
('dwYSize', wintypes.DWORD),
('dwXCountChars', wintypes.DWORD),
('dwYCountChars', wintypes.DWORD),
('dwFillAttribute', wintypes.DWORD),
('dwFlags', wintypes.DWORD),
('wShowWindow', wintypes.WORD),
('cbReserved2', wintypes.WORD),
('lpReserved2', LPBYTE),
('hStdInput', wintypes.HANDLE),
('hStdOutput', wintypes.HANDLE),
('hStdError', wintypes.HANDLE))
def __init__(self, **kwds):
self.cb = ctypes.sizeof(self)
super(STARTUPINFO, self).__init__(**kwds)
LPSTARTUPINFO = ctypes.POINTER(STARTUPINFO)
class PROC_THREAD_ATTRIBUTE_LIST(ctypes.Structure):
pass
PPROC_THREAD_ATTRIBUTE_LIST = ctypes.POINTER(PROC_THREAD_ATTRIBUTE_LIST)
class STARTUPINFOEX(STARTUPINFO):
_fields_ = (('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST),)
LPSTARTUPINFOEX = ctypes.POINTER(STARTUPINFOEX)
class PROCESS_INFORMATION(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms684873"""
_fields_ = (('hProcess', wintypes.HANDLE),
('hThread', wintypes.HANDLE),
('dwProcessId', wintypes.DWORD),
('dwThreadId', wintypes.DWORD))
LPPROCESS_INFORMATION = ctypes.POINTER(PROCESS_INFORMATION)
class HANDLE_IHV(wintypes.HANDLE):
pass
def errcheck_ihv(result, func, args):
if result.value == INVALID_HANDLE_VALUE:
raise ctypes.WinError()
return result.value
class DWORD_IDV(wintypes.DWORD):
pass
def errcheck_idv(result, func, args):
if result.value == INVALID_DWORD_VALUE:
raise ctypes.WinError()
return result.value
def errcheck_bool(result, func, args):
if not result:
raise ctypes.WinError()
return args
def _win(func, restype, *argtypes):
func.restype = restype
func.argtypes = argtypes
if issubclass(restype, NTSTATUS):
func.errcheck = _check_status
elif issubclass(restype, BOOL):
func.errcheck = _check_bool
elif issubclass(restype, HANDLE_IHV):
func.errcheck = errcheck_ihv
elif issubclass(restype, DWORD_IDV):
func.errcheck = errcheck_idv
else:
func.errcheck = errcheck_bool
# https://msdn.microsoft.com/en-us/library/ms683231
_win(kernel32.GetStdHandle, HANDLE_IHV,
wintypes.DWORD) # _In_ nStdHandle
# https://msdn.microsoft.com/en-us/library/ms724211
_win(kernel32.CloseHandle, wintypes.BOOL,
wintypes.HANDLE) # _In_ hObject
# https://msdn.microsoft.com/en-us/library/ms724935
_win(kernel32.SetHandleInformation, wintypes.BOOL,
wintypes.HANDLE, # _In_ hObject
wintypes.DWORD, # _In_ dwMask
wintypes.DWORD) # _In_ dwFlags
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, wintypes.BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle,
wintypes.HANDLE, # _In_ hSourceHandle,
wintypes.HANDLE, # _In_ hTargetProcessHandle,
LPHANDLE, # _Out_ lpTargetHandle,
wintypes.DWORD, # _In_ dwDesiredAccess,
wintypes.BOOL, # _In_ bInheritHandle,
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms683189
_win(kernel32.GetExitCodeProcess, wintypes.BOOL,
wintypes.HANDLE, # _In_ hProcess,
LPDWORD) # _Out_ lpExitCode
# https://msdn.microsoft.com/en-us/library/aa365152
_win(kernel32.CreatePipe, wintypes.BOOL,
PHANDLE, # _Out_ hReadPipe,
PHANDLE, # _Out_ hWritePipe,
LPSECURITY_ATTRIBUTES, # _In_opt_ lpPipeAttributes,
wintypes.DWORD) # _In_ nSize
# https://msdn.microsoft.com/en-us/library/ms682431
#_win(advapi32.CreateProcessWithTokenW, wintypes.BOOL,
# PHANDLE, # _In_ lpUsername
# wintypes.DWORD, # _In_ dwLogonFlags
# wintypes.LPCWSTR, # _In_opt_ lpApplicationName
# wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
# wintypes.DWORD, # _In_ dwCreationFlags
# wintypes.LPVOID, # _In_opt_ lpEnvironment
# wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
# LPSTARTUPINFO, # _In_ lpStartupInfo
# LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms682431
_win(advapi32.CreateProcessWithLogonW, wintypes.BOOL,
wintypes.LPCWSTR, # _In_ lpUsername
wintypes.LPCWSTR, # _In_opt_ lpDomain
wintypes.LPCWSTR, # _In_ lpPassword
wintypes.DWORD, # _In_ dwLogonFlags
wintypes.LPCWSTR, # _In_opt_ lpApplicationName
wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
wintypes.DWORD, # _In_ dwCreationFlags
wintypes.LPCWSTR, # _In_opt_ lpEnvironment
wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
LPSTARTUPINFO, # _In_ lpStartupInfo
LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle
wintypes.HANDLE, # _In_ hSourceHandle
wintypes.HANDLE, # _In_ hTargetProcessHandle
LPHANDLE, # _Out_ lpTargetHandle
wintypes.DWORD, # _In_ dwDesiredAccess
wintypes.BOOL, # _In_ bInheritHandle
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms724295
_win(kernel32.GetComputerNameW, BOOL,
wintypes.LPWSTR, # _Out_ lpBuffer
LPDWORD) # _Inout_ lpnSize
# https://msdn.microsoft.com/en-us/library/aa379295
_win(advapi32.OpenProcessToken, BOOL,
wintypes.HANDLE, # _In_ ProcessHandle
wintypes.DWORD, # _In_ DesiredAccess
LPHANDLE) # _Out_ TokenHandle
# https://msdn.microsoft.com/en-us/library/aa446617
_win(advapi32.DuplicateTokenEx, BOOL,
wintypes.HANDLE, # _In_ hExistingToken
wintypes.DWORD, # _In_ dwDesiredAccess
LPSECURITY_ATTRIBUTES, # _In_opt_ lpTokenAttributes
SECURITY_IMPERSONATION_LEVEL, # _In_ ImpersonationLevel
TOKEN_TYPE, # _In_ TokenType
LPHANDLE) # _Out_ phNewToken
# https://msdn.microsoft.com/en-us/library/ff566415
_win(ntdll.NtAllocateLocallyUniqueId, NTSTATUS,
LPLUID) # _Out_ LUID
# https://msdn.microsoft.com/en-us/library/aa378279
_win(secur32.LsaFreeReturnBuffer, NTSTATUS,
wintypes.LPVOID,) # _In_ Buffer
# https://msdn.microsoft.com/en-us/library/aa378265
_win(secur32.LsaConnectUntrusted, NTSTATUS,
LPHANDLE,) # _Out_ LsaHandle
#https://msdn.microsoft.com/en-us/library/aa378318
_win(secur32.LsaRegisterLogonProcess, NTSTATUS,
LPSTRING, # _In_ LogonProcessName
LPHANDLE, # _Out_ LsaHandle
LPLSA_OPERATIONAL_MODE) # _Out_ SecurityMode
# https://msdn.microsoft.com/en-us/library/aa378269
_win(secur32.LsaDeregisterLogonProcess, NTSTATUS,
wintypes.HANDLE) # _In_ LsaHandle
# https://msdn.microsoft.com/en-us/library/aa378297
_win(secur32.LsaLookupAuthenticationPackage, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ PackageName
LPULONG) # _Out_ AuthenticationPackage
# https://msdn.microsoft.com/en-us/library/aa378292
_win(secur32.LsaLogonUser, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ OriginName
SECURITY_LOGON_TYPE, # _In_ LogonType
wintypes.ULONG, # _In_ AuthenticationPackage
wintypes.LPVOID, # _In_ AuthenticationInformation
wintypes.ULONG, # _In_ AuthenticationInformationLength
LPTOKEN_GROUPS, # _In_opt_ LocalGroups
LPTOKEN_SOURCE, # _In_ SourceContext
LPLPVOID, # _Out_ ProfileBuffer
LPULONG, # _Out_ ProfileBufferLength
LPLUID, # _Out_ LogonId
LPHANDLE, # _Out_ Token
LPQUOTA_LIMITS, # _Out_ Quotas
PNTSTATUS) # _Out_ SubStatus
def duplicate_token(source_token=None, access=TOKEN_ALL_ACCESS,
impersonation_level=SecurityImpersonation,
token_type=TokenPrimary, attributes=None):
close_source = False
if source_token is None:
close_source = True
source_token = HANDLE()
advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
TOKEN_ALL_ACCESS, ctypes.byref(source_token))
token = HANDLE()
try:
advapi32.DuplicateTokenEx(source_token, access, attributes,
impersonation_level, token_type, ctypes.byref(token))
finally:
if close_source:
source_token.Close()
return token
def lsa_connect_untrusted():
handle = wintypes.HANDLE()
secur32.LsaConnectUntrusted(ctypes.byref(handle))
return handle.value
def lsa_register_logon_process(logon_process_name):
if not isinstance(logon_process_name, bytes):
logon_process_name = logon_process_name.encode('mbcs')
logon_process_name = logon_process_name[:127]
buf = ctypes.create_string_buffer(logon_process_name, 128)
name = STRING(len(logon_process_name), len(buf), buf)
handle = wintypes.HANDLE()
mode = LSA_OPERATIONAL_MODE()
secur32.LsaRegisterLogonProcess(ctypes.byref(name),
ctypes.byref(handle), ctypes.byref(mode))
return handle.value
def lsa_lookup_authentication_package(lsa_handle, package_name):
if not isinstance(package_name, bytes):
package_name = package_name.encode('mbcs')
package_name = package_name[:127]
buf = ctypes.create_string_buffer(package_name)
name = STRING(len(package_name), len(buf), buf)
package = wintypes.ULONG()
secur32.LsaLookupAuthenticationPackage(lsa_handle, ctypes.byref(name),
ctypes.byref(package))
return package.value
LOGONINFO = collections.namedtuple('LOGONINFO', ('Token', 'LogonId',
'Profile', 'Quotas'))
def lsa_logon_user(auth_info, local_groups=None, origin_name=py_origin_name,
source_context=None, auth_package=None, logon_type=None,
lsa_handle=None):
if local_groups is None:
plocal_groups = LPTOKEN_GROUPS()
else:
plocal_groups = ctypes.byref(local_groups)
if source_context is None:
source_context = py_source_context
if not isinstance(origin_name, bytes):
origin_name = origin_name.encode('mbcs')
buf = ctypes.create_string_buffer(origin_name)
origin_name = STRING(len(origin_name), len(buf), buf)
if auth_package is None:
if isinstance(auth_info, MSV1_0_S4U_LOGON):
auth_package = NEGOTIATE_PACKAGE_NAME
elif isinstance(auth_info, KERB_S4U_LOGON):
auth_package = MICROSOFT_KERBEROS_NAME
else:
auth_package = MSV1_0_PACKAGE_NAME
if logon_type is None:
if isinstance(auth_info, S4ULogon):
logon_type = win32con.LOGON32_LOGON_NETWORK
else:
logon_type = Interactive
profile_buffer = wintypes.LPVOID()
profile_buffer_length = wintypes.ULONG()
profile = None
logonid = LUID()
htoken = HANDLE()
quotas = QUOTA_LIMITS()
substatus = NTSTATUS()
deregister = False
if lsa_handle is None:
lsa_handle = lsa_connect_untrusted()
deregister = True
try:
if isinstance(auth_package, (str, bytes)):
auth_package = lsa_lookup_authentication_package(lsa_handle,
auth_package)
try:
secur32.LsaLogonUser(lsa_handle, ctypes.byref(origin_name),
logon_type, auth_package, ctypes.byref(auth_info),
ctypes.sizeof(auth_info), plocal_groups,
ctypes.byref(source_context), ctypes.byref(profile_buffer),
ctypes.byref(profile_buffer_length), ctypes.byref(logonid),
ctypes.byref(htoken), ctypes.byref(quotas),
ctypes.byref(substatus))
except WindowsError: # pylint: disable=undefined-variable
if substatus.value:
raise ctypes.WinError(substatus.to_error())
raise
finally:
if profile_buffer:
address = profile_buffer.value
buftype = PROFILE_BUFFER_TYPE.from_address(address).value
if buftype == MsV1_0InteractiveLogon:
profile = MSV1_0_INTERACTIVE_PROFILE.from_address_copy(
address, profile_buffer_length.value)
secur32.LsaFreeReturnBuffer(address)
finally:
if deregister:
secur32.LsaDeregisterLogonProcess(lsa_handle)
return LOGONINFO(htoken, logonid, profile, quotas)
def logon_msv1(name, password, domain=None, local_groups=None,
origin_name=py_origin_name, source_context=None):
return lsa_logon_user(MSV1_0_INTERACTIVE_LOGON(name, password, domain),
local_groups, origin_name, source_context)
def logon_msv1_s4u(name, local_groups=None, origin_name=py_origin_name,
source_context=None):
domain = ctypes.create_unicode_buffer(MAX_COMPUTER_NAME_LENGTH + 1)
length = wintypes.DWORD(len(domain))
kernel32.GetComputerNameW(domain, ctypes.byref(length))
return lsa_logon_user(MSV1_0_S4U_LOGON(name, domain.value),
local_groups, origin_name, source_context)
def logon_kerb_s4u(name, realm=None, local_groups=None,
origin_name=py_origin_name,
source_context=None,
logon_process_name=py_logon_process_name):
lsa_handle = lsa_register_logon_process(logon_process_name)
try:
return lsa_logon_user(KERB_S4U_LOGON(name, realm),
local_groups, origin_name, source_context,
lsa_handle=lsa_handle)
finally:
secur32.LsaDeregisterLogonProcess(lsa_handle)
def DuplicateHandle(hsrc=kernel32.GetCurrentProcess(),
srchandle=kernel32.GetCurrentProcess(),
htgt=kernel32.GetCurrentProcess(),
access=0, inherit=False,
options=win32con.DUPLICATE_SAME_ACCESS):
tgthandle = wintypes.HANDLE()
kernel32.DuplicateHandle(hsrc, srchandle,
htgt, ctypes.byref(tgthandle),
access, inherit, options)
return tgthandle.value
def CreatePipe(inherit_read=False, inherit_write=False):
read, write = wintypes.HANDLE(), wintypes.HANDLE()
kernel32.CreatePipe(ctypes.byref(read), ctypes.byref(write), None, 0)
if inherit_read:
kernel32.SetHandleInformation(read, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
if inherit_write:
kernel32.SetHandleInformation(write, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
return read.value, write.value
def set_user_perm(obj, perm, sid):
'''
Set an object permission for the given user sid
'''
info = (
win32security.OWNER_SECURITY_INFORMATION |
win32security.GROUP_SECURITY_INFORMATION |
win32security.DACL_SECURITY_INFORMATION
)
sd = win32security.GetUserObjectSecurity(obj, info)
dacl = sd.GetSecurityDescriptorDacl()
ace_cnt = dacl.GetAceCount()
found = False
for idx in range(0, ace_cnt):
(aceType, aceFlags), ace_mask, ace_sid = dacl.GetAce(idx)
ace_exists = (
aceType == ntsecuritycon.ACCESS_ALLOWED_ACE_TYPE and
ace_mask == perm and
ace_sid == sid
)
if ace_exists:
# If the ace already exists, do nothing
break
else:
dacl.AddAccessAllowedAce(dacl.GetAclRevision(), perm, sid)
sd.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetUserObjectSecurity(obj, info, sd)
def environment_string(env):
senv = ''
for k, v in env.items():
senv += k + '=' + v + '\0'
senv += '\0'
return ctypes.create_unicode_buffer(senv)
def CreateProcessWithTokenW(token,
logonflags=0,
applicationname=None,
commandline=None,
creationflags=0,
environment=None,
currentdirectory=None,
startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
if currentdirectory is not None:
currentdirectory = ctypes.create_unicode_buffer(currentdirectory)
if environment:
environment = ctypes.pointer(
environment_string(environment)
)
process_info = PROCESS_INFORMATION()
ret = advapi32.CreateProcessWithTokenW(
token,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
if ret == 0:
winerr = win32api.GetLastError()
exc = WindowsError(win32api.FormatMessage(winerr)) # pylint: disable=undefined-variable
exc.winerror = winerr
raise exc
return process_info
def enumerate_tokens(sid=None, session_id=None, privs=None):
'''
Enumerate tokens from any existing processes that can be accessed.
Optionally filter by sid.
'''
for p in psutil.process_iter():
if p.pid == 0:
continue
try:
ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, p.pid)
except win32api.error as exc:
if exc.winerror == 5:
log.debug("Unable to OpenProcess pid=%d name=%s", p.pid, p.name())
continue
raise exc
try:
access = (
win32security.TOKEN_DUPLICATE |
win32security.TOKEN_QUERY |
win32security.TOKEN_IMPERSONATE |
win32security.TOKEN_ASSIGN_PRIMARY
)
th = win32security.OpenProcessToken(ph, access)
except Exception as exc:
log.debug("OpenProcessToken failed pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
try:
process_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
except Exception as exc:
log.exception("GetTokenInformation pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
proc_sid = win32security.ConvertSidToStringSid(process_sid)
if sid and sid != proc_sid:
log.debug("Token for pid does not match user sid: %s", sid)
continue
if session_id and win32security.GetTokenInformation(th, win32security.TokenSessionId) != session_id:
continue
def has_priv(tok, priv):
luid = win32security.LookupPrivilegeValue(None, priv)
for priv_luid, flags in win32security.GetTokenInformation(tok, win32security.TokenPrivileges):
if priv_luid == luid:
return True
return False
if privs:
has_all = True
for name in privs:
if not has_priv(th, name):
has_all = False
if not has_all:
continue
yield dup_token(th)
def impersonate_sid(sid, session_id=None, privs=None):
'''
Find an existing process token for the given sid and impersonate the token.
'''
for tok in enumerate_tokens(sid, session_id, privs):
tok = dup_token(tok)
elevate_token(tok)
if win32security.ImpersonateLoggedOnUser(tok) == 0:
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
return tok
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
def dup_token(th):
'''
duplicate the access token
'''
# TODO: is `duplicate_token` the same?
sec_attr = win32security.SECURITY_ATTRIBUTES()
sec_attr.bInheritHandle = True
return win32security.DuplicateTokenEx(
th,
win32security.SecurityImpersonation,
win32con.MAXIMUM_ALLOWED,
win32security.TokenPrimary,
sec_attr,
)
def elevate_token(th):
'''
Set all token priviledges to enabled
'''
# Get list of privileges this token contains
privileges = win32security.GetTokenInformation(
th, win32security.TokenPrivileges)
# Create a set of all privileges to be enabled
enable_privs = set()
for luid, flags in privileges:
enable_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED))
# Enable the privileges
if win32security.AdjustTokenPrivileges(th, 0, enable_privs) == 0:
raise WindowsError(win32api.FormatMessage(win32api.GetLastError())) # pylint: disable=undefined-variable
def make_inheritable(token):
'''Create an inheritable handle'''
return win32api.DuplicateHandle(
win32api.GetCurrentProcess(),
token,
win32api.GetCurrentProcess(),
0,
1,
win32con.DUPLICATE_SAME_ACCESS
)
def CreateProcessWithLogonW(username=None, domain=None, password=None,
logonflags=0, applicationname=None, commandline=None, creationflags=0,
environment=None, currentdirectory=None, startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
process_info = PROCESS_INFORMATION()
advapi32.CreateProcessWithLogonW(
username,
domain,
password,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
return process_info
|
saltstack/salt | salt/platform/win.py | enumerate_tokens | python | def enumerate_tokens(sid=None, session_id=None, privs=None):
'''
Enumerate tokens from any existing processes that can be accessed.
Optionally filter by sid.
'''
for p in psutil.process_iter():
if p.pid == 0:
continue
try:
ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, p.pid)
except win32api.error as exc:
if exc.winerror == 5:
log.debug("Unable to OpenProcess pid=%d name=%s", p.pid, p.name())
continue
raise exc
try:
access = (
win32security.TOKEN_DUPLICATE |
win32security.TOKEN_QUERY |
win32security.TOKEN_IMPERSONATE |
win32security.TOKEN_ASSIGN_PRIMARY
)
th = win32security.OpenProcessToken(ph, access)
except Exception as exc:
log.debug("OpenProcessToken failed pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
try:
process_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
except Exception as exc:
log.exception("GetTokenInformation pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
proc_sid = win32security.ConvertSidToStringSid(process_sid)
if sid and sid != proc_sid:
log.debug("Token for pid does not match user sid: %s", sid)
continue
if session_id and win32security.GetTokenInformation(th, win32security.TokenSessionId) != session_id:
continue
def has_priv(tok, priv):
luid = win32security.LookupPrivilegeValue(None, priv)
for priv_luid, flags in win32security.GetTokenInformation(tok, win32security.TokenPrivileges):
if priv_luid == luid:
return True
return False
if privs:
has_all = True
for name in privs:
if not has_priv(th, name):
has_all = False
if not has_all:
continue
yield dup_token(th) | Enumerate tokens from any existing processes that can be accessed.
Optionally filter by sid. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/platform/win.py#L1062-L1115 | [
"def dup_token(th):\n '''\n duplicate the access token\n '''\n # TODO: is `duplicate_token` the same?\n sec_attr = win32security.SECURITY_ATTRIBUTES()\n sec_attr.bInheritHandle = True\n return win32security.DuplicateTokenEx(\n th,\n win32security.SecurityImpersonation,\n win32con.MAXIMUM_ALLOWED,\n win32security.TokenPrimary,\n sec_attr,\n )\n",
"def has_priv(tok, priv):\n luid = win32security.LookupPrivilegeValue(None, priv)\n for priv_luid, flags in win32security.GetTokenInformation(tok, win32security.TokenPrivileges):\n if priv_luid == luid:\n return True\n return False\n"
] | # -*- coding: utf-8 -*-
'''
Windows specific utility functions, this module should be imported in a try,
except block because it is only applicable on Windows platforms.
Much of what is here was adapted from the following:
https://stackoverflow.com/a/43233332
http://stackoverflow.com/questions/29566330
'''
from __future__ import absolute_import, unicode_literals
import os
import collections
import logging
import psutil
import ctypes
from ctypes import wintypes
from salt.ext.six.moves import range
from salt.ext.six.moves import zip
import win32con
import win32con
import win32api
import win32process
import win32security
import win32service
import ntsecuritycon
# Set up logging
log = logging.getLogger(__name__)
ntdll = ctypes.WinDLL('ntdll')
secur32 = ctypes.WinDLL('secur32')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
advapi32 = ctypes.WinDLL('advapi32', use_last_error=True)
userenv = ctypes.WinDLL('userenv', use_last_error=True)
SYSTEM_SID = "S-1-5-18"
LOCAL_SRV_SID = "S-1-5-19"
NETWORK_SRV_SID = "S-1-5-19"
LOGON_WITH_PROFILE = 0x00000001
WINSTA_ALL = (
win32con.WINSTA_ACCESSCLIPBOARD |
win32con.WINSTA_ACCESSGLOBALATOMS |
win32con.WINSTA_CREATEDESKTOP |
win32con.WINSTA_ENUMDESKTOPS |
win32con.WINSTA_ENUMERATE |
win32con.WINSTA_EXITWINDOWS |
win32con.WINSTA_READATTRIBUTES |
win32con.WINSTA_READSCREEN |
win32con.WINSTA_WRITEATTRIBUTES |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
DESKTOP_ALL = (
win32con.DESKTOP_CREATEMENU |
win32con.DESKTOP_CREATEWINDOW |
win32con.DESKTOP_ENUMERATE |
win32con.DESKTOP_HOOKCONTROL |
win32con.DESKTOP_JOURNALPLAYBACK |
win32con.DESKTOP_JOURNALRECORD |
win32con.DESKTOP_READOBJECTS |
win32con.DESKTOP_SWITCHDESKTOP |
win32con.DESKTOP_WRITEOBJECTS |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
MAX_COMPUTER_NAME_LENGTH = 15
SECURITY_LOGON_TYPE = wintypes.ULONG
Interactive = 2
Network = 3
Batch = 4
Service = 5
LOGON_SUBMIT_TYPE = wintypes.ULONG
PROFILE_BUFFER_TYPE = wintypes.ULONG
MsV1_0InteractiveLogon = 2
MsV1_0Lm20Logon = 3
MsV1_0NetworkLogon = 4
MsV1_0WorkstationUnlockLogon = 7
MsV1_0S4ULogon = 12
MsV1_0NoElevationLogon = 82
KerbInteractiveLogon = 2
KerbWorkstationUnlockLogon = 7
KerbS4ULogon = 12
MSV1_0_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_IDENTITY = 0x8
TOKEN_SOURCE_LENGTH = 8
NEGOTIATE_PACKAGE_NAME = b'Negotiate'
MICROSOFT_KERBEROS_NAME = b'Kerberos'
MSV1_0_PACKAGE_NAME = b'MICROSOFT_AUTHENTICATION_PACKAGE_V1_0'
DELETE = 0x00010000
READ_CONTROL = 0x00020000
WRITE_DAC = 0x00040000
WRITE_OWNER = 0x00080000
STANDARD_RIGHTS_REQUIRED = (
DELETE |
READ_CONTROL |
WRITE_DAC |
WRITE_OWNER
)
TOKEN_ASSIGN_PRIMARY = 0x0001
TOKEN_DUPLICATE = 0x0002
TOKEN_IMPERSONATE = 0x0004
TOKEN_QUERY = 0x0008
TOKEN_QUERY_SOURCE = 0x0010
TOKEN_ADJUST_PRIVILEGES = 0x0020
TOKEN_ADJUST_GROUPS = 0x0040
TOKEN_ADJUST_DEFAULT = 0x0080
TOKEN_ADJUST_SESSIONID = 0x0100
TOKEN_ALL_ACCESS = (
STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE |
TOKEN_IMPERSONATE |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID
)
DUPLICATE_CLOSE_SOURCE = 0x00000001
DUPLICATE_SAME_ACCESS = 0x00000002
TOKEN_TYPE = wintypes.ULONG
TokenPrimary = 1
TokenImpersonation = 2
SECURITY_IMPERSONATION_LEVEL = wintypes.ULONG
SecurityAnonymous = 0
SecurityIdentification = 1
SecurityImpersonation = 2
SecurityDelegation = 3
class NTSTATUS(wintypes.LONG):
def to_error(self):
return ntdll.RtlNtStatusToDosError(self)
def __repr__(self):
name = self.__class__.__name__
status = wintypes.ULONG.from_buffer(self)
return '{}({})'.format(name, status.value)
PNTSTATUS = ctypes.POINTER(NTSTATUS)
class BOOL(wintypes.BOOL):
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, bool(self))
class HANDLE(wintypes.HANDLE):
__slots__ = 'closed',
def __int__(self):
return self.value or 0
def Detach(self):
if not getattr(self, 'closed', False):
self.closed = True
value = int(self)
self.value = None
return value
raise ValueError("already closed")
def Close(self, CloseHandle=kernel32.CloseHandle):
if self and not getattr(self, 'closed', False):
CloseHandle(self.Detach())
__del__ = Close
def __repr__(self):
return "{}({})".format(self.__class__.__name__, int(self))
class LARGE_INTEGER(wintypes.LARGE_INTEGER):
# https://msdn.microsoft.com/en-us/library/ff553204
ntdll.RtlSecondsSince1970ToTime.restype = None
_unix_epoch = wintypes.LARGE_INTEGER()
ntdll.RtlSecondsSince1970ToTime(0, ctypes.byref(_unix_epoch))
_unix_epoch = _unix_epoch.value
def __int__(self):
return self.value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, self.value)
def as_time(self):
time100ns = self.value - self._unix_epoch
if time100ns >= 0:
return time100ns / 1e7
raise ValueError('value predates the Unix epoch')
@classmethod
def from_time(cls, t):
time100ns = int(t * 10**7)
return cls(time100ns + cls._unix_epoch)
CHAR = ctypes.c_char
WCHAR = ctypes.c_wchar
PCHAR = ctypes.POINTER(CHAR)
PWCHAR = ctypes.POINTER(WCHAR)
class STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PCHAR),
)
LPSTRING = ctypes.POINTER(STRING)
class UNICODE_STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PWCHAR),
)
LPUNICODE_STRING = ctypes.POINTER(UNICODE_STRING)
class LUID(ctypes.Structure):
_fields_ = (
('LowPart', wintypes.DWORD),
('HighPart', wintypes.LONG),
)
def __new__(cls, value=0):
return cls.from_buffer_copy(ctypes.c_ulonglong(value))
def __int__(self):
return ctypes.c_ulonglong.from_buffer(self).value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, int(self))
LPLUID = ctypes.POINTER(LUID)
PSID = wintypes.LPVOID
class SID_AND_ATTRIBUTES(ctypes.Structure):
_fields_ = (
('Sid', PSID),
('Attributes', wintypes.DWORD),
)
LPSID_AND_ATTRIBUTES = ctypes.POINTER(SID_AND_ATTRIBUTES)
class TOKEN_GROUPS(ctypes.Structure):
_fields_ = (
('GroupCount', wintypes.DWORD),
('Groups', SID_AND_ATTRIBUTES * 1),
)
LPTOKEN_GROUPS = ctypes.POINTER(TOKEN_GROUPS)
class TOKEN_SOURCE(ctypes.Structure):
_fields_ = (
('SourceName', CHAR * TOKEN_SOURCE_LENGTH),
('SourceIdentifier', LUID),
)
def __init__(self, SourceName=None, SourceIdentifier=None):
super(TOKEN_SOURCE, self).__init__()
if SourceName is not None:
if not isinstance(SourceName, bytes):
SourceName = SourceName.encode('mbcs')
self.SourceName = SourceName
if SourceIdentifier is None:
luid = self.SourceIdentifier # pylint: disable=access-member-before-definition
ntdll.NtAllocateLocallyUniqueId(ctypes.byref(luid))
else:
self.SourceIdentifier = SourceIdentifier
LPTOKEN_SOURCE = ctypes.POINTER(TOKEN_SOURCE)
py_source_context = TOKEN_SOURCE(b"PYTHON ")
py_origin_name = __name__.encode()
py_logon_process_name = "{}-{}".format(py_origin_name, os.getpid())
SIZE_T = ctypes.c_size_t
class QUOTA_LIMITS(ctypes.Structure):
_fields_ = (('PagedPoolLimit', SIZE_T),
('NonPagedPoolLimit', SIZE_T),
('MinimumWorkingSetSize', SIZE_T),
('MaximumWorkingSetSize', SIZE_T),
('PagefileLimit', SIZE_T),
('TimeLimit', wintypes.LARGE_INTEGER))
LPQUOTA_LIMITS = ctypes.POINTER(QUOTA_LIMITS)
LPULONG = ctypes.POINTER(wintypes.ULONG)
LSA_OPERATIONAL_MODE = wintypes.ULONG
LPLSA_OPERATIONAL_MODE = LPULONG
LPHANDLE = ctypes.POINTER(wintypes.HANDLE)
LPLPVOID = ctypes.POINTER(wintypes.LPVOID)
LPDWORD = ctypes.POINTER(wintypes.DWORD)
class ContiguousUnicode(ctypes.Structure):
# _string_names_: sequence matched to underscore-prefixed fields
def __init__(self, *args, **kwargs):
super(ContiguousUnicode, self).__init__(*args, **kwargs)
def _get_unicode_string(self, name):
wchar_size = ctypes.sizeof(WCHAR)
s = getattr(self, '_{}'.format(name))
length = s.Length // wchar_size
buf = s.Buffer
if buf:
return buf[:length]
return None
def _set_unicode_buffer(self, values):
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
bufsize = (len('\x00'.join(values)) + 1) * wchar_size
ctypes.resize(self, ctypes.sizeof(cls) + bufsize)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for value in values:
bufsize = (len(value) + 1) * wchar_size
ctypes.memmove(addr, value, bufsize)
addr += bufsize
def _set_unicode_string(self, name, value):
values = []
for n in self._string_names_:
if n == name:
values.append(value or '')
else:
values.append(getattr(self, n) or '')
self._set_unicode_buffer(values)
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for n, v in zip(self._string_names_, values):
ptr = ctypes.cast(addr, PWCHAR)
ustr = getattr(self, '_{}'.format(n))
length = ustr.Length = len(v) * wchar_size
full_length = length + wchar_size
if ((n == name and value is None) or
(n != name and not (length or ustr.Buffer))):
ustr.Buffer = None
ustr.MaximumLength = 0
else:
ustr.Buffer = ptr
ustr.MaximumLength = full_length
addr += full_length
def __getattr__(self, name):
if name not in self._string_names_:
raise AttributeError
return self._get_unicode_string(name)
def __setattr__(self, name, value):
if name in self._string_names_:
self._set_unicode_string(name, value)
else:
super(ContiguousUnicode, self).__setattr__(name, value)
@classmethod
def from_address_copy(cls, address, size=None):
x = ctypes.Structure.__new__(cls)
if size is not None:
ctypes.resize(x, size)
ctypes.memmove(ctypes.byref(x), address, ctypes.sizeof(x))
delta = ctypes.addressof(x) - address
for n in cls._string_names_:
ustr = getattr(x, '_{}'.format(n))
addr = ctypes.c_void_p.from_buffer(ustr.Buffer)
if addr:
addr.value += delta
return x
class AuthInfo(ContiguousUnicode):
# _message_type_: from a logon-submit-type enumeration
def __init__(self):
super(AuthInfo, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_LOGON(AuthInfo):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = 'LogonDomainName', 'UserName', 'Password'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('_LogonDomainName', UNICODE_STRING),
('_UserName', UNICODE_STRING),
('_Password', UNICODE_STRING))
def __init__(self, UserName=None, Password=None, LogonDomainName=None):
super(MSV1_0_INTERACTIVE_LOGON, self).__init__()
if LogonDomainName is not None:
self.LogonDomainName = LogonDomainName
if UserName is not None:
self.UserName = UserName
if Password is not None:
self.Password = Password
class S4ULogon(AuthInfo):
_string_names_ = 'UserPrincipalName', 'DomainName'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('Flags', wintypes.ULONG),
('_UserPrincipalName', UNICODE_STRING),
('_DomainName', UNICODE_STRING))
def __init__(self, UserPrincipalName=None, DomainName=None, Flags=0):
super(S4ULogon, self).__init__()
self.Flags = Flags
if UserPrincipalName is not None:
self.UserPrincipalName = UserPrincipalName
if DomainName is not None:
self.DomainName = DomainName
class MSV1_0_S4U_LOGON(S4ULogon):
_message_type_ = MsV1_0S4ULogon
class KERB_S4U_LOGON(S4ULogon):
_message_type_ = KerbS4ULogon
PMSV1_0_S4U_LOGON = ctypes.POINTER(MSV1_0_S4U_LOGON)
PKERB_S4U_LOGON = ctypes.POINTER(KERB_S4U_LOGON)
class ProfileBuffer(ContiguousUnicode):
# _message_type_
def __init__(self):
super(ProfileBuffer, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_PROFILE(ProfileBuffer):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = ('LogonScript', 'HomeDirectory', 'FullName',
'ProfilePath', 'HomeDirectoryDrive', 'LogonServer')
_fields_ = (('MessageType', PROFILE_BUFFER_TYPE),
('LogonCount', wintypes.USHORT),
('BadPasswordCount', wintypes.USHORT),
('LogonTime', LARGE_INTEGER),
('LogoffTime', LARGE_INTEGER),
('KickOffTime', LARGE_INTEGER),
('PasswordLastSet', LARGE_INTEGER),
('PasswordCanChange', LARGE_INTEGER),
('PasswordMustChange', LARGE_INTEGER),
('_LogonScript', UNICODE_STRING),
('_HomeDirectory', UNICODE_STRING),
('_FullName', UNICODE_STRING),
('_ProfilePath', UNICODE_STRING),
('_HomeDirectoryDrive', UNICODE_STRING),
('_LogonServer', UNICODE_STRING),
('UserFlags', wintypes.ULONG))
def _check_status(result, func, args):
if result.value < 0:
raise ctypes.WinError(result.to_error())
return args
def _check_bool(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
INVALID_DWORD_VALUE = wintypes.DWORD(-1).value # ~WinAPI
INFINITE = INVALID_DWORD_VALUE
STD_INPUT_HANDLE = wintypes.DWORD(-10).value
STD_OUTPUT_HANDLE = wintypes.DWORD(-11).value
STD_ERROR_HANDLE = wintypes.DWORD(-12).value
class SECURITY_ATTRIBUTES(ctypes.Structure):
_fields_ = (('nLength', wintypes.DWORD),
('lpSecurityDescriptor', wintypes.LPVOID),
('bInheritHandle', wintypes.BOOL))
def __init__(self, **kwds):
self.nLength = ctypes.sizeof(self)
super(SECURITY_ATTRIBUTES, self).__init__(**kwds)
LPSECURITY_ATTRIBUTES = ctypes.POINTER(SECURITY_ATTRIBUTES)
LPBYTE = ctypes.POINTER(wintypes.BYTE)
LPHANDLE = PHANDLE = ctypes.POINTER(ctypes.c_void_p)
LPDWORD = ctypes.POINTER(ctypes.c_ulong)
class STARTUPINFO(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms686331"""
_fields_ = (('cb', wintypes.DWORD),
('lpReserved', wintypes.LPWSTR),
('lpDesktop', wintypes.LPWSTR),
('lpTitle', wintypes.LPWSTR),
('dwX', wintypes.DWORD),
('dwY', wintypes.DWORD),
('dwXSize', wintypes.DWORD),
('dwYSize', wintypes.DWORD),
('dwXCountChars', wintypes.DWORD),
('dwYCountChars', wintypes.DWORD),
('dwFillAttribute', wintypes.DWORD),
('dwFlags', wintypes.DWORD),
('wShowWindow', wintypes.WORD),
('cbReserved2', wintypes.WORD),
('lpReserved2', LPBYTE),
('hStdInput', wintypes.HANDLE),
('hStdOutput', wintypes.HANDLE),
('hStdError', wintypes.HANDLE))
def __init__(self, **kwds):
self.cb = ctypes.sizeof(self)
super(STARTUPINFO, self).__init__(**kwds)
LPSTARTUPINFO = ctypes.POINTER(STARTUPINFO)
class PROC_THREAD_ATTRIBUTE_LIST(ctypes.Structure):
pass
PPROC_THREAD_ATTRIBUTE_LIST = ctypes.POINTER(PROC_THREAD_ATTRIBUTE_LIST)
class STARTUPINFOEX(STARTUPINFO):
_fields_ = (('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST),)
LPSTARTUPINFOEX = ctypes.POINTER(STARTUPINFOEX)
class PROCESS_INFORMATION(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms684873"""
_fields_ = (('hProcess', wintypes.HANDLE),
('hThread', wintypes.HANDLE),
('dwProcessId', wintypes.DWORD),
('dwThreadId', wintypes.DWORD))
LPPROCESS_INFORMATION = ctypes.POINTER(PROCESS_INFORMATION)
class HANDLE_IHV(wintypes.HANDLE):
pass
def errcheck_ihv(result, func, args):
if result.value == INVALID_HANDLE_VALUE:
raise ctypes.WinError()
return result.value
class DWORD_IDV(wintypes.DWORD):
pass
def errcheck_idv(result, func, args):
if result.value == INVALID_DWORD_VALUE:
raise ctypes.WinError()
return result.value
def errcheck_bool(result, func, args):
if not result:
raise ctypes.WinError()
return args
def _win(func, restype, *argtypes):
func.restype = restype
func.argtypes = argtypes
if issubclass(restype, NTSTATUS):
func.errcheck = _check_status
elif issubclass(restype, BOOL):
func.errcheck = _check_bool
elif issubclass(restype, HANDLE_IHV):
func.errcheck = errcheck_ihv
elif issubclass(restype, DWORD_IDV):
func.errcheck = errcheck_idv
else:
func.errcheck = errcheck_bool
# https://msdn.microsoft.com/en-us/library/ms683231
_win(kernel32.GetStdHandle, HANDLE_IHV,
wintypes.DWORD) # _In_ nStdHandle
# https://msdn.microsoft.com/en-us/library/ms724211
_win(kernel32.CloseHandle, wintypes.BOOL,
wintypes.HANDLE) # _In_ hObject
# https://msdn.microsoft.com/en-us/library/ms724935
_win(kernel32.SetHandleInformation, wintypes.BOOL,
wintypes.HANDLE, # _In_ hObject
wintypes.DWORD, # _In_ dwMask
wintypes.DWORD) # _In_ dwFlags
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, wintypes.BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle,
wintypes.HANDLE, # _In_ hSourceHandle,
wintypes.HANDLE, # _In_ hTargetProcessHandle,
LPHANDLE, # _Out_ lpTargetHandle,
wintypes.DWORD, # _In_ dwDesiredAccess,
wintypes.BOOL, # _In_ bInheritHandle,
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms683189
_win(kernel32.GetExitCodeProcess, wintypes.BOOL,
wintypes.HANDLE, # _In_ hProcess,
LPDWORD) # _Out_ lpExitCode
# https://msdn.microsoft.com/en-us/library/aa365152
_win(kernel32.CreatePipe, wintypes.BOOL,
PHANDLE, # _Out_ hReadPipe,
PHANDLE, # _Out_ hWritePipe,
LPSECURITY_ATTRIBUTES, # _In_opt_ lpPipeAttributes,
wintypes.DWORD) # _In_ nSize
# https://msdn.microsoft.com/en-us/library/ms682431
#_win(advapi32.CreateProcessWithTokenW, wintypes.BOOL,
# PHANDLE, # _In_ lpUsername
# wintypes.DWORD, # _In_ dwLogonFlags
# wintypes.LPCWSTR, # _In_opt_ lpApplicationName
# wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
# wintypes.DWORD, # _In_ dwCreationFlags
# wintypes.LPVOID, # _In_opt_ lpEnvironment
# wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
# LPSTARTUPINFO, # _In_ lpStartupInfo
# LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms682431
_win(advapi32.CreateProcessWithLogonW, wintypes.BOOL,
wintypes.LPCWSTR, # _In_ lpUsername
wintypes.LPCWSTR, # _In_opt_ lpDomain
wintypes.LPCWSTR, # _In_ lpPassword
wintypes.DWORD, # _In_ dwLogonFlags
wintypes.LPCWSTR, # _In_opt_ lpApplicationName
wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
wintypes.DWORD, # _In_ dwCreationFlags
wintypes.LPCWSTR, # _In_opt_ lpEnvironment
wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
LPSTARTUPINFO, # _In_ lpStartupInfo
LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle
wintypes.HANDLE, # _In_ hSourceHandle
wintypes.HANDLE, # _In_ hTargetProcessHandle
LPHANDLE, # _Out_ lpTargetHandle
wintypes.DWORD, # _In_ dwDesiredAccess
wintypes.BOOL, # _In_ bInheritHandle
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms724295
_win(kernel32.GetComputerNameW, BOOL,
wintypes.LPWSTR, # _Out_ lpBuffer
LPDWORD) # _Inout_ lpnSize
# https://msdn.microsoft.com/en-us/library/aa379295
_win(advapi32.OpenProcessToken, BOOL,
wintypes.HANDLE, # _In_ ProcessHandle
wintypes.DWORD, # _In_ DesiredAccess
LPHANDLE) # _Out_ TokenHandle
# https://msdn.microsoft.com/en-us/library/aa446617
_win(advapi32.DuplicateTokenEx, BOOL,
wintypes.HANDLE, # _In_ hExistingToken
wintypes.DWORD, # _In_ dwDesiredAccess
LPSECURITY_ATTRIBUTES, # _In_opt_ lpTokenAttributes
SECURITY_IMPERSONATION_LEVEL, # _In_ ImpersonationLevel
TOKEN_TYPE, # _In_ TokenType
LPHANDLE) # _Out_ phNewToken
# https://msdn.microsoft.com/en-us/library/ff566415
_win(ntdll.NtAllocateLocallyUniqueId, NTSTATUS,
LPLUID) # _Out_ LUID
# https://msdn.microsoft.com/en-us/library/aa378279
_win(secur32.LsaFreeReturnBuffer, NTSTATUS,
wintypes.LPVOID,) # _In_ Buffer
# https://msdn.microsoft.com/en-us/library/aa378265
_win(secur32.LsaConnectUntrusted, NTSTATUS,
LPHANDLE,) # _Out_ LsaHandle
#https://msdn.microsoft.com/en-us/library/aa378318
_win(secur32.LsaRegisterLogonProcess, NTSTATUS,
LPSTRING, # _In_ LogonProcessName
LPHANDLE, # _Out_ LsaHandle
LPLSA_OPERATIONAL_MODE) # _Out_ SecurityMode
# https://msdn.microsoft.com/en-us/library/aa378269
_win(secur32.LsaDeregisterLogonProcess, NTSTATUS,
wintypes.HANDLE) # _In_ LsaHandle
# https://msdn.microsoft.com/en-us/library/aa378297
_win(secur32.LsaLookupAuthenticationPackage, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ PackageName
LPULONG) # _Out_ AuthenticationPackage
# https://msdn.microsoft.com/en-us/library/aa378292
_win(secur32.LsaLogonUser, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ OriginName
SECURITY_LOGON_TYPE, # _In_ LogonType
wintypes.ULONG, # _In_ AuthenticationPackage
wintypes.LPVOID, # _In_ AuthenticationInformation
wintypes.ULONG, # _In_ AuthenticationInformationLength
LPTOKEN_GROUPS, # _In_opt_ LocalGroups
LPTOKEN_SOURCE, # _In_ SourceContext
LPLPVOID, # _Out_ ProfileBuffer
LPULONG, # _Out_ ProfileBufferLength
LPLUID, # _Out_ LogonId
LPHANDLE, # _Out_ Token
LPQUOTA_LIMITS, # _Out_ Quotas
PNTSTATUS) # _Out_ SubStatus
def duplicate_token(source_token=None, access=TOKEN_ALL_ACCESS,
impersonation_level=SecurityImpersonation,
token_type=TokenPrimary, attributes=None):
close_source = False
if source_token is None:
close_source = True
source_token = HANDLE()
advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
TOKEN_ALL_ACCESS, ctypes.byref(source_token))
token = HANDLE()
try:
advapi32.DuplicateTokenEx(source_token, access, attributes,
impersonation_level, token_type, ctypes.byref(token))
finally:
if close_source:
source_token.Close()
return token
def lsa_connect_untrusted():
handle = wintypes.HANDLE()
secur32.LsaConnectUntrusted(ctypes.byref(handle))
return handle.value
def lsa_register_logon_process(logon_process_name):
if not isinstance(logon_process_name, bytes):
logon_process_name = logon_process_name.encode('mbcs')
logon_process_name = logon_process_name[:127]
buf = ctypes.create_string_buffer(logon_process_name, 128)
name = STRING(len(logon_process_name), len(buf), buf)
handle = wintypes.HANDLE()
mode = LSA_OPERATIONAL_MODE()
secur32.LsaRegisterLogonProcess(ctypes.byref(name),
ctypes.byref(handle), ctypes.byref(mode))
return handle.value
def lsa_lookup_authentication_package(lsa_handle, package_name):
if not isinstance(package_name, bytes):
package_name = package_name.encode('mbcs')
package_name = package_name[:127]
buf = ctypes.create_string_buffer(package_name)
name = STRING(len(package_name), len(buf), buf)
package = wintypes.ULONG()
secur32.LsaLookupAuthenticationPackage(lsa_handle, ctypes.byref(name),
ctypes.byref(package))
return package.value
LOGONINFO = collections.namedtuple('LOGONINFO', ('Token', 'LogonId',
'Profile', 'Quotas'))
def lsa_logon_user(auth_info, local_groups=None, origin_name=py_origin_name,
source_context=None, auth_package=None, logon_type=None,
lsa_handle=None):
if local_groups is None:
plocal_groups = LPTOKEN_GROUPS()
else:
plocal_groups = ctypes.byref(local_groups)
if source_context is None:
source_context = py_source_context
if not isinstance(origin_name, bytes):
origin_name = origin_name.encode('mbcs')
buf = ctypes.create_string_buffer(origin_name)
origin_name = STRING(len(origin_name), len(buf), buf)
if auth_package is None:
if isinstance(auth_info, MSV1_0_S4U_LOGON):
auth_package = NEGOTIATE_PACKAGE_NAME
elif isinstance(auth_info, KERB_S4U_LOGON):
auth_package = MICROSOFT_KERBEROS_NAME
else:
auth_package = MSV1_0_PACKAGE_NAME
if logon_type is None:
if isinstance(auth_info, S4ULogon):
logon_type = win32con.LOGON32_LOGON_NETWORK
else:
logon_type = Interactive
profile_buffer = wintypes.LPVOID()
profile_buffer_length = wintypes.ULONG()
profile = None
logonid = LUID()
htoken = HANDLE()
quotas = QUOTA_LIMITS()
substatus = NTSTATUS()
deregister = False
if lsa_handle is None:
lsa_handle = lsa_connect_untrusted()
deregister = True
try:
if isinstance(auth_package, (str, bytes)):
auth_package = lsa_lookup_authentication_package(lsa_handle,
auth_package)
try:
secur32.LsaLogonUser(lsa_handle, ctypes.byref(origin_name),
logon_type, auth_package, ctypes.byref(auth_info),
ctypes.sizeof(auth_info), plocal_groups,
ctypes.byref(source_context), ctypes.byref(profile_buffer),
ctypes.byref(profile_buffer_length), ctypes.byref(logonid),
ctypes.byref(htoken), ctypes.byref(quotas),
ctypes.byref(substatus))
except WindowsError: # pylint: disable=undefined-variable
if substatus.value:
raise ctypes.WinError(substatus.to_error())
raise
finally:
if profile_buffer:
address = profile_buffer.value
buftype = PROFILE_BUFFER_TYPE.from_address(address).value
if buftype == MsV1_0InteractiveLogon:
profile = MSV1_0_INTERACTIVE_PROFILE.from_address_copy(
address, profile_buffer_length.value)
secur32.LsaFreeReturnBuffer(address)
finally:
if deregister:
secur32.LsaDeregisterLogonProcess(lsa_handle)
return LOGONINFO(htoken, logonid, profile, quotas)
def logon_msv1(name, password, domain=None, local_groups=None,
origin_name=py_origin_name, source_context=None):
return lsa_logon_user(MSV1_0_INTERACTIVE_LOGON(name, password, domain),
local_groups, origin_name, source_context)
def logon_msv1_s4u(name, local_groups=None, origin_name=py_origin_name,
source_context=None):
domain = ctypes.create_unicode_buffer(MAX_COMPUTER_NAME_LENGTH + 1)
length = wintypes.DWORD(len(domain))
kernel32.GetComputerNameW(domain, ctypes.byref(length))
return lsa_logon_user(MSV1_0_S4U_LOGON(name, domain.value),
local_groups, origin_name, source_context)
def logon_kerb_s4u(name, realm=None, local_groups=None,
origin_name=py_origin_name,
source_context=None,
logon_process_name=py_logon_process_name):
lsa_handle = lsa_register_logon_process(logon_process_name)
try:
return lsa_logon_user(KERB_S4U_LOGON(name, realm),
local_groups, origin_name, source_context,
lsa_handle=lsa_handle)
finally:
secur32.LsaDeregisterLogonProcess(lsa_handle)
def DuplicateHandle(hsrc=kernel32.GetCurrentProcess(),
srchandle=kernel32.GetCurrentProcess(),
htgt=kernel32.GetCurrentProcess(),
access=0, inherit=False,
options=win32con.DUPLICATE_SAME_ACCESS):
tgthandle = wintypes.HANDLE()
kernel32.DuplicateHandle(hsrc, srchandle,
htgt, ctypes.byref(tgthandle),
access, inherit, options)
return tgthandle.value
def CreatePipe(inherit_read=False, inherit_write=False):
read, write = wintypes.HANDLE(), wintypes.HANDLE()
kernel32.CreatePipe(ctypes.byref(read), ctypes.byref(write), None, 0)
if inherit_read:
kernel32.SetHandleInformation(read, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
if inherit_write:
kernel32.SetHandleInformation(write, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
return read.value, write.value
def set_user_perm(obj, perm, sid):
'''
Set an object permission for the given user sid
'''
info = (
win32security.OWNER_SECURITY_INFORMATION |
win32security.GROUP_SECURITY_INFORMATION |
win32security.DACL_SECURITY_INFORMATION
)
sd = win32security.GetUserObjectSecurity(obj, info)
dacl = sd.GetSecurityDescriptorDacl()
ace_cnt = dacl.GetAceCount()
found = False
for idx in range(0, ace_cnt):
(aceType, aceFlags), ace_mask, ace_sid = dacl.GetAce(idx)
ace_exists = (
aceType == ntsecuritycon.ACCESS_ALLOWED_ACE_TYPE and
ace_mask == perm and
ace_sid == sid
)
if ace_exists:
# If the ace already exists, do nothing
break
else:
dacl.AddAccessAllowedAce(dacl.GetAclRevision(), perm, sid)
sd.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetUserObjectSecurity(obj, info, sd)
def grant_winsta_and_desktop(th):
'''
Grant the token's user access to the current process's window station and
desktop.
'''
current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
# Add permissions for the sid to the current windows station and thread id.
# This prevents windows error 0xC0000142.
winsta = win32process.GetProcessWindowStation()
set_user_perm(winsta, WINSTA_ALL, current_sid)
desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId())
set_user_perm(desktop, DESKTOP_ALL, current_sid)
def environment_string(env):
senv = ''
for k, v in env.items():
senv += k + '=' + v + '\0'
senv += '\0'
return ctypes.create_unicode_buffer(senv)
def CreateProcessWithTokenW(token,
logonflags=0,
applicationname=None,
commandline=None,
creationflags=0,
environment=None,
currentdirectory=None,
startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
if currentdirectory is not None:
currentdirectory = ctypes.create_unicode_buffer(currentdirectory)
if environment:
environment = ctypes.pointer(
environment_string(environment)
)
process_info = PROCESS_INFORMATION()
ret = advapi32.CreateProcessWithTokenW(
token,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
if ret == 0:
winerr = win32api.GetLastError()
exc = WindowsError(win32api.FormatMessage(winerr)) # pylint: disable=undefined-variable
exc.winerror = winerr
raise exc
return process_info
def impersonate_sid(sid, session_id=None, privs=None):
'''
Find an existing process token for the given sid and impersonate the token.
'''
for tok in enumerate_tokens(sid, session_id, privs):
tok = dup_token(tok)
elevate_token(tok)
if win32security.ImpersonateLoggedOnUser(tok) == 0:
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
return tok
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
def dup_token(th):
'''
duplicate the access token
'''
# TODO: is `duplicate_token` the same?
sec_attr = win32security.SECURITY_ATTRIBUTES()
sec_attr.bInheritHandle = True
return win32security.DuplicateTokenEx(
th,
win32security.SecurityImpersonation,
win32con.MAXIMUM_ALLOWED,
win32security.TokenPrimary,
sec_attr,
)
def elevate_token(th):
'''
Set all token priviledges to enabled
'''
# Get list of privileges this token contains
privileges = win32security.GetTokenInformation(
th, win32security.TokenPrivileges)
# Create a set of all privileges to be enabled
enable_privs = set()
for luid, flags in privileges:
enable_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED))
# Enable the privileges
if win32security.AdjustTokenPrivileges(th, 0, enable_privs) == 0:
raise WindowsError(win32api.FormatMessage(win32api.GetLastError())) # pylint: disable=undefined-variable
def make_inheritable(token):
'''Create an inheritable handle'''
return win32api.DuplicateHandle(
win32api.GetCurrentProcess(),
token,
win32api.GetCurrentProcess(),
0,
1,
win32con.DUPLICATE_SAME_ACCESS
)
def CreateProcessWithLogonW(username=None, domain=None, password=None,
logonflags=0, applicationname=None, commandline=None, creationflags=0,
environment=None, currentdirectory=None, startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
process_info = PROCESS_INFORMATION()
advapi32.CreateProcessWithLogonW(
username,
domain,
password,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
return process_info
|
saltstack/salt | salt/platform/win.py | impersonate_sid | python | def impersonate_sid(sid, session_id=None, privs=None):
'''
Find an existing process token for the given sid and impersonate the token.
'''
for tok in enumerate_tokens(sid, session_id, privs):
tok = dup_token(tok)
elevate_token(tok)
if win32security.ImpersonateLoggedOnUser(tok) == 0:
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
return tok
raise WindowsError("Impersonation failure") | Find an existing process token for the given sid and impersonate the token. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/platform/win.py#L1118-L1128 | [
"def enumerate_tokens(sid=None, session_id=None, privs=None):\n '''\n Enumerate tokens from any existing processes that can be accessed.\n Optionally filter by sid.\n '''\n for p in psutil.process_iter():\n if p.pid == 0:\n continue\n try:\n ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, p.pid)\n except win32api.error as exc:\n if exc.winerror == 5:\n log.debug(\"Unable to OpenProcess pid=%d name=%s\", p.pid, p.name())\n continue\n raise exc\n try:\n access = (\n win32security.TOKEN_DUPLICATE |\n win32security.TOKEN_QUERY |\n win32security.TOKEN_IMPERSONATE |\n win32security.TOKEN_ASSIGN_PRIMARY\n )\n th = win32security.OpenProcessToken(ph, access)\n except Exception as exc:\n log.debug(\"OpenProcessToken failed pid=%d name=%s user%s\", p.pid, p.name(), p.username())\n continue\n try:\n process_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]\n except Exception as exc:\n log.exception(\"GetTokenInformation pid=%d name=%s user%s\", p.pid, p.name(), p.username())\n continue\n\n proc_sid = win32security.ConvertSidToStringSid(process_sid)\n if sid and sid != proc_sid:\n log.debug(\"Token for pid does not match user sid: %s\", sid)\n continue\n\n if session_id and win32security.GetTokenInformation(th, win32security.TokenSessionId) != session_id:\n continue\n\n def has_priv(tok, priv):\n luid = win32security.LookupPrivilegeValue(None, priv)\n for priv_luid, flags in win32security.GetTokenInformation(tok, win32security.TokenPrivileges):\n if priv_luid == luid:\n return True\n return False\n if privs:\n has_all = True\n for name in privs:\n if not has_priv(th, name):\n has_all = False\n if not has_all:\n continue\n yield dup_token(th)\n",
"def dup_token(th):\n '''\n duplicate the access token\n '''\n # TODO: is `duplicate_token` the same?\n sec_attr = win32security.SECURITY_ATTRIBUTES()\n sec_attr.bInheritHandle = True\n return win32security.DuplicateTokenEx(\n th,\n win32security.SecurityImpersonation,\n win32con.MAXIMUM_ALLOWED,\n win32security.TokenPrimary,\n sec_attr,\n )\n",
"def elevate_token(th):\n '''\n Set all token priviledges to enabled\n '''\n # Get list of privileges this token contains\n privileges = win32security.GetTokenInformation(\n th, win32security.TokenPrivileges)\n\n # Create a set of all privileges to be enabled\n enable_privs = set()\n for luid, flags in privileges:\n enable_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED))\n\n # Enable the privileges\n if win32security.AdjustTokenPrivileges(th, 0, enable_privs) == 0:\n raise WindowsError(win32api.FormatMessage(win32api.GetLastError())) # pylint: disable=undefined-variable\n"
] | # -*- coding: utf-8 -*-
'''
Windows specific utility functions, this module should be imported in a try,
except block because it is only applicable on Windows platforms.
Much of what is here was adapted from the following:
https://stackoverflow.com/a/43233332
http://stackoverflow.com/questions/29566330
'''
from __future__ import absolute_import, unicode_literals
import os
import collections
import logging
import psutil
import ctypes
from ctypes import wintypes
from salt.ext.six.moves import range
from salt.ext.six.moves import zip
import win32con
import win32con
import win32api
import win32process
import win32security
import win32service
import ntsecuritycon
# Set up logging
log = logging.getLogger(__name__)
ntdll = ctypes.WinDLL('ntdll')
secur32 = ctypes.WinDLL('secur32')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
advapi32 = ctypes.WinDLL('advapi32', use_last_error=True)
userenv = ctypes.WinDLL('userenv', use_last_error=True)
SYSTEM_SID = "S-1-5-18"
LOCAL_SRV_SID = "S-1-5-19"
NETWORK_SRV_SID = "S-1-5-19"
LOGON_WITH_PROFILE = 0x00000001
WINSTA_ALL = (
win32con.WINSTA_ACCESSCLIPBOARD |
win32con.WINSTA_ACCESSGLOBALATOMS |
win32con.WINSTA_CREATEDESKTOP |
win32con.WINSTA_ENUMDESKTOPS |
win32con.WINSTA_ENUMERATE |
win32con.WINSTA_EXITWINDOWS |
win32con.WINSTA_READATTRIBUTES |
win32con.WINSTA_READSCREEN |
win32con.WINSTA_WRITEATTRIBUTES |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
DESKTOP_ALL = (
win32con.DESKTOP_CREATEMENU |
win32con.DESKTOP_CREATEWINDOW |
win32con.DESKTOP_ENUMERATE |
win32con.DESKTOP_HOOKCONTROL |
win32con.DESKTOP_JOURNALPLAYBACK |
win32con.DESKTOP_JOURNALRECORD |
win32con.DESKTOP_READOBJECTS |
win32con.DESKTOP_SWITCHDESKTOP |
win32con.DESKTOP_WRITEOBJECTS |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
MAX_COMPUTER_NAME_LENGTH = 15
SECURITY_LOGON_TYPE = wintypes.ULONG
Interactive = 2
Network = 3
Batch = 4
Service = 5
LOGON_SUBMIT_TYPE = wintypes.ULONG
PROFILE_BUFFER_TYPE = wintypes.ULONG
MsV1_0InteractiveLogon = 2
MsV1_0Lm20Logon = 3
MsV1_0NetworkLogon = 4
MsV1_0WorkstationUnlockLogon = 7
MsV1_0S4ULogon = 12
MsV1_0NoElevationLogon = 82
KerbInteractiveLogon = 2
KerbWorkstationUnlockLogon = 7
KerbS4ULogon = 12
MSV1_0_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_IDENTITY = 0x8
TOKEN_SOURCE_LENGTH = 8
NEGOTIATE_PACKAGE_NAME = b'Negotiate'
MICROSOFT_KERBEROS_NAME = b'Kerberos'
MSV1_0_PACKAGE_NAME = b'MICROSOFT_AUTHENTICATION_PACKAGE_V1_0'
DELETE = 0x00010000
READ_CONTROL = 0x00020000
WRITE_DAC = 0x00040000
WRITE_OWNER = 0x00080000
STANDARD_RIGHTS_REQUIRED = (
DELETE |
READ_CONTROL |
WRITE_DAC |
WRITE_OWNER
)
TOKEN_ASSIGN_PRIMARY = 0x0001
TOKEN_DUPLICATE = 0x0002
TOKEN_IMPERSONATE = 0x0004
TOKEN_QUERY = 0x0008
TOKEN_QUERY_SOURCE = 0x0010
TOKEN_ADJUST_PRIVILEGES = 0x0020
TOKEN_ADJUST_GROUPS = 0x0040
TOKEN_ADJUST_DEFAULT = 0x0080
TOKEN_ADJUST_SESSIONID = 0x0100
TOKEN_ALL_ACCESS = (
STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE |
TOKEN_IMPERSONATE |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID
)
DUPLICATE_CLOSE_SOURCE = 0x00000001
DUPLICATE_SAME_ACCESS = 0x00000002
TOKEN_TYPE = wintypes.ULONG
TokenPrimary = 1
TokenImpersonation = 2
SECURITY_IMPERSONATION_LEVEL = wintypes.ULONG
SecurityAnonymous = 0
SecurityIdentification = 1
SecurityImpersonation = 2
SecurityDelegation = 3
class NTSTATUS(wintypes.LONG):
def to_error(self):
return ntdll.RtlNtStatusToDosError(self)
def __repr__(self):
name = self.__class__.__name__
status = wintypes.ULONG.from_buffer(self)
return '{}({})'.format(name, status.value)
PNTSTATUS = ctypes.POINTER(NTSTATUS)
class BOOL(wintypes.BOOL):
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, bool(self))
class HANDLE(wintypes.HANDLE):
__slots__ = 'closed',
def __int__(self):
return self.value or 0
def Detach(self):
if not getattr(self, 'closed', False):
self.closed = True
value = int(self)
self.value = None
return value
raise ValueError("already closed")
def Close(self, CloseHandle=kernel32.CloseHandle):
if self and not getattr(self, 'closed', False):
CloseHandle(self.Detach())
__del__ = Close
def __repr__(self):
return "{}({})".format(self.__class__.__name__, int(self))
class LARGE_INTEGER(wintypes.LARGE_INTEGER):
# https://msdn.microsoft.com/en-us/library/ff553204
ntdll.RtlSecondsSince1970ToTime.restype = None
_unix_epoch = wintypes.LARGE_INTEGER()
ntdll.RtlSecondsSince1970ToTime(0, ctypes.byref(_unix_epoch))
_unix_epoch = _unix_epoch.value
def __int__(self):
return self.value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, self.value)
def as_time(self):
time100ns = self.value - self._unix_epoch
if time100ns >= 0:
return time100ns / 1e7
raise ValueError('value predates the Unix epoch')
@classmethod
def from_time(cls, t):
time100ns = int(t * 10**7)
return cls(time100ns + cls._unix_epoch)
CHAR = ctypes.c_char
WCHAR = ctypes.c_wchar
PCHAR = ctypes.POINTER(CHAR)
PWCHAR = ctypes.POINTER(WCHAR)
class STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PCHAR),
)
LPSTRING = ctypes.POINTER(STRING)
class UNICODE_STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PWCHAR),
)
LPUNICODE_STRING = ctypes.POINTER(UNICODE_STRING)
class LUID(ctypes.Structure):
_fields_ = (
('LowPart', wintypes.DWORD),
('HighPart', wintypes.LONG),
)
def __new__(cls, value=0):
return cls.from_buffer_copy(ctypes.c_ulonglong(value))
def __int__(self):
return ctypes.c_ulonglong.from_buffer(self).value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, int(self))
LPLUID = ctypes.POINTER(LUID)
PSID = wintypes.LPVOID
class SID_AND_ATTRIBUTES(ctypes.Structure):
_fields_ = (
('Sid', PSID),
('Attributes', wintypes.DWORD),
)
LPSID_AND_ATTRIBUTES = ctypes.POINTER(SID_AND_ATTRIBUTES)
class TOKEN_GROUPS(ctypes.Structure):
_fields_ = (
('GroupCount', wintypes.DWORD),
('Groups', SID_AND_ATTRIBUTES * 1),
)
LPTOKEN_GROUPS = ctypes.POINTER(TOKEN_GROUPS)
class TOKEN_SOURCE(ctypes.Structure):
_fields_ = (
('SourceName', CHAR * TOKEN_SOURCE_LENGTH),
('SourceIdentifier', LUID),
)
def __init__(self, SourceName=None, SourceIdentifier=None):
super(TOKEN_SOURCE, self).__init__()
if SourceName is not None:
if not isinstance(SourceName, bytes):
SourceName = SourceName.encode('mbcs')
self.SourceName = SourceName
if SourceIdentifier is None:
luid = self.SourceIdentifier # pylint: disable=access-member-before-definition
ntdll.NtAllocateLocallyUniqueId(ctypes.byref(luid))
else:
self.SourceIdentifier = SourceIdentifier
LPTOKEN_SOURCE = ctypes.POINTER(TOKEN_SOURCE)
py_source_context = TOKEN_SOURCE(b"PYTHON ")
py_origin_name = __name__.encode()
py_logon_process_name = "{}-{}".format(py_origin_name, os.getpid())
SIZE_T = ctypes.c_size_t
class QUOTA_LIMITS(ctypes.Structure):
_fields_ = (('PagedPoolLimit', SIZE_T),
('NonPagedPoolLimit', SIZE_T),
('MinimumWorkingSetSize', SIZE_T),
('MaximumWorkingSetSize', SIZE_T),
('PagefileLimit', SIZE_T),
('TimeLimit', wintypes.LARGE_INTEGER))
LPQUOTA_LIMITS = ctypes.POINTER(QUOTA_LIMITS)
LPULONG = ctypes.POINTER(wintypes.ULONG)
LSA_OPERATIONAL_MODE = wintypes.ULONG
LPLSA_OPERATIONAL_MODE = LPULONG
LPHANDLE = ctypes.POINTER(wintypes.HANDLE)
LPLPVOID = ctypes.POINTER(wintypes.LPVOID)
LPDWORD = ctypes.POINTER(wintypes.DWORD)
class ContiguousUnicode(ctypes.Structure):
# _string_names_: sequence matched to underscore-prefixed fields
def __init__(self, *args, **kwargs):
super(ContiguousUnicode, self).__init__(*args, **kwargs)
def _get_unicode_string(self, name):
wchar_size = ctypes.sizeof(WCHAR)
s = getattr(self, '_{}'.format(name))
length = s.Length // wchar_size
buf = s.Buffer
if buf:
return buf[:length]
return None
def _set_unicode_buffer(self, values):
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
bufsize = (len('\x00'.join(values)) + 1) * wchar_size
ctypes.resize(self, ctypes.sizeof(cls) + bufsize)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for value in values:
bufsize = (len(value) + 1) * wchar_size
ctypes.memmove(addr, value, bufsize)
addr += bufsize
def _set_unicode_string(self, name, value):
values = []
for n in self._string_names_:
if n == name:
values.append(value or '')
else:
values.append(getattr(self, n) or '')
self._set_unicode_buffer(values)
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for n, v in zip(self._string_names_, values):
ptr = ctypes.cast(addr, PWCHAR)
ustr = getattr(self, '_{}'.format(n))
length = ustr.Length = len(v) * wchar_size
full_length = length + wchar_size
if ((n == name and value is None) or
(n != name and not (length or ustr.Buffer))):
ustr.Buffer = None
ustr.MaximumLength = 0
else:
ustr.Buffer = ptr
ustr.MaximumLength = full_length
addr += full_length
def __getattr__(self, name):
if name not in self._string_names_:
raise AttributeError
return self._get_unicode_string(name)
def __setattr__(self, name, value):
if name in self._string_names_:
self._set_unicode_string(name, value)
else:
super(ContiguousUnicode, self).__setattr__(name, value)
@classmethod
def from_address_copy(cls, address, size=None):
x = ctypes.Structure.__new__(cls)
if size is not None:
ctypes.resize(x, size)
ctypes.memmove(ctypes.byref(x), address, ctypes.sizeof(x))
delta = ctypes.addressof(x) - address
for n in cls._string_names_:
ustr = getattr(x, '_{}'.format(n))
addr = ctypes.c_void_p.from_buffer(ustr.Buffer)
if addr:
addr.value += delta
return x
class AuthInfo(ContiguousUnicode):
# _message_type_: from a logon-submit-type enumeration
def __init__(self):
super(AuthInfo, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_LOGON(AuthInfo):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = 'LogonDomainName', 'UserName', 'Password'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('_LogonDomainName', UNICODE_STRING),
('_UserName', UNICODE_STRING),
('_Password', UNICODE_STRING))
def __init__(self, UserName=None, Password=None, LogonDomainName=None):
super(MSV1_0_INTERACTIVE_LOGON, self).__init__()
if LogonDomainName is not None:
self.LogonDomainName = LogonDomainName
if UserName is not None:
self.UserName = UserName
if Password is not None:
self.Password = Password
class S4ULogon(AuthInfo):
_string_names_ = 'UserPrincipalName', 'DomainName'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('Flags', wintypes.ULONG),
('_UserPrincipalName', UNICODE_STRING),
('_DomainName', UNICODE_STRING))
def __init__(self, UserPrincipalName=None, DomainName=None, Flags=0):
super(S4ULogon, self).__init__()
self.Flags = Flags
if UserPrincipalName is not None:
self.UserPrincipalName = UserPrincipalName
if DomainName is not None:
self.DomainName = DomainName
class MSV1_0_S4U_LOGON(S4ULogon):
_message_type_ = MsV1_0S4ULogon
class KERB_S4U_LOGON(S4ULogon):
_message_type_ = KerbS4ULogon
PMSV1_0_S4U_LOGON = ctypes.POINTER(MSV1_0_S4U_LOGON)
PKERB_S4U_LOGON = ctypes.POINTER(KERB_S4U_LOGON)
class ProfileBuffer(ContiguousUnicode):
# _message_type_
def __init__(self):
super(ProfileBuffer, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_PROFILE(ProfileBuffer):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = ('LogonScript', 'HomeDirectory', 'FullName',
'ProfilePath', 'HomeDirectoryDrive', 'LogonServer')
_fields_ = (('MessageType', PROFILE_BUFFER_TYPE),
('LogonCount', wintypes.USHORT),
('BadPasswordCount', wintypes.USHORT),
('LogonTime', LARGE_INTEGER),
('LogoffTime', LARGE_INTEGER),
('KickOffTime', LARGE_INTEGER),
('PasswordLastSet', LARGE_INTEGER),
('PasswordCanChange', LARGE_INTEGER),
('PasswordMustChange', LARGE_INTEGER),
('_LogonScript', UNICODE_STRING),
('_HomeDirectory', UNICODE_STRING),
('_FullName', UNICODE_STRING),
('_ProfilePath', UNICODE_STRING),
('_HomeDirectoryDrive', UNICODE_STRING),
('_LogonServer', UNICODE_STRING),
('UserFlags', wintypes.ULONG))
def _check_status(result, func, args):
if result.value < 0:
raise ctypes.WinError(result.to_error())
return args
def _check_bool(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
INVALID_DWORD_VALUE = wintypes.DWORD(-1).value # ~WinAPI
INFINITE = INVALID_DWORD_VALUE
STD_INPUT_HANDLE = wintypes.DWORD(-10).value
STD_OUTPUT_HANDLE = wintypes.DWORD(-11).value
STD_ERROR_HANDLE = wintypes.DWORD(-12).value
class SECURITY_ATTRIBUTES(ctypes.Structure):
_fields_ = (('nLength', wintypes.DWORD),
('lpSecurityDescriptor', wintypes.LPVOID),
('bInheritHandle', wintypes.BOOL))
def __init__(self, **kwds):
self.nLength = ctypes.sizeof(self)
super(SECURITY_ATTRIBUTES, self).__init__(**kwds)
LPSECURITY_ATTRIBUTES = ctypes.POINTER(SECURITY_ATTRIBUTES)
LPBYTE = ctypes.POINTER(wintypes.BYTE)
LPHANDLE = PHANDLE = ctypes.POINTER(ctypes.c_void_p)
LPDWORD = ctypes.POINTER(ctypes.c_ulong)
class STARTUPINFO(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms686331"""
_fields_ = (('cb', wintypes.DWORD),
('lpReserved', wintypes.LPWSTR),
('lpDesktop', wintypes.LPWSTR),
('lpTitle', wintypes.LPWSTR),
('dwX', wintypes.DWORD),
('dwY', wintypes.DWORD),
('dwXSize', wintypes.DWORD),
('dwYSize', wintypes.DWORD),
('dwXCountChars', wintypes.DWORD),
('dwYCountChars', wintypes.DWORD),
('dwFillAttribute', wintypes.DWORD),
('dwFlags', wintypes.DWORD),
('wShowWindow', wintypes.WORD),
('cbReserved2', wintypes.WORD),
('lpReserved2', LPBYTE),
('hStdInput', wintypes.HANDLE),
('hStdOutput', wintypes.HANDLE),
('hStdError', wintypes.HANDLE))
def __init__(self, **kwds):
self.cb = ctypes.sizeof(self)
super(STARTUPINFO, self).__init__(**kwds)
LPSTARTUPINFO = ctypes.POINTER(STARTUPINFO)
class PROC_THREAD_ATTRIBUTE_LIST(ctypes.Structure):
pass
PPROC_THREAD_ATTRIBUTE_LIST = ctypes.POINTER(PROC_THREAD_ATTRIBUTE_LIST)
class STARTUPINFOEX(STARTUPINFO):
_fields_ = (('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST),)
LPSTARTUPINFOEX = ctypes.POINTER(STARTUPINFOEX)
class PROCESS_INFORMATION(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms684873"""
_fields_ = (('hProcess', wintypes.HANDLE),
('hThread', wintypes.HANDLE),
('dwProcessId', wintypes.DWORD),
('dwThreadId', wintypes.DWORD))
LPPROCESS_INFORMATION = ctypes.POINTER(PROCESS_INFORMATION)
class HANDLE_IHV(wintypes.HANDLE):
pass
def errcheck_ihv(result, func, args):
if result.value == INVALID_HANDLE_VALUE:
raise ctypes.WinError()
return result.value
class DWORD_IDV(wintypes.DWORD):
pass
def errcheck_idv(result, func, args):
if result.value == INVALID_DWORD_VALUE:
raise ctypes.WinError()
return result.value
def errcheck_bool(result, func, args):
if not result:
raise ctypes.WinError()
return args
def _win(func, restype, *argtypes):
func.restype = restype
func.argtypes = argtypes
if issubclass(restype, NTSTATUS):
func.errcheck = _check_status
elif issubclass(restype, BOOL):
func.errcheck = _check_bool
elif issubclass(restype, HANDLE_IHV):
func.errcheck = errcheck_ihv
elif issubclass(restype, DWORD_IDV):
func.errcheck = errcheck_idv
else:
func.errcheck = errcheck_bool
# https://msdn.microsoft.com/en-us/library/ms683231
_win(kernel32.GetStdHandle, HANDLE_IHV,
wintypes.DWORD) # _In_ nStdHandle
# https://msdn.microsoft.com/en-us/library/ms724211
_win(kernel32.CloseHandle, wintypes.BOOL,
wintypes.HANDLE) # _In_ hObject
# https://msdn.microsoft.com/en-us/library/ms724935
_win(kernel32.SetHandleInformation, wintypes.BOOL,
wintypes.HANDLE, # _In_ hObject
wintypes.DWORD, # _In_ dwMask
wintypes.DWORD) # _In_ dwFlags
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, wintypes.BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle,
wintypes.HANDLE, # _In_ hSourceHandle,
wintypes.HANDLE, # _In_ hTargetProcessHandle,
LPHANDLE, # _Out_ lpTargetHandle,
wintypes.DWORD, # _In_ dwDesiredAccess,
wintypes.BOOL, # _In_ bInheritHandle,
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms683189
_win(kernel32.GetExitCodeProcess, wintypes.BOOL,
wintypes.HANDLE, # _In_ hProcess,
LPDWORD) # _Out_ lpExitCode
# https://msdn.microsoft.com/en-us/library/aa365152
_win(kernel32.CreatePipe, wintypes.BOOL,
PHANDLE, # _Out_ hReadPipe,
PHANDLE, # _Out_ hWritePipe,
LPSECURITY_ATTRIBUTES, # _In_opt_ lpPipeAttributes,
wintypes.DWORD) # _In_ nSize
# https://msdn.microsoft.com/en-us/library/ms682431
#_win(advapi32.CreateProcessWithTokenW, wintypes.BOOL,
# PHANDLE, # _In_ lpUsername
# wintypes.DWORD, # _In_ dwLogonFlags
# wintypes.LPCWSTR, # _In_opt_ lpApplicationName
# wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
# wintypes.DWORD, # _In_ dwCreationFlags
# wintypes.LPVOID, # _In_opt_ lpEnvironment
# wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
# LPSTARTUPINFO, # _In_ lpStartupInfo
# LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms682431
_win(advapi32.CreateProcessWithLogonW, wintypes.BOOL,
wintypes.LPCWSTR, # _In_ lpUsername
wintypes.LPCWSTR, # _In_opt_ lpDomain
wintypes.LPCWSTR, # _In_ lpPassword
wintypes.DWORD, # _In_ dwLogonFlags
wintypes.LPCWSTR, # _In_opt_ lpApplicationName
wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
wintypes.DWORD, # _In_ dwCreationFlags
wintypes.LPCWSTR, # _In_opt_ lpEnvironment
wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
LPSTARTUPINFO, # _In_ lpStartupInfo
LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle
wintypes.HANDLE, # _In_ hSourceHandle
wintypes.HANDLE, # _In_ hTargetProcessHandle
LPHANDLE, # _Out_ lpTargetHandle
wintypes.DWORD, # _In_ dwDesiredAccess
wintypes.BOOL, # _In_ bInheritHandle
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms724295
_win(kernel32.GetComputerNameW, BOOL,
wintypes.LPWSTR, # _Out_ lpBuffer
LPDWORD) # _Inout_ lpnSize
# https://msdn.microsoft.com/en-us/library/aa379295
_win(advapi32.OpenProcessToken, BOOL,
wintypes.HANDLE, # _In_ ProcessHandle
wintypes.DWORD, # _In_ DesiredAccess
LPHANDLE) # _Out_ TokenHandle
# https://msdn.microsoft.com/en-us/library/aa446617
_win(advapi32.DuplicateTokenEx, BOOL,
wintypes.HANDLE, # _In_ hExistingToken
wintypes.DWORD, # _In_ dwDesiredAccess
LPSECURITY_ATTRIBUTES, # _In_opt_ lpTokenAttributes
SECURITY_IMPERSONATION_LEVEL, # _In_ ImpersonationLevel
TOKEN_TYPE, # _In_ TokenType
LPHANDLE) # _Out_ phNewToken
# https://msdn.microsoft.com/en-us/library/ff566415
_win(ntdll.NtAllocateLocallyUniqueId, NTSTATUS,
LPLUID) # _Out_ LUID
# https://msdn.microsoft.com/en-us/library/aa378279
_win(secur32.LsaFreeReturnBuffer, NTSTATUS,
wintypes.LPVOID,) # _In_ Buffer
# https://msdn.microsoft.com/en-us/library/aa378265
_win(secur32.LsaConnectUntrusted, NTSTATUS,
LPHANDLE,) # _Out_ LsaHandle
#https://msdn.microsoft.com/en-us/library/aa378318
_win(secur32.LsaRegisterLogonProcess, NTSTATUS,
LPSTRING, # _In_ LogonProcessName
LPHANDLE, # _Out_ LsaHandle
LPLSA_OPERATIONAL_MODE) # _Out_ SecurityMode
# https://msdn.microsoft.com/en-us/library/aa378269
_win(secur32.LsaDeregisterLogonProcess, NTSTATUS,
wintypes.HANDLE) # _In_ LsaHandle
# https://msdn.microsoft.com/en-us/library/aa378297
_win(secur32.LsaLookupAuthenticationPackage, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ PackageName
LPULONG) # _Out_ AuthenticationPackage
# https://msdn.microsoft.com/en-us/library/aa378292
_win(secur32.LsaLogonUser, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ OriginName
SECURITY_LOGON_TYPE, # _In_ LogonType
wintypes.ULONG, # _In_ AuthenticationPackage
wintypes.LPVOID, # _In_ AuthenticationInformation
wintypes.ULONG, # _In_ AuthenticationInformationLength
LPTOKEN_GROUPS, # _In_opt_ LocalGroups
LPTOKEN_SOURCE, # _In_ SourceContext
LPLPVOID, # _Out_ ProfileBuffer
LPULONG, # _Out_ ProfileBufferLength
LPLUID, # _Out_ LogonId
LPHANDLE, # _Out_ Token
LPQUOTA_LIMITS, # _Out_ Quotas
PNTSTATUS) # _Out_ SubStatus
def duplicate_token(source_token=None, access=TOKEN_ALL_ACCESS,
impersonation_level=SecurityImpersonation,
token_type=TokenPrimary, attributes=None):
close_source = False
if source_token is None:
close_source = True
source_token = HANDLE()
advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
TOKEN_ALL_ACCESS, ctypes.byref(source_token))
token = HANDLE()
try:
advapi32.DuplicateTokenEx(source_token, access, attributes,
impersonation_level, token_type, ctypes.byref(token))
finally:
if close_source:
source_token.Close()
return token
def lsa_connect_untrusted():
handle = wintypes.HANDLE()
secur32.LsaConnectUntrusted(ctypes.byref(handle))
return handle.value
def lsa_register_logon_process(logon_process_name):
if not isinstance(logon_process_name, bytes):
logon_process_name = logon_process_name.encode('mbcs')
logon_process_name = logon_process_name[:127]
buf = ctypes.create_string_buffer(logon_process_name, 128)
name = STRING(len(logon_process_name), len(buf), buf)
handle = wintypes.HANDLE()
mode = LSA_OPERATIONAL_MODE()
secur32.LsaRegisterLogonProcess(ctypes.byref(name),
ctypes.byref(handle), ctypes.byref(mode))
return handle.value
def lsa_lookup_authentication_package(lsa_handle, package_name):
if not isinstance(package_name, bytes):
package_name = package_name.encode('mbcs')
package_name = package_name[:127]
buf = ctypes.create_string_buffer(package_name)
name = STRING(len(package_name), len(buf), buf)
package = wintypes.ULONG()
secur32.LsaLookupAuthenticationPackage(lsa_handle, ctypes.byref(name),
ctypes.byref(package))
return package.value
LOGONINFO = collections.namedtuple('LOGONINFO', ('Token', 'LogonId',
'Profile', 'Quotas'))
def lsa_logon_user(auth_info, local_groups=None, origin_name=py_origin_name,
source_context=None, auth_package=None, logon_type=None,
lsa_handle=None):
if local_groups is None:
plocal_groups = LPTOKEN_GROUPS()
else:
plocal_groups = ctypes.byref(local_groups)
if source_context is None:
source_context = py_source_context
if not isinstance(origin_name, bytes):
origin_name = origin_name.encode('mbcs')
buf = ctypes.create_string_buffer(origin_name)
origin_name = STRING(len(origin_name), len(buf), buf)
if auth_package is None:
if isinstance(auth_info, MSV1_0_S4U_LOGON):
auth_package = NEGOTIATE_PACKAGE_NAME
elif isinstance(auth_info, KERB_S4U_LOGON):
auth_package = MICROSOFT_KERBEROS_NAME
else:
auth_package = MSV1_0_PACKAGE_NAME
if logon_type is None:
if isinstance(auth_info, S4ULogon):
logon_type = win32con.LOGON32_LOGON_NETWORK
else:
logon_type = Interactive
profile_buffer = wintypes.LPVOID()
profile_buffer_length = wintypes.ULONG()
profile = None
logonid = LUID()
htoken = HANDLE()
quotas = QUOTA_LIMITS()
substatus = NTSTATUS()
deregister = False
if lsa_handle is None:
lsa_handle = lsa_connect_untrusted()
deregister = True
try:
if isinstance(auth_package, (str, bytes)):
auth_package = lsa_lookup_authentication_package(lsa_handle,
auth_package)
try:
secur32.LsaLogonUser(lsa_handle, ctypes.byref(origin_name),
logon_type, auth_package, ctypes.byref(auth_info),
ctypes.sizeof(auth_info), plocal_groups,
ctypes.byref(source_context), ctypes.byref(profile_buffer),
ctypes.byref(profile_buffer_length), ctypes.byref(logonid),
ctypes.byref(htoken), ctypes.byref(quotas),
ctypes.byref(substatus))
except WindowsError: # pylint: disable=undefined-variable
if substatus.value:
raise ctypes.WinError(substatus.to_error())
raise
finally:
if profile_buffer:
address = profile_buffer.value
buftype = PROFILE_BUFFER_TYPE.from_address(address).value
if buftype == MsV1_0InteractiveLogon:
profile = MSV1_0_INTERACTIVE_PROFILE.from_address_copy(
address, profile_buffer_length.value)
secur32.LsaFreeReturnBuffer(address)
finally:
if deregister:
secur32.LsaDeregisterLogonProcess(lsa_handle)
return LOGONINFO(htoken, logonid, profile, quotas)
def logon_msv1(name, password, domain=None, local_groups=None,
origin_name=py_origin_name, source_context=None):
return lsa_logon_user(MSV1_0_INTERACTIVE_LOGON(name, password, domain),
local_groups, origin_name, source_context)
def logon_msv1_s4u(name, local_groups=None, origin_name=py_origin_name,
source_context=None):
domain = ctypes.create_unicode_buffer(MAX_COMPUTER_NAME_LENGTH + 1)
length = wintypes.DWORD(len(domain))
kernel32.GetComputerNameW(domain, ctypes.byref(length))
return lsa_logon_user(MSV1_0_S4U_LOGON(name, domain.value),
local_groups, origin_name, source_context)
def logon_kerb_s4u(name, realm=None, local_groups=None,
origin_name=py_origin_name,
source_context=None,
logon_process_name=py_logon_process_name):
lsa_handle = lsa_register_logon_process(logon_process_name)
try:
return lsa_logon_user(KERB_S4U_LOGON(name, realm),
local_groups, origin_name, source_context,
lsa_handle=lsa_handle)
finally:
secur32.LsaDeregisterLogonProcess(lsa_handle)
def DuplicateHandle(hsrc=kernel32.GetCurrentProcess(),
srchandle=kernel32.GetCurrentProcess(),
htgt=kernel32.GetCurrentProcess(),
access=0, inherit=False,
options=win32con.DUPLICATE_SAME_ACCESS):
tgthandle = wintypes.HANDLE()
kernel32.DuplicateHandle(hsrc, srchandle,
htgt, ctypes.byref(tgthandle),
access, inherit, options)
return tgthandle.value
def CreatePipe(inherit_read=False, inherit_write=False):
read, write = wintypes.HANDLE(), wintypes.HANDLE()
kernel32.CreatePipe(ctypes.byref(read), ctypes.byref(write), None, 0)
if inherit_read:
kernel32.SetHandleInformation(read, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
if inherit_write:
kernel32.SetHandleInformation(write, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
return read.value, write.value
def set_user_perm(obj, perm, sid):
'''
Set an object permission for the given user sid
'''
info = (
win32security.OWNER_SECURITY_INFORMATION |
win32security.GROUP_SECURITY_INFORMATION |
win32security.DACL_SECURITY_INFORMATION
)
sd = win32security.GetUserObjectSecurity(obj, info)
dacl = sd.GetSecurityDescriptorDacl()
ace_cnt = dacl.GetAceCount()
found = False
for idx in range(0, ace_cnt):
(aceType, aceFlags), ace_mask, ace_sid = dacl.GetAce(idx)
ace_exists = (
aceType == ntsecuritycon.ACCESS_ALLOWED_ACE_TYPE and
ace_mask == perm and
ace_sid == sid
)
if ace_exists:
# If the ace already exists, do nothing
break
else:
dacl.AddAccessAllowedAce(dacl.GetAclRevision(), perm, sid)
sd.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetUserObjectSecurity(obj, info, sd)
def grant_winsta_and_desktop(th):
'''
Grant the token's user access to the current process's window station and
desktop.
'''
current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
# Add permissions for the sid to the current windows station and thread id.
# This prevents windows error 0xC0000142.
winsta = win32process.GetProcessWindowStation()
set_user_perm(winsta, WINSTA_ALL, current_sid)
desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId())
set_user_perm(desktop, DESKTOP_ALL, current_sid)
def environment_string(env):
senv = ''
for k, v in env.items():
senv += k + '=' + v + '\0'
senv += '\0'
return ctypes.create_unicode_buffer(senv)
def CreateProcessWithTokenW(token,
logonflags=0,
applicationname=None,
commandline=None,
creationflags=0,
environment=None,
currentdirectory=None,
startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
if currentdirectory is not None:
currentdirectory = ctypes.create_unicode_buffer(currentdirectory)
if environment:
environment = ctypes.pointer(
environment_string(environment)
)
process_info = PROCESS_INFORMATION()
ret = advapi32.CreateProcessWithTokenW(
token,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
if ret == 0:
winerr = win32api.GetLastError()
exc = WindowsError(win32api.FormatMessage(winerr)) # pylint: disable=undefined-variable
exc.winerror = winerr
raise exc
return process_info
def enumerate_tokens(sid=None, session_id=None, privs=None):
'''
Enumerate tokens from any existing processes that can be accessed.
Optionally filter by sid.
'''
for p in psutil.process_iter():
if p.pid == 0:
continue
try:
ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, p.pid)
except win32api.error as exc:
if exc.winerror == 5:
log.debug("Unable to OpenProcess pid=%d name=%s", p.pid, p.name())
continue
raise exc
try:
access = (
win32security.TOKEN_DUPLICATE |
win32security.TOKEN_QUERY |
win32security.TOKEN_IMPERSONATE |
win32security.TOKEN_ASSIGN_PRIMARY
)
th = win32security.OpenProcessToken(ph, access)
except Exception as exc:
log.debug("OpenProcessToken failed pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
try:
process_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
except Exception as exc:
log.exception("GetTokenInformation pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
proc_sid = win32security.ConvertSidToStringSid(process_sid)
if sid and sid != proc_sid:
log.debug("Token for pid does not match user sid: %s", sid)
continue
if session_id and win32security.GetTokenInformation(th, win32security.TokenSessionId) != session_id:
continue
def has_priv(tok, priv):
luid = win32security.LookupPrivilegeValue(None, priv)
for priv_luid, flags in win32security.GetTokenInformation(tok, win32security.TokenPrivileges):
if priv_luid == luid:
return True
return False
if privs:
has_all = True
for name in privs:
if not has_priv(th, name):
has_all = False
if not has_all:
continue
yield dup_token(th)
# pylint: disable=undefined-variable
def dup_token(th):
'''
duplicate the access token
'''
# TODO: is `duplicate_token` the same?
sec_attr = win32security.SECURITY_ATTRIBUTES()
sec_attr.bInheritHandle = True
return win32security.DuplicateTokenEx(
th,
win32security.SecurityImpersonation,
win32con.MAXIMUM_ALLOWED,
win32security.TokenPrimary,
sec_attr,
)
def elevate_token(th):
'''
Set all token priviledges to enabled
'''
# Get list of privileges this token contains
privileges = win32security.GetTokenInformation(
th, win32security.TokenPrivileges)
# Create a set of all privileges to be enabled
enable_privs = set()
for luid, flags in privileges:
enable_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED))
# Enable the privileges
if win32security.AdjustTokenPrivileges(th, 0, enable_privs) == 0:
raise WindowsError(win32api.FormatMessage(win32api.GetLastError())) # pylint: disable=undefined-variable
def make_inheritable(token):
'''Create an inheritable handle'''
return win32api.DuplicateHandle(
win32api.GetCurrentProcess(),
token,
win32api.GetCurrentProcess(),
0,
1,
win32con.DUPLICATE_SAME_ACCESS
)
def CreateProcessWithLogonW(username=None, domain=None, password=None,
logonflags=0, applicationname=None, commandline=None, creationflags=0,
environment=None, currentdirectory=None, startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
process_info = PROCESS_INFORMATION()
advapi32.CreateProcessWithLogonW(
username,
domain,
password,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
return process_info
|
saltstack/salt | salt/platform/win.py | dup_token | python | def dup_token(th):
'''
duplicate the access token
'''
# TODO: is `duplicate_token` the same?
sec_attr = win32security.SECURITY_ATTRIBUTES()
sec_attr.bInheritHandle = True
return win32security.DuplicateTokenEx(
th,
win32security.SecurityImpersonation,
win32con.MAXIMUM_ALLOWED,
win32security.TokenPrimary,
sec_attr,
) | duplicate the access token | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/platform/win.py#L1131-L1144 | null | # -*- coding: utf-8 -*-
'''
Windows specific utility functions, this module should be imported in a try,
except block because it is only applicable on Windows platforms.
Much of what is here was adapted from the following:
https://stackoverflow.com/a/43233332
http://stackoverflow.com/questions/29566330
'''
from __future__ import absolute_import, unicode_literals
import os
import collections
import logging
import psutil
import ctypes
from ctypes import wintypes
from salt.ext.six.moves import range
from salt.ext.six.moves import zip
import win32con
import win32con
import win32api
import win32process
import win32security
import win32service
import ntsecuritycon
# Set up logging
log = logging.getLogger(__name__)
ntdll = ctypes.WinDLL('ntdll')
secur32 = ctypes.WinDLL('secur32')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
advapi32 = ctypes.WinDLL('advapi32', use_last_error=True)
userenv = ctypes.WinDLL('userenv', use_last_error=True)
SYSTEM_SID = "S-1-5-18"
LOCAL_SRV_SID = "S-1-5-19"
NETWORK_SRV_SID = "S-1-5-19"
LOGON_WITH_PROFILE = 0x00000001
WINSTA_ALL = (
win32con.WINSTA_ACCESSCLIPBOARD |
win32con.WINSTA_ACCESSGLOBALATOMS |
win32con.WINSTA_CREATEDESKTOP |
win32con.WINSTA_ENUMDESKTOPS |
win32con.WINSTA_ENUMERATE |
win32con.WINSTA_EXITWINDOWS |
win32con.WINSTA_READATTRIBUTES |
win32con.WINSTA_READSCREEN |
win32con.WINSTA_WRITEATTRIBUTES |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
DESKTOP_ALL = (
win32con.DESKTOP_CREATEMENU |
win32con.DESKTOP_CREATEWINDOW |
win32con.DESKTOP_ENUMERATE |
win32con.DESKTOP_HOOKCONTROL |
win32con.DESKTOP_JOURNALPLAYBACK |
win32con.DESKTOP_JOURNALRECORD |
win32con.DESKTOP_READOBJECTS |
win32con.DESKTOP_SWITCHDESKTOP |
win32con.DESKTOP_WRITEOBJECTS |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
MAX_COMPUTER_NAME_LENGTH = 15
SECURITY_LOGON_TYPE = wintypes.ULONG
Interactive = 2
Network = 3
Batch = 4
Service = 5
LOGON_SUBMIT_TYPE = wintypes.ULONG
PROFILE_BUFFER_TYPE = wintypes.ULONG
MsV1_0InteractiveLogon = 2
MsV1_0Lm20Logon = 3
MsV1_0NetworkLogon = 4
MsV1_0WorkstationUnlockLogon = 7
MsV1_0S4ULogon = 12
MsV1_0NoElevationLogon = 82
KerbInteractiveLogon = 2
KerbWorkstationUnlockLogon = 7
KerbS4ULogon = 12
MSV1_0_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_IDENTITY = 0x8
TOKEN_SOURCE_LENGTH = 8
NEGOTIATE_PACKAGE_NAME = b'Negotiate'
MICROSOFT_KERBEROS_NAME = b'Kerberos'
MSV1_0_PACKAGE_NAME = b'MICROSOFT_AUTHENTICATION_PACKAGE_V1_0'
DELETE = 0x00010000
READ_CONTROL = 0x00020000
WRITE_DAC = 0x00040000
WRITE_OWNER = 0x00080000
STANDARD_RIGHTS_REQUIRED = (
DELETE |
READ_CONTROL |
WRITE_DAC |
WRITE_OWNER
)
TOKEN_ASSIGN_PRIMARY = 0x0001
TOKEN_DUPLICATE = 0x0002
TOKEN_IMPERSONATE = 0x0004
TOKEN_QUERY = 0x0008
TOKEN_QUERY_SOURCE = 0x0010
TOKEN_ADJUST_PRIVILEGES = 0x0020
TOKEN_ADJUST_GROUPS = 0x0040
TOKEN_ADJUST_DEFAULT = 0x0080
TOKEN_ADJUST_SESSIONID = 0x0100
TOKEN_ALL_ACCESS = (
STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE |
TOKEN_IMPERSONATE |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID
)
DUPLICATE_CLOSE_SOURCE = 0x00000001
DUPLICATE_SAME_ACCESS = 0x00000002
TOKEN_TYPE = wintypes.ULONG
TokenPrimary = 1
TokenImpersonation = 2
SECURITY_IMPERSONATION_LEVEL = wintypes.ULONG
SecurityAnonymous = 0
SecurityIdentification = 1
SecurityImpersonation = 2
SecurityDelegation = 3
class NTSTATUS(wintypes.LONG):
def to_error(self):
return ntdll.RtlNtStatusToDosError(self)
def __repr__(self):
name = self.__class__.__name__
status = wintypes.ULONG.from_buffer(self)
return '{}({})'.format(name, status.value)
PNTSTATUS = ctypes.POINTER(NTSTATUS)
class BOOL(wintypes.BOOL):
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, bool(self))
class HANDLE(wintypes.HANDLE):
__slots__ = 'closed',
def __int__(self):
return self.value or 0
def Detach(self):
if not getattr(self, 'closed', False):
self.closed = True
value = int(self)
self.value = None
return value
raise ValueError("already closed")
def Close(self, CloseHandle=kernel32.CloseHandle):
if self and not getattr(self, 'closed', False):
CloseHandle(self.Detach())
__del__ = Close
def __repr__(self):
return "{}({})".format(self.__class__.__name__, int(self))
class LARGE_INTEGER(wintypes.LARGE_INTEGER):
# https://msdn.microsoft.com/en-us/library/ff553204
ntdll.RtlSecondsSince1970ToTime.restype = None
_unix_epoch = wintypes.LARGE_INTEGER()
ntdll.RtlSecondsSince1970ToTime(0, ctypes.byref(_unix_epoch))
_unix_epoch = _unix_epoch.value
def __int__(self):
return self.value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, self.value)
def as_time(self):
time100ns = self.value - self._unix_epoch
if time100ns >= 0:
return time100ns / 1e7
raise ValueError('value predates the Unix epoch')
@classmethod
def from_time(cls, t):
time100ns = int(t * 10**7)
return cls(time100ns + cls._unix_epoch)
CHAR = ctypes.c_char
WCHAR = ctypes.c_wchar
PCHAR = ctypes.POINTER(CHAR)
PWCHAR = ctypes.POINTER(WCHAR)
class STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PCHAR),
)
LPSTRING = ctypes.POINTER(STRING)
class UNICODE_STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PWCHAR),
)
LPUNICODE_STRING = ctypes.POINTER(UNICODE_STRING)
class LUID(ctypes.Structure):
_fields_ = (
('LowPart', wintypes.DWORD),
('HighPart', wintypes.LONG),
)
def __new__(cls, value=0):
return cls.from_buffer_copy(ctypes.c_ulonglong(value))
def __int__(self):
return ctypes.c_ulonglong.from_buffer(self).value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, int(self))
LPLUID = ctypes.POINTER(LUID)
PSID = wintypes.LPVOID
class SID_AND_ATTRIBUTES(ctypes.Structure):
_fields_ = (
('Sid', PSID),
('Attributes', wintypes.DWORD),
)
LPSID_AND_ATTRIBUTES = ctypes.POINTER(SID_AND_ATTRIBUTES)
class TOKEN_GROUPS(ctypes.Structure):
_fields_ = (
('GroupCount', wintypes.DWORD),
('Groups', SID_AND_ATTRIBUTES * 1),
)
LPTOKEN_GROUPS = ctypes.POINTER(TOKEN_GROUPS)
class TOKEN_SOURCE(ctypes.Structure):
_fields_ = (
('SourceName', CHAR * TOKEN_SOURCE_LENGTH),
('SourceIdentifier', LUID),
)
def __init__(self, SourceName=None, SourceIdentifier=None):
super(TOKEN_SOURCE, self).__init__()
if SourceName is not None:
if not isinstance(SourceName, bytes):
SourceName = SourceName.encode('mbcs')
self.SourceName = SourceName
if SourceIdentifier is None:
luid = self.SourceIdentifier # pylint: disable=access-member-before-definition
ntdll.NtAllocateLocallyUniqueId(ctypes.byref(luid))
else:
self.SourceIdentifier = SourceIdentifier
LPTOKEN_SOURCE = ctypes.POINTER(TOKEN_SOURCE)
py_source_context = TOKEN_SOURCE(b"PYTHON ")
py_origin_name = __name__.encode()
py_logon_process_name = "{}-{}".format(py_origin_name, os.getpid())
SIZE_T = ctypes.c_size_t
class QUOTA_LIMITS(ctypes.Structure):
_fields_ = (('PagedPoolLimit', SIZE_T),
('NonPagedPoolLimit', SIZE_T),
('MinimumWorkingSetSize', SIZE_T),
('MaximumWorkingSetSize', SIZE_T),
('PagefileLimit', SIZE_T),
('TimeLimit', wintypes.LARGE_INTEGER))
LPQUOTA_LIMITS = ctypes.POINTER(QUOTA_LIMITS)
LPULONG = ctypes.POINTER(wintypes.ULONG)
LSA_OPERATIONAL_MODE = wintypes.ULONG
LPLSA_OPERATIONAL_MODE = LPULONG
LPHANDLE = ctypes.POINTER(wintypes.HANDLE)
LPLPVOID = ctypes.POINTER(wintypes.LPVOID)
LPDWORD = ctypes.POINTER(wintypes.DWORD)
class ContiguousUnicode(ctypes.Structure):
# _string_names_: sequence matched to underscore-prefixed fields
def __init__(self, *args, **kwargs):
super(ContiguousUnicode, self).__init__(*args, **kwargs)
def _get_unicode_string(self, name):
wchar_size = ctypes.sizeof(WCHAR)
s = getattr(self, '_{}'.format(name))
length = s.Length // wchar_size
buf = s.Buffer
if buf:
return buf[:length]
return None
def _set_unicode_buffer(self, values):
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
bufsize = (len('\x00'.join(values)) + 1) * wchar_size
ctypes.resize(self, ctypes.sizeof(cls) + bufsize)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for value in values:
bufsize = (len(value) + 1) * wchar_size
ctypes.memmove(addr, value, bufsize)
addr += bufsize
def _set_unicode_string(self, name, value):
values = []
for n in self._string_names_:
if n == name:
values.append(value or '')
else:
values.append(getattr(self, n) or '')
self._set_unicode_buffer(values)
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for n, v in zip(self._string_names_, values):
ptr = ctypes.cast(addr, PWCHAR)
ustr = getattr(self, '_{}'.format(n))
length = ustr.Length = len(v) * wchar_size
full_length = length + wchar_size
if ((n == name and value is None) or
(n != name and not (length or ustr.Buffer))):
ustr.Buffer = None
ustr.MaximumLength = 0
else:
ustr.Buffer = ptr
ustr.MaximumLength = full_length
addr += full_length
def __getattr__(self, name):
if name not in self._string_names_:
raise AttributeError
return self._get_unicode_string(name)
def __setattr__(self, name, value):
if name in self._string_names_:
self._set_unicode_string(name, value)
else:
super(ContiguousUnicode, self).__setattr__(name, value)
@classmethod
def from_address_copy(cls, address, size=None):
x = ctypes.Structure.__new__(cls)
if size is not None:
ctypes.resize(x, size)
ctypes.memmove(ctypes.byref(x), address, ctypes.sizeof(x))
delta = ctypes.addressof(x) - address
for n in cls._string_names_:
ustr = getattr(x, '_{}'.format(n))
addr = ctypes.c_void_p.from_buffer(ustr.Buffer)
if addr:
addr.value += delta
return x
class AuthInfo(ContiguousUnicode):
# _message_type_: from a logon-submit-type enumeration
def __init__(self):
super(AuthInfo, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_LOGON(AuthInfo):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = 'LogonDomainName', 'UserName', 'Password'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('_LogonDomainName', UNICODE_STRING),
('_UserName', UNICODE_STRING),
('_Password', UNICODE_STRING))
def __init__(self, UserName=None, Password=None, LogonDomainName=None):
super(MSV1_0_INTERACTIVE_LOGON, self).__init__()
if LogonDomainName is not None:
self.LogonDomainName = LogonDomainName
if UserName is not None:
self.UserName = UserName
if Password is not None:
self.Password = Password
class S4ULogon(AuthInfo):
_string_names_ = 'UserPrincipalName', 'DomainName'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('Flags', wintypes.ULONG),
('_UserPrincipalName', UNICODE_STRING),
('_DomainName', UNICODE_STRING))
def __init__(self, UserPrincipalName=None, DomainName=None, Flags=0):
super(S4ULogon, self).__init__()
self.Flags = Flags
if UserPrincipalName is not None:
self.UserPrincipalName = UserPrincipalName
if DomainName is not None:
self.DomainName = DomainName
class MSV1_0_S4U_LOGON(S4ULogon):
_message_type_ = MsV1_0S4ULogon
class KERB_S4U_LOGON(S4ULogon):
_message_type_ = KerbS4ULogon
PMSV1_0_S4U_LOGON = ctypes.POINTER(MSV1_0_S4U_LOGON)
PKERB_S4U_LOGON = ctypes.POINTER(KERB_S4U_LOGON)
class ProfileBuffer(ContiguousUnicode):
# _message_type_
def __init__(self):
super(ProfileBuffer, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_PROFILE(ProfileBuffer):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = ('LogonScript', 'HomeDirectory', 'FullName',
'ProfilePath', 'HomeDirectoryDrive', 'LogonServer')
_fields_ = (('MessageType', PROFILE_BUFFER_TYPE),
('LogonCount', wintypes.USHORT),
('BadPasswordCount', wintypes.USHORT),
('LogonTime', LARGE_INTEGER),
('LogoffTime', LARGE_INTEGER),
('KickOffTime', LARGE_INTEGER),
('PasswordLastSet', LARGE_INTEGER),
('PasswordCanChange', LARGE_INTEGER),
('PasswordMustChange', LARGE_INTEGER),
('_LogonScript', UNICODE_STRING),
('_HomeDirectory', UNICODE_STRING),
('_FullName', UNICODE_STRING),
('_ProfilePath', UNICODE_STRING),
('_HomeDirectoryDrive', UNICODE_STRING),
('_LogonServer', UNICODE_STRING),
('UserFlags', wintypes.ULONG))
def _check_status(result, func, args):
if result.value < 0:
raise ctypes.WinError(result.to_error())
return args
def _check_bool(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
INVALID_DWORD_VALUE = wintypes.DWORD(-1).value # ~WinAPI
INFINITE = INVALID_DWORD_VALUE
STD_INPUT_HANDLE = wintypes.DWORD(-10).value
STD_OUTPUT_HANDLE = wintypes.DWORD(-11).value
STD_ERROR_HANDLE = wintypes.DWORD(-12).value
class SECURITY_ATTRIBUTES(ctypes.Structure):
_fields_ = (('nLength', wintypes.DWORD),
('lpSecurityDescriptor', wintypes.LPVOID),
('bInheritHandle', wintypes.BOOL))
def __init__(self, **kwds):
self.nLength = ctypes.sizeof(self)
super(SECURITY_ATTRIBUTES, self).__init__(**kwds)
LPSECURITY_ATTRIBUTES = ctypes.POINTER(SECURITY_ATTRIBUTES)
LPBYTE = ctypes.POINTER(wintypes.BYTE)
LPHANDLE = PHANDLE = ctypes.POINTER(ctypes.c_void_p)
LPDWORD = ctypes.POINTER(ctypes.c_ulong)
class STARTUPINFO(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms686331"""
_fields_ = (('cb', wintypes.DWORD),
('lpReserved', wintypes.LPWSTR),
('lpDesktop', wintypes.LPWSTR),
('lpTitle', wintypes.LPWSTR),
('dwX', wintypes.DWORD),
('dwY', wintypes.DWORD),
('dwXSize', wintypes.DWORD),
('dwYSize', wintypes.DWORD),
('dwXCountChars', wintypes.DWORD),
('dwYCountChars', wintypes.DWORD),
('dwFillAttribute', wintypes.DWORD),
('dwFlags', wintypes.DWORD),
('wShowWindow', wintypes.WORD),
('cbReserved2', wintypes.WORD),
('lpReserved2', LPBYTE),
('hStdInput', wintypes.HANDLE),
('hStdOutput', wintypes.HANDLE),
('hStdError', wintypes.HANDLE))
def __init__(self, **kwds):
self.cb = ctypes.sizeof(self)
super(STARTUPINFO, self).__init__(**kwds)
LPSTARTUPINFO = ctypes.POINTER(STARTUPINFO)
class PROC_THREAD_ATTRIBUTE_LIST(ctypes.Structure):
pass
PPROC_THREAD_ATTRIBUTE_LIST = ctypes.POINTER(PROC_THREAD_ATTRIBUTE_LIST)
class STARTUPINFOEX(STARTUPINFO):
_fields_ = (('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST),)
LPSTARTUPINFOEX = ctypes.POINTER(STARTUPINFOEX)
class PROCESS_INFORMATION(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms684873"""
_fields_ = (('hProcess', wintypes.HANDLE),
('hThread', wintypes.HANDLE),
('dwProcessId', wintypes.DWORD),
('dwThreadId', wintypes.DWORD))
LPPROCESS_INFORMATION = ctypes.POINTER(PROCESS_INFORMATION)
class HANDLE_IHV(wintypes.HANDLE):
pass
def errcheck_ihv(result, func, args):
if result.value == INVALID_HANDLE_VALUE:
raise ctypes.WinError()
return result.value
class DWORD_IDV(wintypes.DWORD):
pass
def errcheck_idv(result, func, args):
if result.value == INVALID_DWORD_VALUE:
raise ctypes.WinError()
return result.value
def errcheck_bool(result, func, args):
if not result:
raise ctypes.WinError()
return args
def _win(func, restype, *argtypes):
func.restype = restype
func.argtypes = argtypes
if issubclass(restype, NTSTATUS):
func.errcheck = _check_status
elif issubclass(restype, BOOL):
func.errcheck = _check_bool
elif issubclass(restype, HANDLE_IHV):
func.errcheck = errcheck_ihv
elif issubclass(restype, DWORD_IDV):
func.errcheck = errcheck_idv
else:
func.errcheck = errcheck_bool
# https://msdn.microsoft.com/en-us/library/ms683231
_win(kernel32.GetStdHandle, HANDLE_IHV,
wintypes.DWORD) # _In_ nStdHandle
# https://msdn.microsoft.com/en-us/library/ms724211
_win(kernel32.CloseHandle, wintypes.BOOL,
wintypes.HANDLE) # _In_ hObject
# https://msdn.microsoft.com/en-us/library/ms724935
_win(kernel32.SetHandleInformation, wintypes.BOOL,
wintypes.HANDLE, # _In_ hObject
wintypes.DWORD, # _In_ dwMask
wintypes.DWORD) # _In_ dwFlags
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, wintypes.BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle,
wintypes.HANDLE, # _In_ hSourceHandle,
wintypes.HANDLE, # _In_ hTargetProcessHandle,
LPHANDLE, # _Out_ lpTargetHandle,
wintypes.DWORD, # _In_ dwDesiredAccess,
wintypes.BOOL, # _In_ bInheritHandle,
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms683189
_win(kernel32.GetExitCodeProcess, wintypes.BOOL,
wintypes.HANDLE, # _In_ hProcess,
LPDWORD) # _Out_ lpExitCode
# https://msdn.microsoft.com/en-us/library/aa365152
_win(kernel32.CreatePipe, wintypes.BOOL,
PHANDLE, # _Out_ hReadPipe,
PHANDLE, # _Out_ hWritePipe,
LPSECURITY_ATTRIBUTES, # _In_opt_ lpPipeAttributes,
wintypes.DWORD) # _In_ nSize
# https://msdn.microsoft.com/en-us/library/ms682431
#_win(advapi32.CreateProcessWithTokenW, wintypes.BOOL,
# PHANDLE, # _In_ lpUsername
# wintypes.DWORD, # _In_ dwLogonFlags
# wintypes.LPCWSTR, # _In_opt_ lpApplicationName
# wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
# wintypes.DWORD, # _In_ dwCreationFlags
# wintypes.LPVOID, # _In_opt_ lpEnvironment
# wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
# LPSTARTUPINFO, # _In_ lpStartupInfo
# LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms682431
_win(advapi32.CreateProcessWithLogonW, wintypes.BOOL,
wintypes.LPCWSTR, # _In_ lpUsername
wintypes.LPCWSTR, # _In_opt_ lpDomain
wintypes.LPCWSTR, # _In_ lpPassword
wintypes.DWORD, # _In_ dwLogonFlags
wintypes.LPCWSTR, # _In_opt_ lpApplicationName
wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
wintypes.DWORD, # _In_ dwCreationFlags
wintypes.LPCWSTR, # _In_opt_ lpEnvironment
wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
LPSTARTUPINFO, # _In_ lpStartupInfo
LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle
wintypes.HANDLE, # _In_ hSourceHandle
wintypes.HANDLE, # _In_ hTargetProcessHandle
LPHANDLE, # _Out_ lpTargetHandle
wintypes.DWORD, # _In_ dwDesiredAccess
wintypes.BOOL, # _In_ bInheritHandle
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms724295
_win(kernel32.GetComputerNameW, BOOL,
wintypes.LPWSTR, # _Out_ lpBuffer
LPDWORD) # _Inout_ lpnSize
# https://msdn.microsoft.com/en-us/library/aa379295
_win(advapi32.OpenProcessToken, BOOL,
wintypes.HANDLE, # _In_ ProcessHandle
wintypes.DWORD, # _In_ DesiredAccess
LPHANDLE) # _Out_ TokenHandle
# https://msdn.microsoft.com/en-us/library/aa446617
_win(advapi32.DuplicateTokenEx, BOOL,
wintypes.HANDLE, # _In_ hExistingToken
wintypes.DWORD, # _In_ dwDesiredAccess
LPSECURITY_ATTRIBUTES, # _In_opt_ lpTokenAttributes
SECURITY_IMPERSONATION_LEVEL, # _In_ ImpersonationLevel
TOKEN_TYPE, # _In_ TokenType
LPHANDLE) # _Out_ phNewToken
# https://msdn.microsoft.com/en-us/library/ff566415
_win(ntdll.NtAllocateLocallyUniqueId, NTSTATUS,
LPLUID) # _Out_ LUID
# https://msdn.microsoft.com/en-us/library/aa378279
_win(secur32.LsaFreeReturnBuffer, NTSTATUS,
wintypes.LPVOID,) # _In_ Buffer
# https://msdn.microsoft.com/en-us/library/aa378265
_win(secur32.LsaConnectUntrusted, NTSTATUS,
LPHANDLE,) # _Out_ LsaHandle
#https://msdn.microsoft.com/en-us/library/aa378318
_win(secur32.LsaRegisterLogonProcess, NTSTATUS,
LPSTRING, # _In_ LogonProcessName
LPHANDLE, # _Out_ LsaHandle
LPLSA_OPERATIONAL_MODE) # _Out_ SecurityMode
# https://msdn.microsoft.com/en-us/library/aa378269
_win(secur32.LsaDeregisterLogonProcess, NTSTATUS,
wintypes.HANDLE) # _In_ LsaHandle
# https://msdn.microsoft.com/en-us/library/aa378297
_win(secur32.LsaLookupAuthenticationPackage, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ PackageName
LPULONG) # _Out_ AuthenticationPackage
# https://msdn.microsoft.com/en-us/library/aa378292
_win(secur32.LsaLogonUser, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ OriginName
SECURITY_LOGON_TYPE, # _In_ LogonType
wintypes.ULONG, # _In_ AuthenticationPackage
wintypes.LPVOID, # _In_ AuthenticationInformation
wintypes.ULONG, # _In_ AuthenticationInformationLength
LPTOKEN_GROUPS, # _In_opt_ LocalGroups
LPTOKEN_SOURCE, # _In_ SourceContext
LPLPVOID, # _Out_ ProfileBuffer
LPULONG, # _Out_ ProfileBufferLength
LPLUID, # _Out_ LogonId
LPHANDLE, # _Out_ Token
LPQUOTA_LIMITS, # _Out_ Quotas
PNTSTATUS) # _Out_ SubStatus
def duplicate_token(source_token=None, access=TOKEN_ALL_ACCESS,
impersonation_level=SecurityImpersonation,
token_type=TokenPrimary, attributes=None):
close_source = False
if source_token is None:
close_source = True
source_token = HANDLE()
advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
TOKEN_ALL_ACCESS, ctypes.byref(source_token))
token = HANDLE()
try:
advapi32.DuplicateTokenEx(source_token, access, attributes,
impersonation_level, token_type, ctypes.byref(token))
finally:
if close_source:
source_token.Close()
return token
def lsa_connect_untrusted():
handle = wintypes.HANDLE()
secur32.LsaConnectUntrusted(ctypes.byref(handle))
return handle.value
def lsa_register_logon_process(logon_process_name):
if not isinstance(logon_process_name, bytes):
logon_process_name = logon_process_name.encode('mbcs')
logon_process_name = logon_process_name[:127]
buf = ctypes.create_string_buffer(logon_process_name, 128)
name = STRING(len(logon_process_name), len(buf), buf)
handle = wintypes.HANDLE()
mode = LSA_OPERATIONAL_MODE()
secur32.LsaRegisterLogonProcess(ctypes.byref(name),
ctypes.byref(handle), ctypes.byref(mode))
return handle.value
def lsa_lookup_authentication_package(lsa_handle, package_name):
if not isinstance(package_name, bytes):
package_name = package_name.encode('mbcs')
package_name = package_name[:127]
buf = ctypes.create_string_buffer(package_name)
name = STRING(len(package_name), len(buf), buf)
package = wintypes.ULONG()
secur32.LsaLookupAuthenticationPackage(lsa_handle, ctypes.byref(name),
ctypes.byref(package))
return package.value
LOGONINFO = collections.namedtuple('LOGONINFO', ('Token', 'LogonId',
'Profile', 'Quotas'))
def lsa_logon_user(auth_info, local_groups=None, origin_name=py_origin_name,
source_context=None, auth_package=None, logon_type=None,
lsa_handle=None):
if local_groups is None:
plocal_groups = LPTOKEN_GROUPS()
else:
plocal_groups = ctypes.byref(local_groups)
if source_context is None:
source_context = py_source_context
if not isinstance(origin_name, bytes):
origin_name = origin_name.encode('mbcs')
buf = ctypes.create_string_buffer(origin_name)
origin_name = STRING(len(origin_name), len(buf), buf)
if auth_package is None:
if isinstance(auth_info, MSV1_0_S4U_LOGON):
auth_package = NEGOTIATE_PACKAGE_NAME
elif isinstance(auth_info, KERB_S4U_LOGON):
auth_package = MICROSOFT_KERBEROS_NAME
else:
auth_package = MSV1_0_PACKAGE_NAME
if logon_type is None:
if isinstance(auth_info, S4ULogon):
logon_type = win32con.LOGON32_LOGON_NETWORK
else:
logon_type = Interactive
profile_buffer = wintypes.LPVOID()
profile_buffer_length = wintypes.ULONG()
profile = None
logonid = LUID()
htoken = HANDLE()
quotas = QUOTA_LIMITS()
substatus = NTSTATUS()
deregister = False
if lsa_handle is None:
lsa_handle = lsa_connect_untrusted()
deregister = True
try:
if isinstance(auth_package, (str, bytes)):
auth_package = lsa_lookup_authentication_package(lsa_handle,
auth_package)
try:
secur32.LsaLogonUser(lsa_handle, ctypes.byref(origin_name),
logon_type, auth_package, ctypes.byref(auth_info),
ctypes.sizeof(auth_info), plocal_groups,
ctypes.byref(source_context), ctypes.byref(profile_buffer),
ctypes.byref(profile_buffer_length), ctypes.byref(logonid),
ctypes.byref(htoken), ctypes.byref(quotas),
ctypes.byref(substatus))
except WindowsError: # pylint: disable=undefined-variable
if substatus.value:
raise ctypes.WinError(substatus.to_error())
raise
finally:
if profile_buffer:
address = profile_buffer.value
buftype = PROFILE_BUFFER_TYPE.from_address(address).value
if buftype == MsV1_0InteractiveLogon:
profile = MSV1_0_INTERACTIVE_PROFILE.from_address_copy(
address, profile_buffer_length.value)
secur32.LsaFreeReturnBuffer(address)
finally:
if deregister:
secur32.LsaDeregisterLogonProcess(lsa_handle)
return LOGONINFO(htoken, logonid, profile, quotas)
def logon_msv1(name, password, domain=None, local_groups=None,
origin_name=py_origin_name, source_context=None):
return lsa_logon_user(MSV1_0_INTERACTIVE_LOGON(name, password, domain),
local_groups, origin_name, source_context)
def logon_msv1_s4u(name, local_groups=None, origin_name=py_origin_name,
source_context=None):
domain = ctypes.create_unicode_buffer(MAX_COMPUTER_NAME_LENGTH + 1)
length = wintypes.DWORD(len(domain))
kernel32.GetComputerNameW(domain, ctypes.byref(length))
return lsa_logon_user(MSV1_0_S4U_LOGON(name, domain.value),
local_groups, origin_name, source_context)
def logon_kerb_s4u(name, realm=None, local_groups=None,
origin_name=py_origin_name,
source_context=None,
logon_process_name=py_logon_process_name):
lsa_handle = lsa_register_logon_process(logon_process_name)
try:
return lsa_logon_user(KERB_S4U_LOGON(name, realm),
local_groups, origin_name, source_context,
lsa_handle=lsa_handle)
finally:
secur32.LsaDeregisterLogonProcess(lsa_handle)
def DuplicateHandle(hsrc=kernel32.GetCurrentProcess(),
srchandle=kernel32.GetCurrentProcess(),
htgt=kernel32.GetCurrentProcess(),
access=0, inherit=False,
options=win32con.DUPLICATE_SAME_ACCESS):
tgthandle = wintypes.HANDLE()
kernel32.DuplicateHandle(hsrc, srchandle,
htgt, ctypes.byref(tgthandle),
access, inherit, options)
return tgthandle.value
def CreatePipe(inherit_read=False, inherit_write=False):
read, write = wintypes.HANDLE(), wintypes.HANDLE()
kernel32.CreatePipe(ctypes.byref(read), ctypes.byref(write), None, 0)
if inherit_read:
kernel32.SetHandleInformation(read, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
if inherit_write:
kernel32.SetHandleInformation(write, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
return read.value, write.value
def set_user_perm(obj, perm, sid):
'''
Set an object permission for the given user sid
'''
info = (
win32security.OWNER_SECURITY_INFORMATION |
win32security.GROUP_SECURITY_INFORMATION |
win32security.DACL_SECURITY_INFORMATION
)
sd = win32security.GetUserObjectSecurity(obj, info)
dacl = sd.GetSecurityDescriptorDacl()
ace_cnt = dacl.GetAceCount()
found = False
for idx in range(0, ace_cnt):
(aceType, aceFlags), ace_mask, ace_sid = dacl.GetAce(idx)
ace_exists = (
aceType == ntsecuritycon.ACCESS_ALLOWED_ACE_TYPE and
ace_mask == perm and
ace_sid == sid
)
if ace_exists:
# If the ace already exists, do nothing
break
else:
dacl.AddAccessAllowedAce(dacl.GetAclRevision(), perm, sid)
sd.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetUserObjectSecurity(obj, info, sd)
def grant_winsta_and_desktop(th):
'''
Grant the token's user access to the current process's window station and
desktop.
'''
current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
# Add permissions for the sid to the current windows station and thread id.
# This prevents windows error 0xC0000142.
winsta = win32process.GetProcessWindowStation()
set_user_perm(winsta, WINSTA_ALL, current_sid)
desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId())
set_user_perm(desktop, DESKTOP_ALL, current_sid)
def environment_string(env):
senv = ''
for k, v in env.items():
senv += k + '=' + v + '\0'
senv += '\0'
return ctypes.create_unicode_buffer(senv)
def CreateProcessWithTokenW(token,
logonflags=0,
applicationname=None,
commandline=None,
creationflags=0,
environment=None,
currentdirectory=None,
startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
if currentdirectory is not None:
currentdirectory = ctypes.create_unicode_buffer(currentdirectory)
if environment:
environment = ctypes.pointer(
environment_string(environment)
)
process_info = PROCESS_INFORMATION()
ret = advapi32.CreateProcessWithTokenW(
token,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
if ret == 0:
winerr = win32api.GetLastError()
exc = WindowsError(win32api.FormatMessage(winerr)) # pylint: disable=undefined-variable
exc.winerror = winerr
raise exc
return process_info
def enumerate_tokens(sid=None, session_id=None, privs=None):
'''
Enumerate tokens from any existing processes that can be accessed.
Optionally filter by sid.
'''
for p in psutil.process_iter():
if p.pid == 0:
continue
try:
ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, p.pid)
except win32api.error as exc:
if exc.winerror == 5:
log.debug("Unable to OpenProcess pid=%d name=%s", p.pid, p.name())
continue
raise exc
try:
access = (
win32security.TOKEN_DUPLICATE |
win32security.TOKEN_QUERY |
win32security.TOKEN_IMPERSONATE |
win32security.TOKEN_ASSIGN_PRIMARY
)
th = win32security.OpenProcessToken(ph, access)
except Exception as exc:
log.debug("OpenProcessToken failed pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
try:
process_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
except Exception as exc:
log.exception("GetTokenInformation pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
proc_sid = win32security.ConvertSidToStringSid(process_sid)
if sid and sid != proc_sid:
log.debug("Token for pid does not match user sid: %s", sid)
continue
if session_id and win32security.GetTokenInformation(th, win32security.TokenSessionId) != session_id:
continue
def has_priv(tok, priv):
luid = win32security.LookupPrivilegeValue(None, priv)
for priv_luid, flags in win32security.GetTokenInformation(tok, win32security.TokenPrivileges):
if priv_luid == luid:
return True
return False
if privs:
has_all = True
for name in privs:
if not has_priv(th, name):
has_all = False
if not has_all:
continue
yield dup_token(th)
def impersonate_sid(sid, session_id=None, privs=None):
'''
Find an existing process token for the given sid and impersonate the token.
'''
for tok in enumerate_tokens(sid, session_id, privs):
tok = dup_token(tok)
elevate_token(tok)
if win32security.ImpersonateLoggedOnUser(tok) == 0:
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
return tok
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
def elevate_token(th):
'''
Set all token priviledges to enabled
'''
# Get list of privileges this token contains
privileges = win32security.GetTokenInformation(
th, win32security.TokenPrivileges)
# Create a set of all privileges to be enabled
enable_privs = set()
for luid, flags in privileges:
enable_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED))
# Enable the privileges
if win32security.AdjustTokenPrivileges(th, 0, enable_privs) == 0:
raise WindowsError(win32api.FormatMessage(win32api.GetLastError())) # pylint: disable=undefined-variable
def make_inheritable(token):
'''Create an inheritable handle'''
return win32api.DuplicateHandle(
win32api.GetCurrentProcess(),
token,
win32api.GetCurrentProcess(),
0,
1,
win32con.DUPLICATE_SAME_ACCESS
)
def CreateProcessWithLogonW(username=None, domain=None, password=None,
logonflags=0, applicationname=None, commandline=None, creationflags=0,
environment=None, currentdirectory=None, startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
process_info = PROCESS_INFORMATION()
advapi32.CreateProcessWithLogonW(
username,
domain,
password,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
return process_info
|
saltstack/salt | salt/platform/win.py | elevate_token | python | def elevate_token(th):
'''
Set all token priviledges to enabled
'''
# Get list of privileges this token contains
privileges = win32security.GetTokenInformation(
th, win32security.TokenPrivileges)
# Create a set of all privileges to be enabled
enable_privs = set()
for luid, flags in privileges:
enable_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED))
# Enable the privileges
if win32security.AdjustTokenPrivileges(th, 0, enable_privs) == 0:
raise WindowsError(win32api.FormatMessage(win32api.GetLastError())) | Set all token priviledges to enabled | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/platform/win.py#L1147-L1162 | null | # -*- coding: utf-8 -*-
'''
Windows specific utility functions, this module should be imported in a try,
except block because it is only applicable on Windows platforms.
Much of what is here was adapted from the following:
https://stackoverflow.com/a/43233332
http://stackoverflow.com/questions/29566330
'''
from __future__ import absolute_import, unicode_literals
import os
import collections
import logging
import psutil
import ctypes
from ctypes import wintypes
from salt.ext.six.moves import range
from salt.ext.six.moves import zip
import win32con
import win32con
import win32api
import win32process
import win32security
import win32service
import ntsecuritycon
# Set up logging
log = logging.getLogger(__name__)
ntdll = ctypes.WinDLL('ntdll')
secur32 = ctypes.WinDLL('secur32')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
advapi32 = ctypes.WinDLL('advapi32', use_last_error=True)
userenv = ctypes.WinDLL('userenv', use_last_error=True)
SYSTEM_SID = "S-1-5-18"
LOCAL_SRV_SID = "S-1-5-19"
NETWORK_SRV_SID = "S-1-5-19"
LOGON_WITH_PROFILE = 0x00000001
WINSTA_ALL = (
win32con.WINSTA_ACCESSCLIPBOARD |
win32con.WINSTA_ACCESSGLOBALATOMS |
win32con.WINSTA_CREATEDESKTOP |
win32con.WINSTA_ENUMDESKTOPS |
win32con.WINSTA_ENUMERATE |
win32con.WINSTA_EXITWINDOWS |
win32con.WINSTA_READATTRIBUTES |
win32con.WINSTA_READSCREEN |
win32con.WINSTA_WRITEATTRIBUTES |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
DESKTOP_ALL = (
win32con.DESKTOP_CREATEMENU |
win32con.DESKTOP_CREATEWINDOW |
win32con.DESKTOP_ENUMERATE |
win32con.DESKTOP_HOOKCONTROL |
win32con.DESKTOP_JOURNALPLAYBACK |
win32con.DESKTOP_JOURNALRECORD |
win32con.DESKTOP_READOBJECTS |
win32con.DESKTOP_SWITCHDESKTOP |
win32con.DESKTOP_WRITEOBJECTS |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
MAX_COMPUTER_NAME_LENGTH = 15
SECURITY_LOGON_TYPE = wintypes.ULONG
Interactive = 2
Network = 3
Batch = 4
Service = 5
LOGON_SUBMIT_TYPE = wintypes.ULONG
PROFILE_BUFFER_TYPE = wintypes.ULONG
MsV1_0InteractiveLogon = 2
MsV1_0Lm20Logon = 3
MsV1_0NetworkLogon = 4
MsV1_0WorkstationUnlockLogon = 7
MsV1_0S4ULogon = 12
MsV1_0NoElevationLogon = 82
KerbInteractiveLogon = 2
KerbWorkstationUnlockLogon = 7
KerbS4ULogon = 12
MSV1_0_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_IDENTITY = 0x8
TOKEN_SOURCE_LENGTH = 8
NEGOTIATE_PACKAGE_NAME = b'Negotiate'
MICROSOFT_KERBEROS_NAME = b'Kerberos'
MSV1_0_PACKAGE_NAME = b'MICROSOFT_AUTHENTICATION_PACKAGE_V1_0'
DELETE = 0x00010000
READ_CONTROL = 0x00020000
WRITE_DAC = 0x00040000
WRITE_OWNER = 0x00080000
STANDARD_RIGHTS_REQUIRED = (
DELETE |
READ_CONTROL |
WRITE_DAC |
WRITE_OWNER
)
TOKEN_ASSIGN_PRIMARY = 0x0001
TOKEN_DUPLICATE = 0x0002
TOKEN_IMPERSONATE = 0x0004
TOKEN_QUERY = 0x0008
TOKEN_QUERY_SOURCE = 0x0010
TOKEN_ADJUST_PRIVILEGES = 0x0020
TOKEN_ADJUST_GROUPS = 0x0040
TOKEN_ADJUST_DEFAULT = 0x0080
TOKEN_ADJUST_SESSIONID = 0x0100
TOKEN_ALL_ACCESS = (
STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE |
TOKEN_IMPERSONATE |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID
)
DUPLICATE_CLOSE_SOURCE = 0x00000001
DUPLICATE_SAME_ACCESS = 0x00000002
TOKEN_TYPE = wintypes.ULONG
TokenPrimary = 1
TokenImpersonation = 2
SECURITY_IMPERSONATION_LEVEL = wintypes.ULONG
SecurityAnonymous = 0
SecurityIdentification = 1
SecurityImpersonation = 2
SecurityDelegation = 3
class NTSTATUS(wintypes.LONG):
def to_error(self):
return ntdll.RtlNtStatusToDosError(self)
def __repr__(self):
name = self.__class__.__name__
status = wintypes.ULONG.from_buffer(self)
return '{}({})'.format(name, status.value)
PNTSTATUS = ctypes.POINTER(NTSTATUS)
class BOOL(wintypes.BOOL):
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, bool(self))
class HANDLE(wintypes.HANDLE):
__slots__ = 'closed',
def __int__(self):
return self.value or 0
def Detach(self):
if not getattr(self, 'closed', False):
self.closed = True
value = int(self)
self.value = None
return value
raise ValueError("already closed")
def Close(self, CloseHandle=kernel32.CloseHandle):
if self and not getattr(self, 'closed', False):
CloseHandle(self.Detach())
__del__ = Close
def __repr__(self):
return "{}({})".format(self.__class__.__name__, int(self))
class LARGE_INTEGER(wintypes.LARGE_INTEGER):
# https://msdn.microsoft.com/en-us/library/ff553204
ntdll.RtlSecondsSince1970ToTime.restype = None
_unix_epoch = wintypes.LARGE_INTEGER()
ntdll.RtlSecondsSince1970ToTime(0, ctypes.byref(_unix_epoch))
_unix_epoch = _unix_epoch.value
def __int__(self):
return self.value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, self.value)
def as_time(self):
time100ns = self.value - self._unix_epoch
if time100ns >= 0:
return time100ns / 1e7
raise ValueError('value predates the Unix epoch')
@classmethod
def from_time(cls, t):
time100ns = int(t * 10**7)
return cls(time100ns + cls._unix_epoch)
CHAR = ctypes.c_char
WCHAR = ctypes.c_wchar
PCHAR = ctypes.POINTER(CHAR)
PWCHAR = ctypes.POINTER(WCHAR)
class STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PCHAR),
)
LPSTRING = ctypes.POINTER(STRING)
class UNICODE_STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PWCHAR),
)
LPUNICODE_STRING = ctypes.POINTER(UNICODE_STRING)
class LUID(ctypes.Structure):
_fields_ = (
('LowPart', wintypes.DWORD),
('HighPart', wintypes.LONG),
)
def __new__(cls, value=0):
return cls.from_buffer_copy(ctypes.c_ulonglong(value))
def __int__(self):
return ctypes.c_ulonglong.from_buffer(self).value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, int(self))
LPLUID = ctypes.POINTER(LUID)
PSID = wintypes.LPVOID
class SID_AND_ATTRIBUTES(ctypes.Structure):
_fields_ = (
('Sid', PSID),
('Attributes', wintypes.DWORD),
)
LPSID_AND_ATTRIBUTES = ctypes.POINTER(SID_AND_ATTRIBUTES)
class TOKEN_GROUPS(ctypes.Structure):
_fields_ = (
('GroupCount', wintypes.DWORD),
('Groups', SID_AND_ATTRIBUTES * 1),
)
LPTOKEN_GROUPS = ctypes.POINTER(TOKEN_GROUPS)
class TOKEN_SOURCE(ctypes.Structure):
_fields_ = (
('SourceName', CHAR * TOKEN_SOURCE_LENGTH),
('SourceIdentifier', LUID),
)
def __init__(self, SourceName=None, SourceIdentifier=None):
super(TOKEN_SOURCE, self).__init__()
if SourceName is not None:
if not isinstance(SourceName, bytes):
SourceName = SourceName.encode('mbcs')
self.SourceName = SourceName
if SourceIdentifier is None:
luid = self.SourceIdentifier # pylint: disable=access-member-before-definition
ntdll.NtAllocateLocallyUniqueId(ctypes.byref(luid))
else:
self.SourceIdentifier = SourceIdentifier
LPTOKEN_SOURCE = ctypes.POINTER(TOKEN_SOURCE)
py_source_context = TOKEN_SOURCE(b"PYTHON ")
py_origin_name = __name__.encode()
py_logon_process_name = "{}-{}".format(py_origin_name, os.getpid())
SIZE_T = ctypes.c_size_t
class QUOTA_LIMITS(ctypes.Structure):
_fields_ = (('PagedPoolLimit', SIZE_T),
('NonPagedPoolLimit', SIZE_T),
('MinimumWorkingSetSize', SIZE_T),
('MaximumWorkingSetSize', SIZE_T),
('PagefileLimit', SIZE_T),
('TimeLimit', wintypes.LARGE_INTEGER))
LPQUOTA_LIMITS = ctypes.POINTER(QUOTA_LIMITS)
LPULONG = ctypes.POINTER(wintypes.ULONG)
LSA_OPERATIONAL_MODE = wintypes.ULONG
LPLSA_OPERATIONAL_MODE = LPULONG
LPHANDLE = ctypes.POINTER(wintypes.HANDLE)
LPLPVOID = ctypes.POINTER(wintypes.LPVOID)
LPDWORD = ctypes.POINTER(wintypes.DWORD)
class ContiguousUnicode(ctypes.Structure):
# _string_names_: sequence matched to underscore-prefixed fields
def __init__(self, *args, **kwargs):
super(ContiguousUnicode, self).__init__(*args, **kwargs)
def _get_unicode_string(self, name):
wchar_size = ctypes.sizeof(WCHAR)
s = getattr(self, '_{}'.format(name))
length = s.Length // wchar_size
buf = s.Buffer
if buf:
return buf[:length]
return None
def _set_unicode_buffer(self, values):
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
bufsize = (len('\x00'.join(values)) + 1) * wchar_size
ctypes.resize(self, ctypes.sizeof(cls) + bufsize)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for value in values:
bufsize = (len(value) + 1) * wchar_size
ctypes.memmove(addr, value, bufsize)
addr += bufsize
def _set_unicode_string(self, name, value):
values = []
for n in self._string_names_:
if n == name:
values.append(value or '')
else:
values.append(getattr(self, n) or '')
self._set_unicode_buffer(values)
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for n, v in zip(self._string_names_, values):
ptr = ctypes.cast(addr, PWCHAR)
ustr = getattr(self, '_{}'.format(n))
length = ustr.Length = len(v) * wchar_size
full_length = length + wchar_size
if ((n == name and value is None) or
(n != name and not (length or ustr.Buffer))):
ustr.Buffer = None
ustr.MaximumLength = 0
else:
ustr.Buffer = ptr
ustr.MaximumLength = full_length
addr += full_length
def __getattr__(self, name):
if name not in self._string_names_:
raise AttributeError
return self._get_unicode_string(name)
def __setattr__(self, name, value):
if name in self._string_names_:
self._set_unicode_string(name, value)
else:
super(ContiguousUnicode, self).__setattr__(name, value)
@classmethod
def from_address_copy(cls, address, size=None):
x = ctypes.Structure.__new__(cls)
if size is not None:
ctypes.resize(x, size)
ctypes.memmove(ctypes.byref(x), address, ctypes.sizeof(x))
delta = ctypes.addressof(x) - address
for n in cls._string_names_:
ustr = getattr(x, '_{}'.format(n))
addr = ctypes.c_void_p.from_buffer(ustr.Buffer)
if addr:
addr.value += delta
return x
class AuthInfo(ContiguousUnicode):
# _message_type_: from a logon-submit-type enumeration
def __init__(self):
super(AuthInfo, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_LOGON(AuthInfo):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = 'LogonDomainName', 'UserName', 'Password'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('_LogonDomainName', UNICODE_STRING),
('_UserName', UNICODE_STRING),
('_Password', UNICODE_STRING))
def __init__(self, UserName=None, Password=None, LogonDomainName=None):
super(MSV1_0_INTERACTIVE_LOGON, self).__init__()
if LogonDomainName is not None:
self.LogonDomainName = LogonDomainName
if UserName is not None:
self.UserName = UserName
if Password is not None:
self.Password = Password
class S4ULogon(AuthInfo):
_string_names_ = 'UserPrincipalName', 'DomainName'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('Flags', wintypes.ULONG),
('_UserPrincipalName', UNICODE_STRING),
('_DomainName', UNICODE_STRING))
def __init__(self, UserPrincipalName=None, DomainName=None, Flags=0):
super(S4ULogon, self).__init__()
self.Flags = Flags
if UserPrincipalName is not None:
self.UserPrincipalName = UserPrincipalName
if DomainName is not None:
self.DomainName = DomainName
class MSV1_0_S4U_LOGON(S4ULogon):
_message_type_ = MsV1_0S4ULogon
class KERB_S4U_LOGON(S4ULogon):
_message_type_ = KerbS4ULogon
PMSV1_0_S4U_LOGON = ctypes.POINTER(MSV1_0_S4U_LOGON)
PKERB_S4U_LOGON = ctypes.POINTER(KERB_S4U_LOGON)
class ProfileBuffer(ContiguousUnicode):
# _message_type_
def __init__(self):
super(ProfileBuffer, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_PROFILE(ProfileBuffer):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = ('LogonScript', 'HomeDirectory', 'FullName',
'ProfilePath', 'HomeDirectoryDrive', 'LogonServer')
_fields_ = (('MessageType', PROFILE_BUFFER_TYPE),
('LogonCount', wintypes.USHORT),
('BadPasswordCount', wintypes.USHORT),
('LogonTime', LARGE_INTEGER),
('LogoffTime', LARGE_INTEGER),
('KickOffTime', LARGE_INTEGER),
('PasswordLastSet', LARGE_INTEGER),
('PasswordCanChange', LARGE_INTEGER),
('PasswordMustChange', LARGE_INTEGER),
('_LogonScript', UNICODE_STRING),
('_HomeDirectory', UNICODE_STRING),
('_FullName', UNICODE_STRING),
('_ProfilePath', UNICODE_STRING),
('_HomeDirectoryDrive', UNICODE_STRING),
('_LogonServer', UNICODE_STRING),
('UserFlags', wintypes.ULONG))
def _check_status(result, func, args):
if result.value < 0:
raise ctypes.WinError(result.to_error())
return args
def _check_bool(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
INVALID_DWORD_VALUE = wintypes.DWORD(-1).value # ~WinAPI
INFINITE = INVALID_DWORD_VALUE
STD_INPUT_HANDLE = wintypes.DWORD(-10).value
STD_OUTPUT_HANDLE = wintypes.DWORD(-11).value
STD_ERROR_HANDLE = wintypes.DWORD(-12).value
class SECURITY_ATTRIBUTES(ctypes.Structure):
_fields_ = (('nLength', wintypes.DWORD),
('lpSecurityDescriptor', wintypes.LPVOID),
('bInheritHandle', wintypes.BOOL))
def __init__(self, **kwds):
self.nLength = ctypes.sizeof(self)
super(SECURITY_ATTRIBUTES, self).__init__(**kwds)
LPSECURITY_ATTRIBUTES = ctypes.POINTER(SECURITY_ATTRIBUTES)
LPBYTE = ctypes.POINTER(wintypes.BYTE)
LPHANDLE = PHANDLE = ctypes.POINTER(ctypes.c_void_p)
LPDWORD = ctypes.POINTER(ctypes.c_ulong)
class STARTUPINFO(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms686331"""
_fields_ = (('cb', wintypes.DWORD),
('lpReserved', wintypes.LPWSTR),
('lpDesktop', wintypes.LPWSTR),
('lpTitle', wintypes.LPWSTR),
('dwX', wintypes.DWORD),
('dwY', wintypes.DWORD),
('dwXSize', wintypes.DWORD),
('dwYSize', wintypes.DWORD),
('dwXCountChars', wintypes.DWORD),
('dwYCountChars', wintypes.DWORD),
('dwFillAttribute', wintypes.DWORD),
('dwFlags', wintypes.DWORD),
('wShowWindow', wintypes.WORD),
('cbReserved2', wintypes.WORD),
('lpReserved2', LPBYTE),
('hStdInput', wintypes.HANDLE),
('hStdOutput', wintypes.HANDLE),
('hStdError', wintypes.HANDLE))
def __init__(self, **kwds):
self.cb = ctypes.sizeof(self)
super(STARTUPINFO, self).__init__(**kwds)
LPSTARTUPINFO = ctypes.POINTER(STARTUPINFO)
class PROC_THREAD_ATTRIBUTE_LIST(ctypes.Structure):
pass
PPROC_THREAD_ATTRIBUTE_LIST = ctypes.POINTER(PROC_THREAD_ATTRIBUTE_LIST)
class STARTUPINFOEX(STARTUPINFO):
_fields_ = (('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST),)
LPSTARTUPINFOEX = ctypes.POINTER(STARTUPINFOEX)
class PROCESS_INFORMATION(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms684873"""
_fields_ = (('hProcess', wintypes.HANDLE),
('hThread', wintypes.HANDLE),
('dwProcessId', wintypes.DWORD),
('dwThreadId', wintypes.DWORD))
LPPROCESS_INFORMATION = ctypes.POINTER(PROCESS_INFORMATION)
class HANDLE_IHV(wintypes.HANDLE):
pass
def errcheck_ihv(result, func, args):
if result.value == INVALID_HANDLE_VALUE:
raise ctypes.WinError()
return result.value
class DWORD_IDV(wintypes.DWORD):
pass
def errcheck_idv(result, func, args):
if result.value == INVALID_DWORD_VALUE:
raise ctypes.WinError()
return result.value
def errcheck_bool(result, func, args):
if not result:
raise ctypes.WinError()
return args
def _win(func, restype, *argtypes):
func.restype = restype
func.argtypes = argtypes
if issubclass(restype, NTSTATUS):
func.errcheck = _check_status
elif issubclass(restype, BOOL):
func.errcheck = _check_bool
elif issubclass(restype, HANDLE_IHV):
func.errcheck = errcheck_ihv
elif issubclass(restype, DWORD_IDV):
func.errcheck = errcheck_idv
else:
func.errcheck = errcheck_bool
# https://msdn.microsoft.com/en-us/library/ms683231
_win(kernel32.GetStdHandle, HANDLE_IHV,
wintypes.DWORD) # _In_ nStdHandle
# https://msdn.microsoft.com/en-us/library/ms724211
_win(kernel32.CloseHandle, wintypes.BOOL,
wintypes.HANDLE) # _In_ hObject
# https://msdn.microsoft.com/en-us/library/ms724935
_win(kernel32.SetHandleInformation, wintypes.BOOL,
wintypes.HANDLE, # _In_ hObject
wintypes.DWORD, # _In_ dwMask
wintypes.DWORD) # _In_ dwFlags
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, wintypes.BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle,
wintypes.HANDLE, # _In_ hSourceHandle,
wintypes.HANDLE, # _In_ hTargetProcessHandle,
LPHANDLE, # _Out_ lpTargetHandle,
wintypes.DWORD, # _In_ dwDesiredAccess,
wintypes.BOOL, # _In_ bInheritHandle,
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms683189
_win(kernel32.GetExitCodeProcess, wintypes.BOOL,
wintypes.HANDLE, # _In_ hProcess,
LPDWORD) # _Out_ lpExitCode
# https://msdn.microsoft.com/en-us/library/aa365152
_win(kernel32.CreatePipe, wintypes.BOOL,
PHANDLE, # _Out_ hReadPipe,
PHANDLE, # _Out_ hWritePipe,
LPSECURITY_ATTRIBUTES, # _In_opt_ lpPipeAttributes,
wintypes.DWORD) # _In_ nSize
# https://msdn.microsoft.com/en-us/library/ms682431
#_win(advapi32.CreateProcessWithTokenW, wintypes.BOOL,
# PHANDLE, # _In_ lpUsername
# wintypes.DWORD, # _In_ dwLogonFlags
# wintypes.LPCWSTR, # _In_opt_ lpApplicationName
# wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
# wintypes.DWORD, # _In_ dwCreationFlags
# wintypes.LPVOID, # _In_opt_ lpEnvironment
# wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
# LPSTARTUPINFO, # _In_ lpStartupInfo
# LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms682431
_win(advapi32.CreateProcessWithLogonW, wintypes.BOOL,
wintypes.LPCWSTR, # _In_ lpUsername
wintypes.LPCWSTR, # _In_opt_ lpDomain
wintypes.LPCWSTR, # _In_ lpPassword
wintypes.DWORD, # _In_ dwLogonFlags
wintypes.LPCWSTR, # _In_opt_ lpApplicationName
wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
wintypes.DWORD, # _In_ dwCreationFlags
wintypes.LPCWSTR, # _In_opt_ lpEnvironment
wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
LPSTARTUPINFO, # _In_ lpStartupInfo
LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle
wintypes.HANDLE, # _In_ hSourceHandle
wintypes.HANDLE, # _In_ hTargetProcessHandle
LPHANDLE, # _Out_ lpTargetHandle
wintypes.DWORD, # _In_ dwDesiredAccess
wintypes.BOOL, # _In_ bInheritHandle
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms724295
_win(kernel32.GetComputerNameW, BOOL,
wintypes.LPWSTR, # _Out_ lpBuffer
LPDWORD) # _Inout_ lpnSize
# https://msdn.microsoft.com/en-us/library/aa379295
_win(advapi32.OpenProcessToken, BOOL,
wintypes.HANDLE, # _In_ ProcessHandle
wintypes.DWORD, # _In_ DesiredAccess
LPHANDLE) # _Out_ TokenHandle
# https://msdn.microsoft.com/en-us/library/aa446617
_win(advapi32.DuplicateTokenEx, BOOL,
wintypes.HANDLE, # _In_ hExistingToken
wintypes.DWORD, # _In_ dwDesiredAccess
LPSECURITY_ATTRIBUTES, # _In_opt_ lpTokenAttributes
SECURITY_IMPERSONATION_LEVEL, # _In_ ImpersonationLevel
TOKEN_TYPE, # _In_ TokenType
LPHANDLE) # _Out_ phNewToken
# https://msdn.microsoft.com/en-us/library/ff566415
_win(ntdll.NtAllocateLocallyUniqueId, NTSTATUS,
LPLUID) # _Out_ LUID
# https://msdn.microsoft.com/en-us/library/aa378279
_win(secur32.LsaFreeReturnBuffer, NTSTATUS,
wintypes.LPVOID,) # _In_ Buffer
# https://msdn.microsoft.com/en-us/library/aa378265
_win(secur32.LsaConnectUntrusted, NTSTATUS,
LPHANDLE,) # _Out_ LsaHandle
#https://msdn.microsoft.com/en-us/library/aa378318
_win(secur32.LsaRegisterLogonProcess, NTSTATUS,
LPSTRING, # _In_ LogonProcessName
LPHANDLE, # _Out_ LsaHandle
LPLSA_OPERATIONAL_MODE) # _Out_ SecurityMode
# https://msdn.microsoft.com/en-us/library/aa378269
_win(secur32.LsaDeregisterLogonProcess, NTSTATUS,
wintypes.HANDLE) # _In_ LsaHandle
# https://msdn.microsoft.com/en-us/library/aa378297
_win(secur32.LsaLookupAuthenticationPackage, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ PackageName
LPULONG) # _Out_ AuthenticationPackage
# https://msdn.microsoft.com/en-us/library/aa378292
_win(secur32.LsaLogonUser, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ OriginName
SECURITY_LOGON_TYPE, # _In_ LogonType
wintypes.ULONG, # _In_ AuthenticationPackage
wintypes.LPVOID, # _In_ AuthenticationInformation
wintypes.ULONG, # _In_ AuthenticationInformationLength
LPTOKEN_GROUPS, # _In_opt_ LocalGroups
LPTOKEN_SOURCE, # _In_ SourceContext
LPLPVOID, # _Out_ ProfileBuffer
LPULONG, # _Out_ ProfileBufferLength
LPLUID, # _Out_ LogonId
LPHANDLE, # _Out_ Token
LPQUOTA_LIMITS, # _Out_ Quotas
PNTSTATUS) # _Out_ SubStatus
def duplicate_token(source_token=None, access=TOKEN_ALL_ACCESS,
impersonation_level=SecurityImpersonation,
token_type=TokenPrimary, attributes=None):
close_source = False
if source_token is None:
close_source = True
source_token = HANDLE()
advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
TOKEN_ALL_ACCESS, ctypes.byref(source_token))
token = HANDLE()
try:
advapi32.DuplicateTokenEx(source_token, access, attributes,
impersonation_level, token_type, ctypes.byref(token))
finally:
if close_source:
source_token.Close()
return token
def lsa_connect_untrusted():
handle = wintypes.HANDLE()
secur32.LsaConnectUntrusted(ctypes.byref(handle))
return handle.value
def lsa_register_logon_process(logon_process_name):
if not isinstance(logon_process_name, bytes):
logon_process_name = logon_process_name.encode('mbcs')
logon_process_name = logon_process_name[:127]
buf = ctypes.create_string_buffer(logon_process_name, 128)
name = STRING(len(logon_process_name), len(buf), buf)
handle = wintypes.HANDLE()
mode = LSA_OPERATIONAL_MODE()
secur32.LsaRegisterLogonProcess(ctypes.byref(name),
ctypes.byref(handle), ctypes.byref(mode))
return handle.value
def lsa_lookup_authentication_package(lsa_handle, package_name):
if not isinstance(package_name, bytes):
package_name = package_name.encode('mbcs')
package_name = package_name[:127]
buf = ctypes.create_string_buffer(package_name)
name = STRING(len(package_name), len(buf), buf)
package = wintypes.ULONG()
secur32.LsaLookupAuthenticationPackage(lsa_handle, ctypes.byref(name),
ctypes.byref(package))
return package.value
LOGONINFO = collections.namedtuple('LOGONINFO', ('Token', 'LogonId',
'Profile', 'Quotas'))
def lsa_logon_user(auth_info, local_groups=None, origin_name=py_origin_name,
source_context=None, auth_package=None, logon_type=None,
lsa_handle=None):
if local_groups is None:
plocal_groups = LPTOKEN_GROUPS()
else:
plocal_groups = ctypes.byref(local_groups)
if source_context is None:
source_context = py_source_context
if not isinstance(origin_name, bytes):
origin_name = origin_name.encode('mbcs')
buf = ctypes.create_string_buffer(origin_name)
origin_name = STRING(len(origin_name), len(buf), buf)
if auth_package is None:
if isinstance(auth_info, MSV1_0_S4U_LOGON):
auth_package = NEGOTIATE_PACKAGE_NAME
elif isinstance(auth_info, KERB_S4U_LOGON):
auth_package = MICROSOFT_KERBEROS_NAME
else:
auth_package = MSV1_0_PACKAGE_NAME
if logon_type is None:
if isinstance(auth_info, S4ULogon):
logon_type = win32con.LOGON32_LOGON_NETWORK
else:
logon_type = Interactive
profile_buffer = wintypes.LPVOID()
profile_buffer_length = wintypes.ULONG()
profile = None
logonid = LUID()
htoken = HANDLE()
quotas = QUOTA_LIMITS()
substatus = NTSTATUS()
deregister = False
if lsa_handle is None:
lsa_handle = lsa_connect_untrusted()
deregister = True
try:
if isinstance(auth_package, (str, bytes)):
auth_package = lsa_lookup_authentication_package(lsa_handle,
auth_package)
try:
secur32.LsaLogonUser(lsa_handle, ctypes.byref(origin_name),
logon_type, auth_package, ctypes.byref(auth_info),
ctypes.sizeof(auth_info), plocal_groups,
ctypes.byref(source_context), ctypes.byref(profile_buffer),
ctypes.byref(profile_buffer_length), ctypes.byref(logonid),
ctypes.byref(htoken), ctypes.byref(quotas),
ctypes.byref(substatus))
except WindowsError: # pylint: disable=undefined-variable
if substatus.value:
raise ctypes.WinError(substatus.to_error())
raise
finally:
if profile_buffer:
address = profile_buffer.value
buftype = PROFILE_BUFFER_TYPE.from_address(address).value
if buftype == MsV1_0InteractiveLogon:
profile = MSV1_0_INTERACTIVE_PROFILE.from_address_copy(
address, profile_buffer_length.value)
secur32.LsaFreeReturnBuffer(address)
finally:
if deregister:
secur32.LsaDeregisterLogonProcess(lsa_handle)
return LOGONINFO(htoken, logonid, profile, quotas)
def logon_msv1(name, password, domain=None, local_groups=None,
origin_name=py_origin_name, source_context=None):
return lsa_logon_user(MSV1_0_INTERACTIVE_LOGON(name, password, domain),
local_groups, origin_name, source_context)
def logon_msv1_s4u(name, local_groups=None, origin_name=py_origin_name,
source_context=None):
domain = ctypes.create_unicode_buffer(MAX_COMPUTER_NAME_LENGTH + 1)
length = wintypes.DWORD(len(domain))
kernel32.GetComputerNameW(domain, ctypes.byref(length))
return lsa_logon_user(MSV1_0_S4U_LOGON(name, domain.value),
local_groups, origin_name, source_context)
def logon_kerb_s4u(name, realm=None, local_groups=None,
origin_name=py_origin_name,
source_context=None,
logon_process_name=py_logon_process_name):
lsa_handle = lsa_register_logon_process(logon_process_name)
try:
return lsa_logon_user(KERB_S4U_LOGON(name, realm),
local_groups, origin_name, source_context,
lsa_handle=lsa_handle)
finally:
secur32.LsaDeregisterLogonProcess(lsa_handle)
def DuplicateHandle(hsrc=kernel32.GetCurrentProcess(),
srchandle=kernel32.GetCurrentProcess(),
htgt=kernel32.GetCurrentProcess(),
access=0, inherit=False,
options=win32con.DUPLICATE_SAME_ACCESS):
tgthandle = wintypes.HANDLE()
kernel32.DuplicateHandle(hsrc, srchandle,
htgt, ctypes.byref(tgthandle),
access, inherit, options)
return tgthandle.value
def CreatePipe(inherit_read=False, inherit_write=False):
read, write = wintypes.HANDLE(), wintypes.HANDLE()
kernel32.CreatePipe(ctypes.byref(read), ctypes.byref(write), None, 0)
if inherit_read:
kernel32.SetHandleInformation(read, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
if inherit_write:
kernel32.SetHandleInformation(write, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
return read.value, write.value
def set_user_perm(obj, perm, sid):
'''
Set an object permission for the given user sid
'''
info = (
win32security.OWNER_SECURITY_INFORMATION |
win32security.GROUP_SECURITY_INFORMATION |
win32security.DACL_SECURITY_INFORMATION
)
sd = win32security.GetUserObjectSecurity(obj, info)
dacl = sd.GetSecurityDescriptorDacl()
ace_cnt = dacl.GetAceCount()
found = False
for idx in range(0, ace_cnt):
(aceType, aceFlags), ace_mask, ace_sid = dacl.GetAce(idx)
ace_exists = (
aceType == ntsecuritycon.ACCESS_ALLOWED_ACE_TYPE and
ace_mask == perm and
ace_sid == sid
)
if ace_exists:
# If the ace already exists, do nothing
break
else:
dacl.AddAccessAllowedAce(dacl.GetAclRevision(), perm, sid)
sd.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetUserObjectSecurity(obj, info, sd)
def grant_winsta_and_desktop(th):
'''
Grant the token's user access to the current process's window station and
desktop.
'''
current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
# Add permissions for the sid to the current windows station and thread id.
# This prevents windows error 0xC0000142.
winsta = win32process.GetProcessWindowStation()
set_user_perm(winsta, WINSTA_ALL, current_sid)
desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId())
set_user_perm(desktop, DESKTOP_ALL, current_sid)
def environment_string(env):
senv = ''
for k, v in env.items():
senv += k + '=' + v + '\0'
senv += '\0'
return ctypes.create_unicode_buffer(senv)
def CreateProcessWithTokenW(token,
logonflags=0,
applicationname=None,
commandline=None,
creationflags=0,
environment=None,
currentdirectory=None,
startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
if currentdirectory is not None:
currentdirectory = ctypes.create_unicode_buffer(currentdirectory)
if environment:
environment = ctypes.pointer(
environment_string(environment)
)
process_info = PROCESS_INFORMATION()
ret = advapi32.CreateProcessWithTokenW(
token,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
if ret == 0:
winerr = win32api.GetLastError()
exc = WindowsError(win32api.FormatMessage(winerr)) # pylint: disable=undefined-variable
exc.winerror = winerr
raise exc
return process_info
def enumerate_tokens(sid=None, session_id=None, privs=None):
'''
Enumerate tokens from any existing processes that can be accessed.
Optionally filter by sid.
'''
for p in psutil.process_iter():
if p.pid == 0:
continue
try:
ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, p.pid)
except win32api.error as exc:
if exc.winerror == 5:
log.debug("Unable to OpenProcess pid=%d name=%s", p.pid, p.name())
continue
raise exc
try:
access = (
win32security.TOKEN_DUPLICATE |
win32security.TOKEN_QUERY |
win32security.TOKEN_IMPERSONATE |
win32security.TOKEN_ASSIGN_PRIMARY
)
th = win32security.OpenProcessToken(ph, access)
except Exception as exc:
log.debug("OpenProcessToken failed pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
try:
process_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
except Exception as exc:
log.exception("GetTokenInformation pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
proc_sid = win32security.ConvertSidToStringSid(process_sid)
if sid and sid != proc_sid:
log.debug("Token for pid does not match user sid: %s", sid)
continue
if session_id and win32security.GetTokenInformation(th, win32security.TokenSessionId) != session_id:
continue
def has_priv(tok, priv):
luid = win32security.LookupPrivilegeValue(None, priv)
for priv_luid, flags in win32security.GetTokenInformation(tok, win32security.TokenPrivileges):
if priv_luid == luid:
return True
return False
if privs:
has_all = True
for name in privs:
if not has_priv(th, name):
has_all = False
if not has_all:
continue
yield dup_token(th)
def impersonate_sid(sid, session_id=None, privs=None):
'''
Find an existing process token for the given sid and impersonate the token.
'''
for tok in enumerate_tokens(sid, session_id, privs):
tok = dup_token(tok)
elevate_token(tok)
if win32security.ImpersonateLoggedOnUser(tok) == 0:
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
return tok
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
def dup_token(th):
'''
duplicate the access token
'''
# TODO: is `duplicate_token` the same?
sec_attr = win32security.SECURITY_ATTRIBUTES()
sec_attr.bInheritHandle = True
return win32security.DuplicateTokenEx(
th,
win32security.SecurityImpersonation,
win32con.MAXIMUM_ALLOWED,
win32security.TokenPrimary,
sec_attr,
)
# pylint: disable=undefined-variable
def make_inheritable(token):
'''Create an inheritable handle'''
return win32api.DuplicateHandle(
win32api.GetCurrentProcess(),
token,
win32api.GetCurrentProcess(),
0,
1,
win32con.DUPLICATE_SAME_ACCESS
)
def CreateProcessWithLogonW(username=None, domain=None, password=None,
logonflags=0, applicationname=None, commandline=None, creationflags=0,
environment=None, currentdirectory=None, startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
process_info = PROCESS_INFORMATION()
advapi32.CreateProcessWithLogonW(
username,
domain,
password,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
return process_info
|
saltstack/salt | salt/platform/win.py | make_inheritable | python | def make_inheritable(token):
'''Create an inheritable handle'''
return win32api.DuplicateHandle(
win32api.GetCurrentProcess(),
token,
win32api.GetCurrentProcess(),
0,
1,
win32con.DUPLICATE_SAME_ACCESS
) | Create an inheritable handle | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/platform/win.py#L1165-L1174 | null | # -*- coding: utf-8 -*-
'''
Windows specific utility functions, this module should be imported in a try,
except block because it is only applicable on Windows platforms.
Much of what is here was adapted from the following:
https://stackoverflow.com/a/43233332
http://stackoverflow.com/questions/29566330
'''
from __future__ import absolute_import, unicode_literals
import os
import collections
import logging
import psutil
import ctypes
from ctypes import wintypes
from salt.ext.six.moves import range
from salt.ext.six.moves import zip
import win32con
import win32con
import win32api
import win32process
import win32security
import win32service
import ntsecuritycon
# Set up logging
log = logging.getLogger(__name__)
ntdll = ctypes.WinDLL('ntdll')
secur32 = ctypes.WinDLL('secur32')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
advapi32 = ctypes.WinDLL('advapi32', use_last_error=True)
userenv = ctypes.WinDLL('userenv', use_last_error=True)
SYSTEM_SID = "S-1-5-18"
LOCAL_SRV_SID = "S-1-5-19"
NETWORK_SRV_SID = "S-1-5-19"
LOGON_WITH_PROFILE = 0x00000001
WINSTA_ALL = (
win32con.WINSTA_ACCESSCLIPBOARD |
win32con.WINSTA_ACCESSGLOBALATOMS |
win32con.WINSTA_CREATEDESKTOP |
win32con.WINSTA_ENUMDESKTOPS |
win32con.WINSTA_ENUMERATE |
win32con.WINSTA_EXITWINDOWS |
win32con.WINSTA_READATTRIBUTES |
win32con.WINSTA_READSCREEN |
win32con.WINSTA_WRITEATTRIBUTES |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
DESKTOP_ALL = (
win32con.DESKTOP_CREATEMENU |
win32con.DESKTOP_CREATEWINDOW |
win32con.DESKTOP_ENUMERATE |
win32con.DESKTOP_HOOKCONTROL |
win32con.DESKTOP_JOURNALPLAYBACK |
win32con.DESKTOP_JOURNALRECORD |
win32con.DESKTOP_READOBJECTS |
win32con.DESKTOP_SWITCHDESKTOP |
win32con.DESKTOP_WRITEOBJECTS |
win32con.DELETE |
win32con.READ_CONTROL |
win32con.WRITE_DAC |
win32con.WRITE_OWNER
)
MAX_COMPUTER_NAME_LENGTH = 15
SECURITY_LOGON_TYPE = wintypes.ULONG
Interactive = 2
Network = 3
Batch = 4
Service = 5
LOGON_SUBMIT_TYPE = wintypes.ULONG
PROFILE_BUFFER_TYPE = wintypes.ULONG
MsV1_0InteractiveLogon = 2
MsV1_0Lm20Logon = 3
MsV1_0NetworkLogon = 4
MsV1_0WorkstationUnlockLogon = 7
MsV1_0S4ULogon = 12
MsV1_0NoElevationLogon = 82
KerbInteractiveLogon = 2
KerbWorkstationUnlockLogon = 7
KerbS4ULogon = 12
MSV1_0_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_CHECK_LOGONHOURS = 0x2
KERB_S4U_LOGON_FLAG_IDENTITY = 0x8
TOKEN_SOURCE_LENGTH = 8
NEGOTIATE_PACKAGE_NAME = b'Negotiate'
MICROSOFT_KERBEROS_NAME = b'Kerberos'
MSV1_0_PACKAGE_NAME = b'MICROSOFT_AUTHENTICATION_PACKAGE_V1_0'
DELETE = 0x00010000
READ_CONTROL = 0x00020000
WRITE_DAC = 0x00040000
WRITE_OWNER = 0x00080000
STANDARD_RIGHTS_REQUIRED = (
DELETE |
READ_CONTROL |
WRITE_DAC |
WRITE_OWNER
)
TOKEN_ASSIGN_PRIMARY = 0x0001
TOKEN_DUPLICATE = 0x0002
TOKEN_IMPERSONATE = 0x0004
TOKEN_QUERY = 0x0008
TOKEN_QUERY_SOURCE = 0x0010
TOKEN_ADJUST_PRIVILEGES = 0x0020
TOKEN_ADJUST_GROUPS = 0x0040
TOKEN_ADJUST_DEFAULT = 0x0080
TOKEN_ADJUST_SESSIONID = 0x0100
TOKEN_ALL_ACCESS = (
STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE |
TOKEN_IMPERSONATE |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID
)
DUPLICATE_CLOSE_SOURCE = 0x00000001
DUPLICATE_SAME_ACCESS = 0x00000002
TOKEN_TYPE = wintypes.ULONG
TokenPrimary = 1
TokenImpersonation = 2
SECURITY_IMPERSONATION_LEVEL = wintypes.ULONG
SecurityAnonymous = 0
SecurityIdentification = 1
SecurityImpersonation = 2
SecurityDelegation = 3
class NTSTATUS(wintypes.LONG):
def to_error(self):
return ntdll.RtlNtStatusToDosError(self)
def __repr__(self):
name = self.__class__.__name__
status = wintypes.ULONG.from_buffer(self)
return '{}({})'.format(name, status.value)
PNTSTATUS = ctypes.POINTER(NTSTATUS)
class BOOL(wintypes.BOOL):
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, bool(self))
class HANDLE(wintypes.HANDLE):
__slots__ = 'closed',
def __int__(self):
return self.value or 0
def Detach(self):
if not getattr(self, 'closed', False):
self.closed = True
value = int(self)
self.value = None
return value
raise ValueError("already closed")
def Close(self, CloseHandle=kernel32.CloseHandle):
if self and not getattr(self, 'closed', False):
CloseHandle(self.Detach())
__del__ = Close
def __repr__(self):
return "{}({})".format(self.__class__.__name__, int(self))
class LARGE_INTEGER(wintypes.LARGE_INTEGER):
# https://msdn.microsoft.com/en-us/library/ff553204
ntdll.RtlSecondsSince1970ToTime.restype = None
_unix_epoch = wintypes.LARGE_INTEGER()
ntdll.RtlSecondsSince1970ToTime(0, ctypes.byref(_unix_epoch))
_unix_epoch = _unix_epoch.value
def __int__(self):
return self.value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, self.value)
def as_time(self):
time100ns = self.value - self._unix_epoch
if time100ns >= 0:
return time100ns / 1e7
raise ValueError('value predates the Unix epoch')
@classmethod
def from_time(cls, t):
time100ns = int(t * 10**7)
return cls(time100ns + cls._unix_epoch)
CHAR = ctypes.c_char
WCHAR = ctypes.c_wchar
PCHAR = ctypes.POINTER(CHAR)
PWCHAR = ctypes.POINTER(WCHAR)
class STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PCHAR),
)
LPSTRING = ctypes.POINTER(STRING)
class UNICODE_STRING(ctypes.Structure):
_fields_ = (
('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', PWCHAR),
)
LPUNICODE_STRING = ctypes.POINTER(UNICODE_STRING)
class LUID(ctypes.Structure):
_fields_ = (
('LowPart', wintypes.DWORD),
('HighPart', wintypes.LONG),
)
def __new__(cls, value=0):
return cls.from_buffer_copy(ctypes.c_ulonglong(value))
def __int__(self):
return ctypes.c_ulonglong.from_buffer(self).value
def __repr__(self):
name = self.__class__.__name__
return '{}({})'.format(name, int(self))
LPLUID = ctypes.POINTER(LUID)
PSID = wintypes.LPVOID
class SID_AND_ATTRIBUTES(ctypes.Structure):
_fields_ = (
('Sid', PSID),
('Attributes', wintypes.DWORD),
)
LPSID_AND_ATTRIBUTES = ctypes.POINTER(SID_AND_ATTRIBUTES)
class TOKEN_GROUPS(ctypes.Structure):
_fields_ = (
('GroupCount', wintypes.DWORD),
('Groups', SID_AND_ATTRIBUTES * 1),
)
LPTOKEN_GROUPS = ctypes.POINTER(TOKEN_GROUPS)
class TOKEN_SOURCE(ctypes.Structure):
_fields_ = (
('SourceName', CHAR * TOKEN_SOURCE_LENGTH),
('SourceIdentifier', LUID),
)
def __init__(self, SourceName=None, SourceIdentifier=None):
super(TOKEN_SOURCE, self).__init__()
if SourceName is not None:
if not isinstance(SourceName, bytes):
SourceName = SourceName.encode('mbcs')
self.SourceName = SourceName
if SourceIdentifier is None:
luid = self.SourceIdentifier # pylint: disable=access-member-before-definition
ntdll.NtAllocateLocallyUniqueId(ctypes.byref(luid))
else:
self.SourceIdentifier = SourceIdentifier
LPTOKEN_SOURCE = ctypes.POINTER(TOKEN_SOURCE)
py_source_context = TOKEN_SOURCE(b"PYTHON ")
py_origin_name = __name__.encode()
py_logon_process_name = "{}-{}".format(py_origin_name, os.getpid())
SIZE_T = ctypes.c_size_t
class QUOTA_LIMITS(ctypes.Structure):
_fields_ = (('PagedPoolLimit', SIZE_T),
('NonPagedPoolLimit', SIZE_T),
('MinimumWorkingSetSize', SIZE_T),
('MaximumWorkingSetSize', SIZE_T),
('PagefileLimit', SIZE_T),
('TimeLimit', wintypes.LARGE_INTEGER))
LPQUOTA_LIMITS = ctypes.POINTER(QUOTA_LIMITS)
LPULONG = ctypes.POINTER(wintypes.ULONG)
LSA_OPERATIONAL_MODE = wintypes.ULONG
LPLSA_OPERATIONAL_MODE = LPULONG
LPHANDLE = ctypes.POINTER(wintypes.HANDLE)
LPLPVOID = ctypes.POINTER(wintypes.LPVOID)
LPDWORD = ctypes.POINTER(wintypes.DWORD)
class ContiguousUnicode(ctypes.Structure):
# _string_names_: sequence matched to underscore-prefixed fields
def __init__(self, *args, **kwargs):
super(ContiguousUnicode, self).__init__(*args, **kwargs)
def _get_unicode_string(self, name):
wchar_size = ctypes.sizeof(WCHAR)
s = getattr(self, '_{}'.format(name))
length = s.Length // wchar_size
buf = s.Buffer
if buf:
return buf[:length]
return None
def _set_unicode_buffer(self, values):
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
bufsize = (len('\x00'.join(values)) + 1) * wchar_size
ctypes.resize(self, ctypes.sizeof(cls) + bufsize)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for value in values:
bufsize = (len(value) + 1) * wchar_size
ctypes.memmove(addr, value, bufsize)
addr += bufsize
def _set_unicode_string(self, name, value):
values = []
for n in self._string_names_:
if n == name:
values.append(value or '')
else:
values.append(getattr(self, n) or '')
self._set_unicode_buffer(values)
cls = type(self)
wchar_size = ctypes.sizeof(WCHAR)
addr = ctypes.addressof(self) + ctypes.sizeof(cls)
for n, v in zip(self._string_names_, values):
ptr = ctypes.cast(addr, PWCHAR)
ustr = getattr(self, '_{}'.format(n))
length = ustr.Length = len(v) * wchar_size
full_length = length + wchar_size
if ((n == name and value is None) or
(n != name and not (length or ustr.Buffer))):
ustr.Buffer = None
ustr.MaximumLength = 0
else:
ustr.Buffer = ptr
ustr.MaximumLength = full_length
addr += full_length
def __getattr__(self, name):
if name not in self._string_names_:
raise AttributeError
return self._get_unicode_string(name)
def __setattr__(self, name, value):
if name in self._string_names_:
self._set_unicode_string(name, value)
else:
super(ContiguousUnicode, self).__setattr__(name, value)
@classmethod
def from_address_copy(cls, address, size=None):
x = ctypes.Structure.__new__(cls)
if size is not None:
ctypes.resize(x, size)
ctypes.memmove(ctypes.byref(x), address, ctypes.sizeof(x))
delta = ctypes.addressof(x) - address
for n in cls._string_names_:
ustr = getattr(x, '_{}'.format(n))
addr = ctypes.c_void_p.from_buffer(ustr.Buffer)
if addr:
addr.value += delta
return x
class AuthInfo(ContiguousUnicode):
# _message_type_: from a logon-submit-type enumeration
def __init__(self):
super(AuthInfo, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_LOGON(AuthInfo):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = 'LogonDomainName', 'UserName', 'Password'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('_LogonDomainName', UNICODE_STRING),
('_UserName', UNICODE_STRING),
('_Password', UNICODE_STRING))
def __init__(self, UserName=None, Password=None, LogonDomainName=None):
super(MSV1_0_INTERACTIVE_LOGON, self).__init__()
if LogonDomainName is not None:
self.LogonDomainName = LogonDomainName
if UserName is not None:
self.UserName = UserName
if Password is not None:
self.Password = Password
class S4ULogon(AuthInfo):
_string_names_ = 'UserPrincipalName', 'DomainName'
_fields_ = (('MessageType', LOGON_SUBMIT_TYPE),
('Flags', wintypes.ULONG),
('_UserPrincipalName', UNICODE_STRING),
('_DomainName', UNICODE_STRING))
def __init__(self, UserPrincipalName=None, DomainName=None, Flags=0):
super(S4ULogon, self).__init__()
self.Flags = Flags
if UserPrincipalName is not None:
self.UserPrincipalName = UserPrincipalName
if DomainName is not None:
self.DomainName = DomainName
class MSV1_0_S4U_LOGON(S4ULogon):
_message_type_ = MsV1_0S4ULogon
class KERB_S4U_LOGON(S4ULogon):
_message_type_ = KerbS4ULogon
PMSV1_0_S4U_LOGON = ctypes.POINTER(MSV1_0_S4U_LOGON)
PKERB_S4U_LOGON = ctypes.POINTER(KERB_S4U_LOGON)
class ProfileBuffer(ContiguousUnicode):
# _message_type_
def __init__(self):
super(ProfileBuffer, self).__init__()
self.MessageType = self._message_type_
class MSV1_0_INTERACTIVE_PROFILE(ProfileBuffer):
_message_type_ = MsV1_0InteractiveLogon
_string_names_ = ('LogonScript', 'HomeDirectory', 'FullName',
'ProfilePath', 'HomeDirectoryDrive', 'LogonServer')
_fields_ = (('MessageType', PROFILE_BUFFER_TYPE),
('LogonCount', wintypes.USHORT),
('BadPasswordCount', wintypes.USHORT),
('LogonTime', LARGE_INTEGER),
('LogoffTime', LARGE_INTEGER),
('KickOffTime', LARGE_INTEGER),
('PasswordLastSet', LARGE_INTEGER),
('PasswordCanChange', LARGE_INTEGER),
('PasswordMustChange', LARGE_INTEGER),
('_LogonScript', UNICODE_STRING),
('_HomeDirectory', UNICODE_STRING),
('_FullName', UNICODE_STRING),
('_ProfilePath', UNICODE_STRING),
('_HomeDirectoryDrive', UNICODE_STRING),
('_LogonServer', UNICODE_STRING),
('UserFlags', wintypes.ULONG))
def _check_status(result, func, args):
if result.value < 0:
raise ctypes.WinError(result.to_error())
return args
def _check_bool(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
INVALID_DWORD_VALUE = wintypes.DWORD(-1).value # ~WinAPI
INFINITE = INVALID_DWORD_VALUE
STD_INPUT_HANDLE = wintypes.DWORD(-10).value
STD_OUTPUT_HANDLE = wintypes.DWORD(-11).value
STD_ERROR_HANDLE = wintypes.DWORD(-12).value
class SECURITY_ATTRIBUTES(ctypes.Structure):
_fields_ = (('nLength', wintypes.DWORD),
('lpSecurityDescriptor', wintypes.LPVOID),
('bInheritHandle', wintypes.BOOL))
def __init__(self, **kwds):
self.nLength = ctypes.sizeof(self)
super(SECURITY_ATTRIBUTES, self).__init__(**kwds)
LPSECURITY_ATTRIBUTES = ctypes.POINTER(SECURITY_ATTRIBUTES)
LPBYTE = ctypes.POINTER(wintypes.BYTE)
LPHANDLE = PHANDLE = ctypes.POINTER(ctypes.c_void_p)
LPDWORD = ctypes.POINTER(ctypes.c_ulong)
class STARTUPINFO(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms686331"""
_fields_ = (('cb', wintypes.DWORD),
('lpReserved', wintypes.LPWSTR),
('lpDesktop', wintypes.LPWSTR),
('lpTitle', wintypes.LPWSTR),
('dwX', wintypes.DWORD),
('dwY', wintypes.DWORD),
('dwXSize', wintypes.DWORD),
('dwYSize', wintypes.DWORD),
('dwXCountChars', wintypes.DWORD),
('dwYCountChars', wintypes.DWORD),
('dwFillAttribute', wintypes.DWORD),
('dwFlags', wintypes.DWORD),
('wShowWindow', wintypes.WORD),
('cbReserved2', wintypes.WORD),
('lpReserved2', LPBYTE),
('hStdInput', wintypes.HANDLE),
('hStdOutput', wintypes.HANDLE),
('hStdError', wintypes.HANDLE))
def __init__(self, **kwds):
self.cb = ctypes.sizeof(self)
super(STARTUPINFO, self).__init__(**kwds)
LPSTARTUPINFO = ctypes.POINTER(STARTUPINFO)
class PROC_THREAD_ATTRIBUTE_LIST(ctypes.Structure):
pass
PPROC_THREAD_ATTRIBUTE_LIST = ctypes.POINTER(PROC_THREAD_ATTRIBUTE_LIST)
class STARTUPINFOEX(STARTUPINFO):
_fields_ = (('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST),)
LPSTARTUPINFOEX = ctypes.POINTER(STARTUPINFOEX)
class PROCESS_INFORMATION(ctypes.Structure):
"""https://msdn.microsoft.com/en-us/library/ms684873"""
_fields_ = (('hProcess', wintypes.HANDLE),
('hThread', wintypes.HANDLE),
('dwProcessId', wintypes.DWORD),
('dwThreadId', wintypes.DWORD))
LPPROCESS_INFORMATION = ctypes.POINTER(PROCESS_INFORMATION)
class HANDLE_IHV(wintypes.HANDLE):
pass
def errcheck_ihv(result, func, args):
if result.value == INVALID_HANDLE_VALUE:
raise ctypes.WinError()
return result.value
class DWORD_IDV(wintypes.DWORD):
pass
def errcheck_idv(result, func, args):
if result.value == INVALID_DWORD_VALUE:
raise ctypes.WinError()
return result.value
def errcheck_bool(result, func, args):
if not result:
raise ctypes.WinError()
return args
def _win(func, restype, *argtypes):
func.restype = restype
func.argtypes = argtypes
if issubclass(restype, NTSTATUS):
func.errcheck = _check_status
elif issubclass(restype, BOOL):
func.errcheck = _check_bool
elif issubclass(restype, HANDLE_IHV):
func.errcheck = errcheck_ihv
elif issubclass(restype, DWORD_IDV):
func.errcheck = errcheck_idv
else:
func.errcheck = errcheck_bool
# https://msdn.microsoft.com/en-us/library/ms683231
_win(kernel32.GetStdHandle, HANDLE_IHV,
wintypes.DWORD) # _In_ nStdHandle
# https://msdn.microsoft.com/en-us/library/ms724211
_win(kernel32.CloseHandle, wintypes.BOOL,
wintypes.HANDLE) # _In_ hObject
# https://msdn.microsoft.com/en-us/library/ms724935
_win(kernel32.SetHandleInformation, wintypes.BOOL,
wintypes.HANDLE, # _In_ hObject
wintypes.DWORD, # _In_ dwMask
wintypes.DWORD) # _In_ dwFlags
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, wintypes.BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle,
wintypes.HANDLE, # _In_ hSourceHandle,
wintypes.HANDLE, # _In_ hTargetProcessHandle,
LPHANDLE, # _Out_ lpTargetHandle,
wintypes.DWORD, # _In_ dwDesiredAccess,
wintypes.BOOL, # _In_ bInheritHandle,
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms683189
_win(kernel32.GetExitCodeProcess, wintypes.BOOL,
wintypes.HANDLE, # _In_ hProcess,
LPDWORD) # _Out_ lpExitCode
# https://msdn.microsoft.com/en-us/library/aa365152
_win(kernel32.CreatePipe, wintypes.BOOL,
PHANDLE, # _Out_ hReadPipe,
PHANDLE, # _Out_ hWritePipe,
LPSECURITY_ATTRIBUTES, # _In_opt_ lpPipeAttributes,
wintypes.DWORD) # _In_ nSize
# https://msdn.microsoft.com/en-us/library/ms682431
#_win(advapi32.CreateProcessWithTokenW, wintypes.BOOL,
# PHANDLE, # _In_ lpUsername
# wintypes.DWORD, # _In_ dwLogonFlags
# wintypes.LPCWSTR, # _In_opt_ lpApplicationName
# wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
# wintypes.DWORD, # _In_ dwCreationFlags
# wintypes.LPVOID, # _In_opt_ lpEnvironment
# wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
# LPSTARTUPINFO, # _In_ lpStartupInfo
# LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms682431
_win(advapi32.CreateProcessWithLogonW, wintypes.BOOL,
wintypes.LPCWSTR, # _In_ lpUsername
wintypes.LPCWSTR, # _In_opt_ lpDomain
wintypes.LPCWSTR, # _In_ lpPassword
wintypes.DWORD, # _In_ dwLogonFlags
wintypes.LPCWSTR, # _In_opt_ lpApplicationName
wintypes.LPWSTR, # _Inout_opt_ lpCommandLine
wintypes.DWORD, # _In_ dwCreationFlags
wintypes.LPCWSTR, # _In_opt_ lpEnvironment
wintypes.LPCWSTR, # _In_opt_ lpCurrentDirectory
LPSTARTUPINFO, # _In_ lpStartupInfo
LPPROCESS_INFORMATION) # _Out_ lpProcessInformation
# https://msdn.microsoft.com/en-us/library/ms683179
_win(kernel32.GetCurrentProcess, wintypes.HANDLE)
# https://msdn.microsoft.com/en-us/library/ms724251
_win(kernel32.DuplicateHandle, BOOL,
wintypes.HANDLE, # _In_ hSourceProcessHandle
wintypes.HANDLE, # _In_ hSourceHandle
wintypes.HANDLE, # _In_ hTargetProcessHandle
LPHANDLE, # _Out_ lpTargetHandle
wintypes.DWORD, # _In_ dwDesiredAccess
wintypes.BOOL, # _In_ bInheritHandle
wintypes.DWORD) # _In_ dwOptions
# https://msdn.microsoft.com/en-us/library/ms724295
_win(kernel32.GetComputerNameW, BOOL,
wintypes.LPWSTR, # _Out_ lpBuffer
LPDWORD) # _Inout_ lpnSize
# https://msdn.microsoft.com/en-us/library/aa379295
_win(advapi32.OpenProcessToken, BOOL,
wintypes.HANDLE, # _In_ ProcessHandle
wintypes.DWORD, # _In_ DesiredAccess
LPHANDLE) # _Out_ TokenHandle
# https://msdn.microsoft.com/en-us/library/aa446617
_win(advapi32.DuplicateTokenEx, BOOL,
wintypes.HANDLE, # _In_ hExistingToken
wintypes.DWORD, # _In_ dwDesiredAccess
LPSECURITY_ATTRIBUTES, # _In_opt_ lpTokenAttributes
SECURITY_IMPERSONATION_LEVEL, # _In_ ImpersonationLevel
TOKEN_TYPE, # _In_ TokenType
LPHANDLE) # _Out_ phNewToken
# https://msdn.microsoft.com/en-us/library/ff566415
_win(ntdll.NtAllocateLocallyUniqueId, NTSTATUS,
LPLUID) # _Out_ LUID
# https://msdn.microsoft.com/en-us/library/aa378279
_win(secur32.LsaFreeReturnBuffer, NTSTATUS,
wintypes.LPVOID,) # _In_ Buffer
# https://msdn.microsoft.com/en-us/library/aa378265
_win(secur32.LsaConnectUntrusted, NTSTATUS,
LPHANDLE,) # _Out_ LsaHandle
#https://msdn.microsoft.com/en-us/library/aa378318
_win(secur32.LsaRegisterLogonProcess, NTSTATUS,
LPSTRING, # _In_ LogonProcessName
LPHANDLE, # _Out_ LsaHandle
LPLSA_OPERATIONAL_MODE) # _Out_ SecurityMode
# https://msdn.microsoft.com/en-us/library/aa378269
_win(secur32.LsaDeregisterLogonProcess, NTSTATUS,
wintypes.HANDLE) # _In_ LsaHandle
# https://msdn.microsoft.com/en-us/library/aa378297
_win(secur32.LsaLookupAuthenticationPackage, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ PackageName
LPULONG) # _Out_ AuthenticationPackage
# https://msdn.microsoft.com/en-us/library/aa378292
_win(secur32.LsaLogonUser, NTSTATUS,
wintypes.HANDLE, # _In_ LsaHandle
LPSTRING, # _In_ OriginName
SECURITY_LOGON_TYPE, # _In_ LogonType
wintypes.ULONG, # _In_ AuthenticationPackage
wintypes.LPVOID, # _In_ AuthenticationInformation
wintypes.ULONG, # _In_ AuthenticationInformationLength
LPTOKEN_GROUPS, # _In_opt_ LocalGroups
LPTOKEN_SOURCE, # _In_ SourceContext
LPLPVOID, # _Out_ ProfileBuffer
LPULONG, # _Out_ ProfileBufferLength
LPLUID, # _Out_ LogonId
LPHANDLE, # _Out_ Token
LPQUOTA_LIMITS, # _Out_ Quotas
PNTSTATUS) # _Out_ SubStatus
def duplicate_token(source_token=None, access=TOKEN_ALL_ACCESS,
impersonation_level=SecurityImpersonation,
token_type=TokenPrimary, attributes=None):
close_source = False
if source_token is None:
close_source = True
source_token = HANDLE()
advapi32.OpenProcessToken(kernel32.GetCurrentProcess(),
TOKEN_ALL_ACCESS, ctypes.byref(source_token))
token = HANDLE()
try:
advapi32.DuplicateTokenEx(source_token, access, attributes,
impersonation_level, token_type, ctypes.byref(token))
finally:
if close_source:
source_token.Close()
return token
def lsa_connect_untrusted():
handle = wintypes.HANDLE()
secur32.LsaConnectUntrusted(ctypes.byref(handle))
return handle.value
def lsa_register_logon_process(logon_process_name):
if not isinstance(logon_process_name, bytes):
logon_process_name = logon_process_name.encode('mbcs')
logon_process_name = logon_process_name[:127]
buf = ctypes.create_string_buffer(logon_process_name, 128)
name = STRING(len(logon_process_name), len(buf), buf)
handle = wintypes.HANDLE()
mode = LSA_OPERATIONAL_MODE()
secur32.LsaRegisterLogonProcess(ctypes.byref(name),
ctypes.byref(handle), ctypes.byref(mode))
return handle.value
def lsa_lookup_authentication_package(lsa_handle, package_name):
if not isinstance(package_name, bytes):
package_name = package_name.encode('mbcs')
package_name = package_name[:127]
buf = ctypes.create_string_buffer(package_name)
name = STRING(len(package_name), len(buf), buf)
package = wintypes.ULONG()
secur32.LsaLookupAuthenticationPackage(lsa_handle, ctypes.byref(name),
ctypes.byref(package))
return package.value
LOGONINFO = collections.namedtuple('LOGONINFO', ('Token', 'LogonId',
'Profile', 'Quotas'))
def lsa_logon_user(auth_info, local_groups=None, origin_name=py_origin_name,
source_context=None, auth_package=None, logon_type=None,
lsa_handle=None):
if local_groups is None:
plocal_groups = LPTOKEN_GROUPS()
else:
plocal_groups = ctypes.byref(local_groups)
if source_context is None:
source_context = py_source_context
if not isinstance(origin_name, bytes):
origin_name = origin_name.encode('mbcs')
buf = ctypes.create_string_buffer(origin_name)
origin_name = STRING(len(origin_name), len(buf), buf)
if auth_package is None:
if isinstance(auth_info, MSV1_0_S4U_LOGON):
auth_package = NEGOTIATE_PACKAGE_NAME
elif isinstance(auth_info, KERB_S4U_LOGON):
auth_package = MICROSOFT_KERBEROS_NAME
else:
auth_package = MSV1_0_PACKAGE_NAME
if logon_type is None:
if isinstance(auth_info, S4ULogon):
logon_type = win32con.LOGON32_LOGON_NETWORK
else:
logon_type = Interactive
profile_buffer = wintypes.LPVOID()
profile_buffer_length = wintypes.ULONG()
profile = None
logonid = LUID()
htoken = HANDLE()
quotas = QUOTA_LIMITS()
substatus = NTSTATUS()
deregister = False
if lsa_handle is None:
lsa_handle = lsa_connect_untrusted()
deregister = True
try:
if isinstance(auth_package, (str, bytes)):
auth_package = lsa_lookup_authentication_package(lsa_handle,
auth_package)
try:
secur32.LsaLogonUser(lsa_handle, ctypes.byref(origin_name),
logon_type, auth_package, ctypes.byref(auth_info),
ctypes.sizeof(auth_info), plocal_groups,
ctypes.byref(source_context), ctypes.byref(profile_buffer),
ctypes.byref(profile_buffer_length), ctypes.byref(logonid),
ctypes.byref(htoken), ctypes.byref(quotas),
ctypes.byref(substatus))
except WindowsError: # pylint: disable=undefined-variable
if substatus.value:
raise ctypes.WinError(substatus.to_error())
raise
finally:
if profile_buffer:
address = profile_buffer.value
buftype = PROFILE_BUFFER_TYPE.from_address(address).value
if buftype == MsV1_0InteractiveLogon:
profile = MSV1_0_INTERACTIVE_PROFILE.from_address_copy(
address, profile_buffer_length.value)
secur32.LsaFreeReturnBuffer(address)
finally:
if deregister:
secur32.LsaDeregisterLogonProcess(lsa_handle)
return LOGONINFO(htoken, logonid, profile, quotas)
def logon_msv1(name, password, domain=None, local_groups=None,
origin_name=py_origin_name, source_context=None):
return lsa_logon_user(MSV1_0_INTERACTIVE_LOGON(name, password, domain),
local_groups, origin_name, source_context)
def logon_msv1_s4u(name, local_groups=None, origin_name=py_origin_name,
source_context=None):
domain = ctypes.create_unicode_buffer(MAX_COMPUTER_NAME_LENGTH + 1)
length = wintypes.DWORD(len(domain))
kernel32.GetComputerNameW(domain, ctypes.byref(length))
return lsa_logon_user(MSV1_0_S4U_LOGON(name, domain.value),
local_groups, origin_name, source_context)
def logon_kerb_s4u(name, realm=None, local_groups=None,
origin_name=py_origin_name,
source_context=None,
logon_process_name=py_logon_process_name):
lsa_handle = lsa_register_logon_process(logon_process_name)
try:
return lsa_logon_user(KERB_S4U_LOGON(name, realm),
local_groups, origin_name, source_context,
lsa_handle=lsa_handle)
finally:
secur32.LsaDeregisterLogonProcess(lsa_handle)
def DuplicateHandle(hsrc=kernel32.GetCurrentProcess(),
srchandle=kernel32.GetCurrentProcess(),
htgt=kernel32.GetCurrentProcess(),
access=0, inherit=False,
options=win32con.DUPLICATE_SAME_ACCESS):
tgthandle = wintypes.HANDLE()
kernel32.DuplicateHandle(hsrc, srchandle,
htgt, ctypes.byref(tgthandle),
access, inherit, options)
return tgthandle.value
def CreatePipe(inherit_read=False, inherit_write=False):
read, write = wintypes.HANDLE(), wintypes.HANDLE()
kernel32.CreatePipe(ctypes.byref(read), ctypes.byref(write), None, 0)
if inherit_read:
kernel32.SetHandleInformation(read, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
if inherit_write:
kernel32.SetHandleInformation(write, win32con.HANDLE_FLAG_INHERIT,
win32con.HANDLE_FLAG_INHERIT)
return read.value, write.value
def set_user_perm(obj, perm, sid):
'''
Set an object permission for the given user sid
'''
info = (
win32security.OWNER_SECURITY_INFORMATION |
win32security.GROUP_SECURITY_INFORMATION |
win32security.DACL_SECURITY_INFORMATION
)
sd = win32security.GetUserObjectSecurity(obj, info)
dacl = sd.GetSecurityDescriptorDacl()
ace_cnt = dacl.GetAceCount()
found = False
for idx in range(0, ace_cnt):
(aceType, aceFlags), ace_mask, ace_sid = dacl.GetAce(idx)
ace_exists = (
aceType == ntsecuritycon.ACCESS_ALLOWED_ACE_TYPE and
ace_mask == perm and
ace_sid == sid
)
if ace_exists:
# If the ace already exists, do nothing
break
else:
dacl.AddAccessAllowedAce(dacl.GetAclRevision(), perm, sid)
sd.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetUserObjectSecurity(obj, info, sd)
def grant_winsta_and_desktop(th):
'''
Grant the token's user access to the current process's window station and
desktop.
'''
current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
# Add permissions for the sid to the current windows station and thread id.
# This prevents windows error 0xC0000142.
winsta = win32process.GetProcessWindowStation()
set_user_perm(winsta, WINSTA_ALL, current_sid)
desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId())
set_user_perm(desktop, DESKTOP_ALL, current_sid)
def environment_string(env):
senv = ''
for k, v in env.items():
senv += k + '=' + v + '\0'
senv += '\0'
return ctypes.create_unicode_buffer(senv)
def CreateProcessWithTokenW(token,
logonflags=0,
applicationname=None,
commandline=None,
creationflags=0,
environment=None,
currentdirectory=None,
startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
if currentdirectory is not None:
currentdirectory = ctypes.create_unicode_buffer(currentdirectory)
if environment:
environment = ctypes.pointer(
environment_string(environment)
)
process_info = PROCESS_INFORMATION()
ret = advapi32.CreateProcessWithTokenW(
token,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
if ret == 0:
winerr = win32api.GetLastError()
exc = WindowsError(win32api.FormatMessage(winerr)) # pylint: disable=undefined-variable
exc.winerror = winerr
raise exc
return process_info
def enumerate_tokens(sid=None, session_id=None, privs=None):
'''
Enumerate tokens from any existing processes that can be accessed.
Optionally filter by sid.
'''
for p in psutil.process_iter():
if p.pid == 0:
continue
try:
ph = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, p.pid)
except win32api.error as exc:
if exc.winerror == 5:
log.debug("Unable to OpenProcess pid=%d name=%s", p.pid, p.name())
continue
raise exc
try:
access = (
win32security.TOKEN_DUPLICATE |
win32security.TOKEN_QUERY |
win32security.TOKEN_IMPERSONATE |
win32security.TOKEN_ASSIGN_PRIMARY
)
th = win32security.OpenProcessToken(ph, access)
except Exception as exc:
log.debug("OpenProcessToken failed pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
try:
process_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
except Exception as exc:
log.exception("GetTokenInformation pid=%d name=%s user%s", p.pid, p.name(), p.username())
continue
proc_sid = win32security.ConvertSidToStringSid(process_sid)
if sid and sid != proc_sid:
log.debug("Token for pid does not match user sid: %s", sid)
continue
if session_id and win32security.GetTokenInformation(th, win32security.TokenSessionId) != session_id:
continue
def has_priv(tok, priv):
luid = win32security.LookupPrivilegeValue(None, priv)
for priv_luid, flags in win32security.GetTokenInformation(tok, win32security.TokenPrivileges):
if priv_luid == luid:
return True
return False
if privs:
has_all = True
for name in privs:
if not has_priv(th, name):
has_all = False
if not has_all:
continue
yield dup_token(th)
def impersonate_sid(sid, session_id=None, privs=None):
'''
Find an existing process token for the given sid and impersonate the token.
'''
for tok in enumerate_tokens(sid, session_id, privs):
tok = dup_token(tok)
elevate_token(tok)
if win32security.ImpersonateLoggedOnUser(tok) == 0:
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
return tok
raise WindowsError("Impersonation failure") # pylint: disable=undefined-variable
def dup_token(th):
'''
duplicate the access token
'''
# TODO: is `duplicate_token` the same?
sec_attr = win32security.SECURITY_ATTRIBUTES()
sec_attr.bInheritHandle = True
return win32security.DuplicateTokenEx(
th,
win32security.SecurityImpersonation,
win32con.MAXIMUM_ALLOWED,
win32security.TokenPrimary,
sec_attr,
)
def elevate_token(th):
'''
Set all token priviledges to enabled
'''
# Get list of privileges this token contains
privileges = win32security.GetTokenInformation(
th, win32security.TokenPrivileges)
# Create a set of all privileges to be enabled
enable_privs = set()
for luid, flags in privileges:
enable_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED))
# Enable the privileges
if win32security.AdjustTokenPrivileges(th, 0, enable_privs) == 0:
raise WindowsError(win32api.FormatMessage(win32api.GetLastError())) # pylint: disable=undefined-variable
def CreateProcessWithLogonW(username=None, domain=None, password=None,
logonflags=0, applicationname=None, commandline=None, creationflags=0,
environment=None, currentdirectory=None, startupinfo=None):
creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
if commandline is not None:
commandline = ctypes.create_unicode_buffer(commandline)
if startupinfo is None:
startupinfo = STARTUPINFO()
process_info = PROCESS_INFORMATION()
advapi32.CreateProcessWithLogonW(
username,
domain,
password,
logonflags,
applicationname,
commandline,
creationflags,
environment,
currentdirectory,
ctypes.byref(startupinfo),
ctypes.byref(process_info),
)
return process_info
|
saltstack/salt | salt/states/boto_cloudfront.py | present | python | def present(
name,
config,
tags,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the CloudFront distribution is present.
name (string)
Name of the CloudFront distribution
config (dict)
Configuration for the distribution
tags (dict)
Tags to associate with the distribution
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
Example:
.. code-block:: yaml
Manage my_distribution CloudFront distribution:
boto_cloudfront.present:
- name: my_distribution
- config:
Comment: 'partial config shown, most parameters elided'
Enabled: True
- tags:
testing_key: testing_value
'''
ret = {
'name': name,
'comment': '',
'changes': {},
}
res = __salt__['boto_cloudfront.get_distribution'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error checking distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
old = res['result']
if old is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Distribution {0} set for creation.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
res = __salt__['boto_cloudfront.create_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error creating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Created distribution {0}.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
else:
full_config_old = {
'config': old['distribution']['DistributionConfig'],
'tags': old['tags'],
}
full_config_new = {
'config': config,
'tags': tags,
}
diffed_config = __utils__['dictdiffer.deep_diff'](
full_config_old,
full_config_new,
)
def _yaml_safe_dump(attrs):
'''
Safely dump YAML using a readable flow style
'''
dumper_name = 'IndentedSafeOrderedDumper'
dumper = __utils__['yaml.get_dumper'](dumper_name)
return __utils__['yaml.dump'](
attrs,
default_flow_style=False,
Dumper=dumper)
changes_diff = ''.join(difflib.unified_diff(
_yaml_safe_dump(full_config_old).splitlines(True),
_yaml_safe_dump(full_config_new).splitlines(True),
))
any_changes = bool('old' in diffed_config or 'new' in diffed_config)
if not any_changes:
ret['result'] = True
ret['comment'] = 'Distribution {0} has correct config.'.format(
name,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join([
'Distribution {0} set for new config:'.format(name),
changes_diff,
])
ret['changes'] = {'diff': changes_diff}
return ret
res = __salt__['boto_cloudfront.update_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error updating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Updated distribution {0}.'.format(name)
ret['changes'] = {'diff': changes_diff}
return ret | Ensure the CloudFront distribution is present.
name (string)
Name of the CloudFront distribution
config (dict)
Configuration for the distribution
tags (dict)
Tags to associate with the distribution
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
Example:
.. code-block:: yaml
Manage my_distribution CloudFront distribution:
boto_cloudfront.present:
- name: my_distribution
- config:
Comment: 'partial config shown, most parameters elided'
Enabled: True
- tags:
testing_key: testing_value | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudfront.py#L73-L237 | [
"def _yaml_safe_dump(attrs):\n '''\n Safely dump YAML using a readable flow style\n '''\n dumper_name = 'IndentedSafeOrderedDumper'\n dumper = __utils__['yaml.get_dumper'](dumper_name)\n return __utils__['yaml.dump'](\n attrs,\n default_flow_style=False,\n Dumper=dumper)\n"
] | # -*- coding: utf-8 -*-
'''
Manage CloudFront distributions
.. versionadded:: 2018.3.0
Create, update and destroy CloudFront distributions.
This module accepts explicit AWS credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API
and no further configuration is necessary.
More information available `here
<https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them,
either in a pillar file or in the minion's config file:
.. code-block:: yaml
cloudfront.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudfront.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid``, and ``region`` via a profile,
either passed in as a dict, or a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
aws:
region:
us-east-1:
profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import uuid
import copy
import json
# Import Salt conveniences
from salt.ext import six
from salt.ext.six.moves import range
#pylint: disable=W0106
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
if 'boto_cloudfront.get_distribution' not in __salt__:
msg = 'The boto_cloudfront state module could not be loaded: {}.'
return (False, msg.format('boto_cloudfront exec module unavailable.'))
return 'boto_cloudfront'
def _fix_quantities(tree):
'''
Stupidly simple function to fix any Items/Quantity disparities inside a
DistributionConfig block before use. Since AWS only accepts JSON-encodable
data types, this implementation is "good enough" for our purposes.
'''
if isinstance(tree, dict):
tree = {k: _fix_quantities(v) for k, v in tree.items()}
if isinstance(tree.get('Items'), list):
tree['Quantity'] = len(tree['Items'])
if not tree['Items']:
tree.pop('Items') # Silly, but AWS requires it....
return tree
elif isinstance(tree, list):
return [_fix_quantities(t) for t in tree]
else:
return tree
def distribution_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure the given CloudFront distribution exists in the described state.
The implementation of this function, and all those following, is orthagonal
to that of :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>`. Resources created with
:py:mod:`boto_cloudfront.present <salt.states.boto_cloudfront.present>`
will not be correctly managed by this function, as a different method is
used to store Salt's state signifier. This function and those following are
a suite, designed to work together. As an extra bonus, they correctly
process updates of the managed resources, so it is recommended to use them
in preference to :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>` above.
Note that the semantics of DistributionConfig (below) are rather arcane,
and vary wildly depending on whether the distribution already exists or not
(e.g. is being initially created, or being updated in place). Many more
details can be found here__.
.. __: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-overview-required-fields.html
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
DistributionConfig (dict)
Configuration for the distribution.
Notes:
- The CallerReference field should NOT be provided - it will be
autopopulated by Salt.
- A large number of sub- (and sub-sub-) fields require a ``Quantity``
element, which simply COUNTS the number of items in the ``Items``
element. This is bluntly stupid, so as a convenience, Salt will
traverse the provided configuration, and add (or fix) a ``Quantity``
element for any ``Items`` elements of list-type it encounters. This
adds a bit of sanity to an otherwise error-prone situation. Note
that for this to work, zero-length lists must be inlined as ``[]``.
- Due to the unavailibity of a better way to store stateful idempotency
information about Distributions, the Comment sub-element (as the only
user-settable attribute without weird self-blocking semantics, and
which is available from the core ``get_distribution()`` API call) is
utilized to store the Salt state signifier, which is used to
determine resource existence and state. That said, to enable **some**
usability of this field, only the value up to the first colon
character is taken as the signifier, with everything afterward
free-form, and ignored (but preserved) by Salt.
Tags (dict)
Tags to associate with the distribution.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
plt-dev-spaapi-cf-dist-cf_dist-present:
boto_cloudfront.distribution_present:
- Name: plt-dev-spaapi-cf-dist
- DistributionConfig:
Comment: SPA
Logging:
Enabled: false
Prefix: ''
Bucket: ''
IncludeCookies: false
WebACLId: ''
Origins:
Items:
- S3OriginConfig:
OriginAccessIdentity: the-SPA-OAI
OriginPath: ''
CustomHeaders:
Items: []
Id: S3-hs-backend-srpms
DomainName: hs-backend-srpms.s3.amazonaws.com
PriceClass: PriceClass_All
DefaultRootObject: ''
Enabled: true
DefaultCacheBehavior:
ViewerProtocolPolicy: allow-all
TrustedSigners:
Items: []
Enabled: false
SmoothStreaming: false
TargetOriginId: S3-hs-backend-srpms
FieldLevelEncryptionId: ''
ForwardedValues:
Headers:
Items: []
Cookies:
Forward: none
QueryStringCacheKeys:
Items: []
QueryString: false
MaxTTL: 31536000
LambdaFunctionAssociations:
Items: []
DefaultTTL: 86400
AllowedMethods:
CachedMethods:
Items:
- HEAD
- GET
Items:
- HEAD
- GET
MinTTL: 0
Compress: false
IsIPV6Enabled: true
ViewerCertificate:
CloudFrontDefaultCertificate: true
MinimumProtocolVersion: TLSv1
CertificateSource: cloudfront
Aliases:
Items:
- bubba-hotep.bodhi-dev.io
HttpVersion: http2
- Tags:
Owner: dev_engrs
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.pop('Name', name)
Tags = kwargs.pop('Tags', None)
DistributionConfig = kwargs.get('DistributionConfig', {})
## Sub-element munging on config data should go in here, before we proceed:
# For instance, origin access identities must be of the form
# `origin-access-identity/cloudfront/ID-of-origin-access-identity`, but we can't really
# know that ID apriori, so any OAI state names inside the config data must be resolved
# and converted into that format before submission. Be aware that the `state names` of
# salt managed OAIs are stored in their Comment fields for lack of any better place...
for item in range(len(DistributionConfig.get('Origins', {}).get('Items', []))):
oai = DistributionConfig['Origins']['Items'][item].get('S3OriginConfig',
{}).get('OriginAccessIdentity', '')
if oai and not oai.startswith('origin-access-identity/cloudfront/'):
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=oai, region=region, key=key, keyid=keyid, profile=profile)
if res is None: # An error occurred, bubble it up...
log.warning('Error encountered while trying to determine the Resource ID of'
' CloudFront origin access identity `%s`. Passing as-is.', oai)
elif not res:
log.warning('Failed to determine the Resource ID of CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
elif len(res) > 1:
log.warning('Failed to find unique Resource ID for CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
else:
# One unique OAI resource found -- deref and replace it...
new = 'origin-access-identity/cloudfront/{}'.format(res[0]['Id'])
DistributionConfig['Origins']['Items'][item]['S3OriginConfig']['OriginAccessIdentity'] = new
# Munge Name into the Comment field...
DistributionConfig['Comment'] = '{}:{}'.format(Name, DistributionConfig['Comment']) \
if DistributionConfig.get('Comment') else Name
# Fix up any missing (or wrong) Quantity sub-elements...
DistributionConfig = _fix_quantities(DistributionConfig)
kwargs['DistributionConfig'] = DistributionConfig
# Current state of the thing?
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, region=region,
key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
# Luckily, the `DistributionConfig` structure returned by `get_distribution()` (as a sub-
# element of `Distribution`) is identical to that returned by `get_distribution_config(),
# and as a bonus, the ETag's are ALSO compatible...
# Since "updates" are actually "replace everything from scratch" events, this implies that
# it's enough to simply determine SOME update is necessary to trigger one, rather than
# exhaustively calculating all changes needed - this makes life MUCH EASIER :)
# Thus our workflow here is:
# - check if the distribution exists
# - if it doesn't, create it fresh with the requested DistributionConfig, and Tag it if needed
# - if it does, grab its ETag, and TWO copies of the current DistributionConfig
# - merge the requested DistributionConfig on top of one of them
# - compare the copy we just merged against the one we didn't
# - if they differ, send the merged copy, along with the ETag we got, back as an update
# - lastly, verify and set/unset any Tags which may need changing...
exists = bool(res)
if not exists:
if 'CallerReference' not in kwargs['DistributionConfig']:
kwargs['DistributionConfig']['CallerReference'] = str(uuid.uuid4())
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be created.'.format(Name)
new = {'DistributionConfig': kwargs['DistributionConfig']}
new.update({'Tags': Tags}) if Tags else None
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs.update(authargs)
comments = []
res = __salt__['boto_cloudfront.create_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while creating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
new = {'DistributionConfig': res['Distribution']['DistributionConfig']}
comments += ['Created distribution `{}`.'.format(Name)]
newARN = res.get('Distribution', {}).get('ARN')
tagged = __salt__['boto_cloudfront.tag_resource'](Tags=Tags, **authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while tagging distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['Tagged distribution `{}`.'.format(Name)]
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': None, 'new': new}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_distribution_v2'](Id=currentId, **authargs)
# Insanely unlikely given that we JUST got back this Id from the previous search, but....
if not current:
msg = 'Failed to lookup CloudFront distribution with Id `{}`.'.format(currentId)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
currentDC = current['Distribution']['DistributionConfig']
currentARN = current['Distribution']['ARN']
currentETag = current['ETag']
currentTags = __salt__['boto_cloudfront.list_tags_for_resource'](Resource=currentARN,
**authargs)
copyOne = copy.deepcopy(currentDC)
copyTwo = copy.deepcopy(currentDC)
copyTwo.update(kwargs['DistributionConfig'])
correct = __utils__['boto3.json_objs_equal'](copyOne, copyTwo)
tags_correct = (currentTags == Tags)
comments = []
old = {}
new = {}
if correct and tags_correct:
ret['comment'] = 'CloudFront distribution `{}` is in the correct state.'.format(Name)
return ret
if __opts__['test']:
ret['result'] = None
if not correct:
comments += ['CloudFront distribution `{}` config would be updated.'.format(Name)]
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = copyTwo
if not tags_correct:
comments += ['CloudFront distribution `{}` Tags would be updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['pchanges'] = {'old': old, 'new': new}
return ret
if not correct:
kwargs = {'DistributionConfig': copyTwo, 'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
log.debug('Calling `boto_cloudfront.update_distribution_v2()` with **kwargs =='
' %s', kwargs)
res = __salt__['boto_cloudfront.update_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = res['Distribution']['DistributionConfig']
comments += ['CloudFront distribution `{}` config updated.'.format(Name)]
if not tags_correct:
tagged = __salt__['boto_cloudfront.enforce_tags'](Resource=currentARN, Tags=Tags,
**authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while updating Tags on distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['CloudFront distribution `{}` Tags updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': new}
return ret
def oai_bucket_policy_present(name, Bucket, OAI, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the given policy exists on an S3 bucket, granting access for the given origin access
identity to do the things specified in the policy.
name
The name of the state definition
Bucket
The S3 bucket which CloudFront needs access to. Note that this policy
is exclusive - it will be the only policy definition on the bucket (and
objects inside the bucket if you specify such permissions in the
policy). Note that this likely SHOULD reflect the bucket mentioned in
the Resource section of the Policy, but this is not enforced...
OAI
The value of `Name` passed to the state definition for the origin
access identity which will be accessing the bucket.
Policy
The full policy document which should be set on the S3 bucket. If a
``Principal`` clause is not provided in the policy, one will be
automatically added, and pointed at the correct value as dereferenced
from the OAI provided above. If one IS provided, then this is not
done, and you are responsible for providing the correct values.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_oai_s3_policy:
boto_cloudfront.oai_bucket_policy_present:
- Bucket: the_bucket_for_my_distribution
- OAI: the_OAI_I_just_created_and_attached_to_my_distribution
- Policy:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::the_bucket_for_my_distribution/*
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
oais = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=OAI, region=region, key=key, keyid=keyid, profile=profile)
if len(oais) > 1:
msg = 'Multiple origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not oais:
msg = 'No origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
canonical_user = oais[0].get('S3CanonicalUserId')
oai_id = oais[0].get('Id')
if isinstance(Policy, six.string_types):
Policy = json.loads(Policy)
for stanza in range(len(Policy.get('Statement', []))):
if 'Principal' not in Policy['Statement'][stanza]:
Policy['Statement'][stanza]['Principal'] = {"CanonicalUser": canonical_user}
bucket = __salt__['boto_s3_bucket.describe'](Bucket=Bucket, region=region, key=key,
keyid=keyid, profile=profile)
if not bucket or 'bucket' not in bucket:
msg = 'S3 bucket `{}` not found.'.format(Bucket)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
curr_policy = bucket['bucket'].get('Policy', {}).get('Policy', {}) # ?!? dunno, that's just how it gets returned...
curr_policy = json.loads(curr_policy) if isinstance(curr_policy,
six.string_types) else curr_policy
# Sooooo, you have to SUBMIT Principals of the form
# Principal: {'S3CanonicalUserId': someCrazyLongMagicValueAsDerivedAbove}
# BUT, they RETURN the Principal as something WILDLY different
# Principal: {'AWS': arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E30ABCDEF12345}
# which obviously compare different on every run... So we fake it thusly.
fake_Policy = copy.deepcopy(Policy)
for stanza in range(len(fake_Policy.get('Statement', []))):
# Warning: unavoidable hardcoded magic values HO!
fake_Policy['Statement'][stanza].update({'Principal': {'AWS':
'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity {}'.format(oai_id)}})
if __utils__['boto3.json_objs_equal'](curr_policy, fake_Policy):
msg = 'Policy of S3 bucket `{}` is in the correct state.'.format(Bucket)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['comment'] = 'Policy on S3 bucket `{}` would be updated.'.format(Bucket)
ret['result'] = None
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
res = __salt__['boto_s3_bucket.put_policy'](Bucket=Bucket, Policy=Policy,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in res:
ret['comment'] = 'Failed to update policy on S3 bucket `{}`: {}'.format(Bucket,
res['error'])
ret['return'] = False
return ret
ret['comment'] = 'Policy on S3 bucket `{}` updated.'.format(Bucket)
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
def route53_alias_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a Route53 Alias exists and is pointing at the given CloudFront
distribution. An ``A`` record is always created, and if IPV6 is enabled on
the given distribution, an ``AAAA`` record will be created as well. Also be
aware that Alias records for CloudFront distributions are only permitted in
non-private zones.
name
The name of the state definition.
Distribution
The name of the CloudFront distribution. Defaults to the value of
``name`` if not provided.
HostedZoneId
Id of the Route53 hosted zone within which the records should be created.
DomainName
The domain name associated with the Hosted Zone. Exclusive with HostedZoneId.
ResourceRecordSet
A Route53 Record Set (with AliasTarget section, suitable for use as an
``Alias`` record, if non-default settings are needed on the Alias)
which should be pointed at the provided CloudFront distribution. Note
that this MUST correlate with the Aliases set within the
DistributionConfig section of the distribution.
Some notes *specifically* about the ``AliasTarget`` subsection of the
ResourceRecordSet:
- If not specified, the ``DNSName`` sub-field will be populated by
dereferencing ``Distribution`` above to the value of its
``DomainName`` attribute.
- The HostedZoneId sub-field should not be provided -- it will be
automatically populated with a ``magic`` AWS value.
- The EvaluateTargetHealth can only be False on a CloudFront Alias.
- The above items taken all together imply that, for most use-cases,
the AliasTarget sub-section can be entirely omitted, as seen in the
first code sample below.
Lastly, note that if you set ``name`` to the desired ResourceRecordSet
Name, you can entirely omit this parameter, as shown in the second
example below.
.. code-block:: yaml
Add a Route53 Alias for my_distribution:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
- ResourceRecordSet:
Name: the-alias.saltstack.org.
# This is even simpler - it uses the value of `name` for ResourceRecordSet.Name
another-alias.saltstack.org.:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
'''
MAGIC_CLOUDFRONT_HOSTED_ZONEID = 'Z2FDTNDATAQYW2'
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
Distribution = kwargs['Distribution'] if 'Distribution' in kwargs else name
ResourceRecordSet = kwargs.get('ResourceRecordSet', {})
Name = ResourceRecordSet.get('Name', name)
ResourceRecordSet['Name'] = Name
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Distribution,
region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error resolving CloudFront distribution `{}` to a Resource ID.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'No CloudFront distibutions matching `{}` found.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
dist = res[0]
Types = ('A', 'AAAA') if dist.get('IsIPV6Enabled', False) else ('A',)
DNSName = dist.get('DomainName', '')
Aliases = dist.get('Aliases', {}).get('Items', [])
# AWS annoyance #437:
# Route53 "FQDNs" (correctly!) REQUIRE trailing periods...
# while CloudFront "FQDNs" don't PERMIT trailing periods...
Aliases += [(a if a.endswith('.') else '{}.'.format(a)) for a in Aliases]
if Name not in Aliases:
msg = ('Route53 alias `{}` requested which is not mirrored in the `Aliases`'
' sub-section of the DistributionConfig.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
changes = {'old': [], 'new': []}
comments = []
# Now mock out a route53 state def, and use the route53 rr_exists state to enforce it...
AliasTarget = ResourceRecordSet.get('AliasTarget', {})
AliasTarget['DNSName'] = AliasTarget['DNSName'] if 'DNSName' in AliasTarget else DNSName
AliasTarget['DNSName'] += '' if AliasTarget['DNSName'].endswith('.') else '.' # GRRRR!
AliasTarget['HostedZoneId'] = MAGIC_CLOUDFRONT_HOSTED_ZONEID
AliasTarget['EvaluateTargetHealth'] = False # Route53 limitation
ResourceRecordSet['name'] = Name
ResourceRecordSet['AliasTarget'] = AliasTarget
ResourceRecordSet['PrivateZone'] = False # Route53 limitation
ResourceRecordSet['DomainName'] = kwargs.get('DomainName')
ResourceRecordSet['HostedZoneId'] = kwargs.get('HostedZoneId')
ResourceRecordSet.update({'region': region, 'key': key, 'keyid': keyid, 'profile': profile})
for Type in Types:
ResourceRecordSet['Type'] = Type
# Checking for `test=True` will occur in the called state....
log.debug('Calling state function `boto3_route53.rr_present()` with args: `%s`',
ResourceRecordSet)
res = __states__['boto3_route53.rr_present'](**ResourceRecordSet)
ret['result'] = res['result']
comments += [res['comment']]
if ret['result'] not in (True, None):
break
changes['old'] += [res['changes']['old']] if res['changes'].get('old') else []
changes['new'] += [res['changes']['new']] if res['changes'].get('new') else []
ret['changes'].update({'old': changes['old']}) if changes.get('old') else None
ret['changes'].update({'new': changes['new']}) if changes.get('new') else None
ret['comment'] = ' '.join(comments)
return ret
def distribution_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
distribution's status to Disabled, and once that returns success, to then
delete the resource. THIS CAN TAKE SOME TIME, so be patient :)
name (string)
Name of the state definition.
Name (string)
Name of the CloudFront distribution to be managed. If not provided, the
value of ``name`` will be used as a default. The purpose of this
parameter is only to resolve it to a Resource ID, so be aware that an
explicit value for ``Id`` below will override any value provided, or
defaulted, here.
Id (string)
The Resource ID of a CloudFront distribution to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure a distribution named my_distribution is gone:
boto_cloudfront.distribution_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
if not Id:
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, **authargs)
if res is None:
msg = 'Error dereferencing CloudFront distribution `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = ('Multiple CloudFront distibutions matched `{}`, no way to know which to'
' delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'CloudFront Distribution `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = res[0]['Id']
if not __salt__['boto_cloudfront.distribution_exists'](Id=Id, **authargs):
msg = 'CloudFront distribution `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_distribution_v2'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront distribution `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
currETag = old['ETag']
Enabled = old['DistributionConfig']['Enabled']
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be {}deleted.'.format(ref,
('disabled and ' if Enabled else ''))
ret['pchanges'] = {'old': old, 'new': None}
return ret
comments = []
if Enabled:
disabled = __salt__['boto_cloudfront.disable_distribution'](Id=Id, **authargs)
if disabled is None:
ret['result'] = False
msg = 'Error disabling CloudFront distribution `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
comments += ['CloudFront distribution `{}` disabled.'.format(ref)]
currETag = disabled['ETag']
deleted = __salt__['boto_cloudfront.delete_distribution'](Id=Id, IfMatch=currETag, **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront distribution `{}`'.format(ref)
comments += [msg]
log.error(msg)
ret['comment'] = ' '.join(comments)
return ret
msg = 'CloudFront distribution `{}` deleted.'.format(ref)
comments += [msg]
log.info(msg)
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': None}
return ret
def origin_access_identity_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity exists.
.. note::
Due to the unavailibity of ANY other way to store stateful idempotency
information about Origin Access Identities (including resource tags),
the Comment attribute (as the only user-settable attribute without
weird self-blocking semantics) is necessarily utilized to store the
Salt state signifier, which is used to determine resource existence and
state. That said, to enable SOME usability of this field, only the
value up to the first colon character is taken as the signifier, while
anything afterward is free-form and ignored by Salt.
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not provided, the value of
`name` will be used.
Comment
Free-form text description of the origin access identity.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_OAI:
boto_cloudfront.origin_access_identity_present:
- Comment: Simply ensures an OAI named my_OAI exists
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.get('Name', name)
# Munge Name into the Comment field...
Comment = '{}:{}'.format(Name, kwargs['Comment']) if kwargs.get('Comment') else Name
# Current state of the thing?
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront origin access identities matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
exists = bool(res)
if not exists:
CloudFrontOriginAccessIdentityConfig = {'Comment': Comment,
'CallerReference': str(uuid.uuid4())}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be created.'.format(Name)
new = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.create_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Failed to create CloudFront origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'Created CloudFrong origin access identity`{}`.'.format(Name)
ret['changes'] = {'old': None, 'new': res}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=currentId,
**authargs)
currentETag = current['ETag']
currentOAIC = current['CloudFrontOriginAccessIdentity']['CloudFrontOriginAccessIdentityConfig']
new = copy.deepcopy(currentOAIC)
new.update({'Comment': Comment}) # Currently the only updatable element :-/
if currentOAIC == new:
msg = 'CloudFront origin access identity `{}` is in the correct state.'.format(Name)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be updated.'.format(Name)
ret['pchanges'] = {'old': currentOAIC, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': new,
'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.update_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'CloudFront origin access identity `{}` config updated.'.format(Name)
ret['changes'] = {'old': currentOAIC, 'new': new}
return ret
def origin_access_identity_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity is absent.
name
The name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
Id (string)
The Resource ID of a CloudFront origin access identity to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure an origin access identity named my_OAI is gone:
boto_cloudfront.origin_access_identity_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
current = None
if not Id:
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, **authargs)
if current is None:
msg = 'Error dereferencing origin access identity `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(current) > 1:
msg = ('Multiple CloudFront origin access identities matched `{}`, no way to know'
' which to delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not current:
msg = 'CloudFront origin access identity `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = current[0]['Id']
if not __salt__['boto_cloudfront.cloud_front_origin_access_identity_exists'](Id=Id, **authargs):
msg = 'CloudFront origin access identity `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront origin access identity `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be deleted.'.format(ref)
ret['pchanges'] = {'old': old, 'new': None}
return ret
deleted = __salt__['boto_cloudfront.delete_cloud_front_origin_access_identity'](Id=Id,
IfMatch=old['ETag'], **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront origin access identity `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
msg = 'CloudFront origin access identity `{}` deleted.'.format(ref)
log.info(msg)
ret['comment'] = msg
ret['changes'] = {'old': old, 'new': None}
return ret
|
saltstack/salt | salt/states/boto_cloudfront.py | _fix_quantities | python | def _fix_quantities(tree):
'''
Stupidly simple function to fix any Items/Quantity disparities inside a
DistributionConfig block before use. Since AWS only accepts JSON-encodable
data types, this implementation is "good enough" for our purposes.
'''
if isinstance(tree, dict):
tree = {k: _fix_quantities(v) for k, v in tree.items()}
if isinstance(tree.get('Items'), list):
tree['Quantity'] = len(tree['Items'])
if not tree['Items']:
tree.pop('Items') # Silly, but AWS requires it....
return tree
elif isinstance(tree, list):
return [_fix_quantities(t) for t in tree]
else:
return tree | Stupidly simple function to fix any Items/Quantity disparities inside a
DistributionConfig block before use. Since AWS only accepts JSON-encodable
data types, this implementation is "good enough" for our purposes. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudfront.py#L240-L256 | null | # -*- coding: utf-8 -*-
'''
Manage CloudFront distributions
.. versionadded:: 2018.3.0
Create, update and destroy CloudFront distributions.
This module accepts explicit AWS credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API
and no further configuration is necessary.
More information available `here
<https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them,
either in a pillar file or in the minion's config file:
.. code-block:: yaml
cloudfront.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudfront.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid``, and ``region`` via a profile,
either passed in as a dict, or a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
aws:
region:
us-east-1:
profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import uuid
import copy
import json
# Import Salt conveniences
from salt.ext import six
from salt.ext.six.moves import range
#pylint: disable=W0106
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
if 'boto_cloudfront.get_distribution' not in __salt__:
msg = 'The boto_cloudfront state module could not be loaded: {}.'
return (False, msg.format('boto_cloudfront exec module unavailable.'))
return 'boto_cloudfront'
def present(
name,
config,
tags,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the CloudFront distribution is present.
name (string)
Name of the CloudFront distribution
config (dict)
Configuration for the distribution
tags (dict)
Tags to associate with the distribution
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
Example:
.. code-block:: yaml
Manage my_distribution CloudFront distribution:
boto_cloudfront.present:
- name: my_distribution
- config:
Comment: 'partial config shown, most parameters elided'
Enabled: True
- tags:
testing_key: testing_value
'''
ret = {
'name': name,
'comment': '',
'changes': {},
}
res = __salt__['boto_cloudfront.get_distribution'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error checking distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
old = res['result']
if old is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Distribution {0} set for creation.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
res = __salt__['boto_cloudfront.create_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error creating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Created distribution {0}.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
else:
full_config_old = {
'config': old['distribution']['DistributionConfig'],
'tags': old['tags'],
}
full_config_new = {
'config': config,
'tags': tags,
}
diffed_config = __utils__['dictdiffer.deep_diff'](
full_config_old,
full_config_new,
)
def _yaml_safe_dump(attrs):
'''
Safely dump YAML using a readable flow style
'''
dumper_name = 'IndentedSafeOrderedDumper'
dumper = __utils__['yaml.get_dumper'](dumper_name)
return __utils__['yaml.dump'](
attrs,
default_flow_style=False,
Dumper=dumper)
changes_diff = ''.join(difflib.unified_diff(
_yaml_safe_dump(full_config_old).splitlines(True),
_yaml_safe_dump(full_config_new).splitlines(True),
))
any_changes = bool('old' in diffed_config or 'new' in diffed_config)
if not any_changes:
ret['result'] = True
ret['comment'] = 'Distribution {0} has correct config.'.format(
name,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join([
'Distribution {0} set for new config:'.format(name),
changes_diff,
])
ret['changes'] = {'diff': changes_diff}
return ret
res = __salt__['boto_cloudfront.update_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error updating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Updated distribution {0}.'.format(name)
ret['changes'] = {'diff': changes_diff}
return ret
def distribution_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure the given CloudFront distribution exists in the described state.
The implementation of this function, and all those following, is orthagonal
to that of :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>`. Resources created with
:py:mod:`boto_cloudfront.present <salt.states.boto_cloudfront.present>`
will not be correctly managed by this function, as a different method is
used to store Salt's state signifier. This function and those following are
a suite, designed to work together. As an extra bonus, they correctly
process updates of the managed resources, so it is recommended to use them
in preference to :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>` above.
Note that the semantics of DistributionConfig (below) are rather arcane,
and vary wildly depending on whether the distribution already exists or not
(e.g. is being initially created, or being updated in place). Many more
details can be found here__.
.. __: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-overview-required-fields.html
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
DistributionConfig (dict)
Configuration for the distribution.
Notes:
- The CallerReference field should NOT be provided - it will be
autopopulated by Salt.
- A large number of sub- (and sub-sub-) fields require a ``Quantity``
element, which simply COUNTS the number of items in the ``Items``
element. This is bluntly stupid, so as a convenience, Salt will
traverse the provided configuration, and add (or fix) a ``Quantity``
element for any ``Items`` elements of list-type it encounters. This
adds a bit of sanity to an otherwise error-prone situation. Note
that for this to work, zero-length lists must be inlined as ``[]``.
- Due to the unavailibity of a better way to store stateful idempotency
information about Distributions, the Comment sub-element (as the only
user-settable attribute without weird self-blocking semantics, and
which is available from the core ``get_distribution()`` API call) is
utilized to store the Salt state signifier, which is used to
determine resource existence and state. That said, to enable **some**
usability of this field, only the value up to the first colon
character is taken as the signifier, with everything afterward
free-form, and ignored (but preserved) by Salt.
Tags (dict)
Tags to associate with the distribution.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
plt-dev-spaapi-cf-dist-cf_dist-present:
boto_cloudfront.distribution_present:
- Name: plt-dev-spaapi-cf-dist
- DistributionConfig:
Comment: SPA
Logging:
Enabled: false
Prefix: ''
Bucket: ''
IncludeCookies: false
WebACLId: ''
Origins:
Items:
- S3OriginConfig:
OriginAccessIdentity: the-SPA-OAI
OriginPath: ''
CustomHeaders:
Items: []
Id: S3-hs-backend-srpms
DomainName: hs-backend-srpms.s3.amazonaws.com
PriceClass: PriceClass_All
DefaultRootObject: ''
Enabled: true
DefaultCacheBehavior:
ViewerProtocolPolicy: allow-all
TrustedSigners:
Items: []
Enabled: false
SmoothStreaming: false
TargetOriginId: S3-hs-backend-srpms
FieldLevelEncryptionId: ''
ForwardedValues:
Headers:
Items: []
Cookies:
Forward: none
QueryStringCacheKeys:
Items: []
QueryString: false
MaxTTL: 31536000
LambdaFunctionAssociations:
Items: []
DefaultTTL: 86400
AllowedMethods:
CachedMethods:
Items:
- HEAD
- GET
Items:
- HEAD
- GET
MinTTL: 0
Compress: false
IsIPV6Enabled: true
ViewerCertificate:
CloudFrontDefaultCertificate: true
MinimumProtocolVersion: TLSv1
CertificateSource: cloudfront
Aliases:
Items:
- bubba-hotep.bodhi-dev.io
HttpVersion: http2
- Tags:
Owner: dev_engrs
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.pop('Name', name)
Tags = kwargs.pop('Tags', None)
DistributionConfig = kwargs.get('DistributionConfig', {})
## Sub-element munging on config data should go in here, before we proceed:
# For instance, origin access identities must be of the form
# `origin-access-identity/cloudfront/ID-of-origin-access-identity`, but we can't really
# know that ID apriori, so any OAI state names inside the config data must be resolved
# and converted into that format before submission. Be aware that the `state names` of
# salt managed OAIs are stored in their Comment fields for lack of any better place...
for item in range(len(DistributionConfig.get('Origins', {}).get('Items', []))):
oai = DistributionConfig['Origins']['Items'][item].get('S3OriginConfig',
{}).get('OriginAccessIdentity', '')
if oai and not oai.startswith('origin-access-identity/cloudfront/'):
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=oai, region=region, key=key, keyid=keyid, profile=profile)
if res is None: # An error occurred, bubble it up...
log.warning('Error encountered while trying to determine the Resource ID of'
' CloudFront origin access identity `%s`. Passing as-is.', oai)
elif not res:
log.warning('Failed to determine the Resource ID of CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
elif len(res) > 1:
log.warning('Failed to find unique Resource ID for CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
else:
# One unique OAI resource found -- deref and replace it...
new = 'origin-access-identity/cloudfront/{}'.format(res[0]['Id'])
DistributionConfig['Origins']['Items'][item]['S3OriginConfig']['OriginAccessIdentity'] = new
# Munge Name into the Comment field...
DistributionConfig['Comment'] = '{}:{}'.format(Name, DistributionConfig['Comment']) \
if DistributionConfig.get('Comment') else Name
# Fix up any missing (or wrong) Quantity sub-elements...
DistributionConfig = _fix_quantities(DistributionConfig)
kwargs['DistributionConfig'] = DistributionConfig
# Current state of the thing?
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, region=region,
key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
# Luckily, the `DistributionConfig` structure returned by `get_distribution()` (as a sub-
# element of `Distribution`) is identical to that returned by `get_distribution_config(),
# and as a bonus, the ETag's are ALSO compatible...
# Since "updates" are actually "replace everything from scratch" events, this implies that
# it's enough to simply determine SOME update is necessary to trigger one, rather than
# exhaustively calculating all changes needed - this makes life MUCH EASIER :)
# Thus our workflow here is:
# - check if the distribution exists
# - if it doesn't, create it fresh with the requested DistributionConfig, and Tag it if needed
# - if it does, grab its ETag, and TWO copies of the current DistributionConfig
# - merge the requested DistributionConfig on top of one of them
# - compare the copy we just merged against the one we didn't
# - if they differ, send the merged copy, along with the ETag we got, back as an update
# - lastly, verify and set/unset any Tags which may need changing...
exists = bool(res)
if not exists:
if 'CallerReference' not in kwargs['DistributionConfig']:
kwargs['DistributionConfig']['CallerReference'] = str(uuid.uuid4())
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be created.'.format(Name)
new = {'DistributionConfig': kwargs['DistributionConfig']}
new.update({'Tags': Tags}) if Tags else None
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs.update(authargs)
comments = []
res = __salt__['boto_cloudfront.create_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while creating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
new = {'DistributionConfig': res['Distribution']['DistributionConfig']}
comments += ['Created distribution `{}`.'.format(Name)]
newARN = res.get('Distribution', {}).get('ARN')
tagged = __salt__['boto_cloudfront.tag_resource'](Tags=Tags, **authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while tagging distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['Tagged distribution `{}`.'.format(Name)]
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': None, 'new': new}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_distribution_v2'](Id=currentId, **authargs)
# Insanely unlikely given that we JUST got back this Id from the previous search, but....
if not current:
msg = 'Failed to lookup CloudFront distribution with Id `{}`.'.format(currentId)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
currentDC = current['Distribution']['DistributionConfig']
currentARN = current['Distribution']['ARN']
currentETag = current['ETag']
currentTags = __salt__['boto_cloudfront.list_tags_for_resource'](Resource=currentARN,
**authargs)
copyOne = copy.deepcopy(currentDC)
copyTwo = copy.deepcopy(currentDC)
copyTwo.update(kwargs['DistributionConfig'])
correct = __utils__['boto3.json_objs_equal'](copyOne, copyTwo)
tags_correct = (currentTags == Tags)
comments = []
old = {}
new = {}
if correct and tags_correct:
ret['comment'] = 'CloudFront distribution `{}` is in the correct state.'.format(Name)
return ret
if __opts__['test']:
ret['result'] = None
if not correct:
comments += ['CloudFront distribution `{}` config would be updated.'.format(Name)]
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = copyTwo
if not tags_correct:
comments += ['CloudFront distribution `{}` Tags would be updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['pchanges'] = {'old': old, 'new': new}
return ret
if not correct:
kwargs = {'DistributionConfig': copyTwo, 'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
log.debug('Calling `boto_cloudfront.update_distribution_v2()` with **kwargs =='
' %s', kwargs)
res = __salt__['boto_cloudfront.update_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = res['Distribution']['DistributionConfig']
comments += ['CloudFront distribution `{}` config updated.'.format(Name)]
if not tags_correct:
tagged = __salt__['boto_cloudfront.enforce_tags'](Resource=currentARN, Tags=Tags,
**authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while updating Tags on distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['CloudFront distribution `{}` Tags updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': new}
return ret
def oai_bucket_policy_present(name, Bucket, OAI, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the given policy exists on an S3 bucket, granting access for the given origin access
identity to do the things specified in the policy.
name
The name of the state definition
Bucket
The S3 bucket which CloudFront needs access to. Note that this policy
is exclusive - it will be the only policy definition on the bucket (and
objects inside the bucket if you specify such permissions in the
policy). Note that this likely SHOULD reflect the bucket mentioned in
the Resource section of the Policy, but this is not enforced...
OAI
The value of `Name` passed to the state definition for the origin
access identity which will be accessing the bucket.
Policy
The full policy document which should be set on the S3 bucket. If a
``Principal`` clause is not provided in the policy, one will be
automatically added, and pointed at the correct value as dereferenced
from the OAI provided above. If one IS provided, then this is not
done, and you are responsible for providing the correct values.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_oai_s3_policy:
boto_cloudfront.oai_bucket_policy_present:
- Bucket: the_bucket_for_my_distribution
- OAI: the_OAI_I_just_created_and_attached_to_my_distribution
- Policy:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::the_bucket_for_my_distribution/*
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
oais = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=OAI, region=region, key=key, keyid=keyid, profile=profile)
if len(oais) > 1:
msg = 'Multiple origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not oais:
msg = 'No origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
canonical_user = oais[0].get('S3CanonicalUserId')
oai_id = oais[0].get('Id')
if isinstance(Policy, six.string_types):
Policy = json.loads(Policy)
for stanza in range(len(Policy.get('Statement', []))):
if 'Principal' not in Policy['Statement'][stanza]:
Policy['Statement'][stanza]['Principal'] = {"CanonicalUser": canonical_user}
bucket = __salt__['boto_s3_bucket.describe'](Bucket=Bucket, region=region, key=key,
keyid=keyid, profile=profile)
if not bucket or 'bucket' not in bucket:
msg = 'S3 bucket `{}` not found.'.format(Bucket)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
curr_policy = bucket['bucket'].get('Policy', {}).get('Policy', {}) # ?!? dunno, that's just how it gets returned...
curr_policy = json.loads(curr_policy) if isinstance(curr_policy,
six.string_types) else curr_policy
# Sooooo, you have to SUBMIT Principals of the form
# Principal: {'S3CanonicalUserId': someCrazyLongMagicValueAsDerivedAbove}
# BUT, they RETURN the Principal as something WILDLY different
# Principal: {'AWS': arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E30ABCDEF12345}
# which obviously compare different on every run... So we fake it thusly.
fake_Policy = copy.deepcopy(Policy)
for stanza in range(len(fake_Policy.get('Statement', []))):
# Warning: unavoidable hardcoded magic values HO!
fake_Policy['Statement'][stanza].update({'Principal': {'AWS':
'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity {}'.format(oai_id)}})
if __utils__['boto3.json_objs_equal'](curr_policy, fake_Policy):
msg = 'Policy of S3 bucket `{}` is in the correct state.'.format(Bucket)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['comment'] = 'Policy on S3 bucket `{}` would be updated.'.format(Bucket)
ret['result'] = None
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
res = __salt__['boto_s3_bucket.put_policy'](Bucket=Bucket, Policy=Policy,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in res:
ret['comment'] = 'Failed to update policy on S3 bucket `{}`: {}'.format(Bucket,
res['error'])
ret['return'] = False
return ret
ret['comment'] = 'Policy on S3 bucket `{}` updated.'.format(Bucket)
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
def route53_alias_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a Route53 Alias exists and is pointing at the given CloudFront
distribution. An ``A`` record is always created, and if IPV6 is enabled on
the given distribution, an ``AAAA`` record will be created as well. Also be
aware that Alias records for CloudFront distributions are only permitted in
non-private zones.
name
The name of the state definition.
Distribution
The name of the CloudFront distribution. Defaults to the value of
``name`` if not provided.
HostedZoneId
Id of the Route53 hosted zone within which the records should be created.
DomainName
The domain name associated with the Hosted Zone. Exclusive with HostedZoneId.
ResourceRecordSet
A Route53 Record Set (with AliasTarget section, suitable for use as an
``Alias`` record, if non-default settings are needed on the Alias)
which should be pointed at the provided CloudFront distribution. Note
that this MUST correlate with the Aliases set within the
DistributionConfig section of the distribution.
Some notes *specifically* about the ``AliasTarget`` subsection of the
ResourceRecordSet:
- If not specified, the ``DNSName`` sub-field will be populated by
dereferencing ``Distribution`` above to the value of its
``DomainName`` attribute.
- The HostedZoneId sub-field should not be provided -- it will be
automatically populated with a ``magic`` AWS value.
- The EvaluateTargetHealth can only be False on a CloudFront Alias.
- The above items taken all together imply that, for most use-cases,
the AliasTarget sub-section can be entirely omitted, as seen in the
first code sample below.
Lastly, note that if you set ``name`` to the desired ResourceRecordSet
Name, you can entirely omit this parameter, as shown in the second
example below.
.. code-block:: yaml
Add a Route53 Alias for my_distribution:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
- ResourceRecordSet:
Name: the-alias.saltstack.org.
# This is even simpler - it uses the value of `name` for ResourceRecordSet.Name
another-alias.saltstack.org.:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
'''
MAGIC_CLOUDFRONT_HOSTED_ZONEID = 'Z2FDTNDATAQYW2'
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
Distribution = kwargs['Distribution'] if 'Distribution' in kwargs else name
ResourceRecordSet = kwargs.get('ResourceRecordSet', {})
Name = ResourceRecordSet.get('Name', name)
ResourceRecordSet['Name'] = Name
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Distribution,
region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error resolving CloudFront distribution `{}` to a Resource ID.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'No CloudFront distibutions matching `{}` found.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
dist = res[0]
Types = ('A', 'AAAA') if dist.get('IsIPV6Enabled', False) else ('A',)
DNSName = dist.get('DomainName', '')
Aliases = dist.get('Aliases', {}).get('Items', [])
# AWS annoyance #437:
# Route53 "FQDNs" (correctly!) REQUIRE trailing periods...
# while CloudFront "FQDNs" don't PERMIT trailing periods...
Aliases += [(a if a.endswith('.') else '{}.'.format(a)) for a in Aliases]
if Name not in Aliases:
msg = ('Route53 alias `{}` requested which is not mirrored in the `Aliases`'
' sub-section of the DistributionConfig.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
changes = {'old': [], 'new': []}
comments = []
# Now mock out a route53 state def, and use the route53 rr_exists state to enforce it...
AliasTarget = ResourceRecordSet.get('AliasTarget', {})
AliasTarget['DNSName'] = AliasTarget['DNSName'] if 'DNSName' in AliasTarget else DNSName
AliasTarget['DNSName'] += '' if AliasTarget['DNSName'].endswith('.') else '.' # GRRRR!
AliasTarget['HostedZoneId'] = MAGIC_CLOUDFRONT_HOSTED_ZONEID
AliasTarget['EvaluateTargetHealth'] = False # Route53 limitation
ResourceRecordSet['name'] = Name
ResourceRecordSet['AliasTarget'] = AliasTarget
ResourceRecordSet['PrivateZone'] = False # Route53 limitation
ResourceRecordSet['DomainName'] = kwargs.get('DomainName')
ResourceRecordSet['HostedZoneId'] = kwargs.get('HostedZoneId')
ResourceRecordSet.update({'region': region, 'key': key, 'keyid': keyid, 'profile': profile})
for Type in Types:
ResourceRecordSet['Type'] = Type
# Checking for `test=True` will occur in the called state....
log.debug('Calling state function `boto3_route53.rr_present()` with args: `%s`',
ResourceRecordSet)
res = __states__['boto3_route53.rr_present'](**ResourceRecordSet)
ret['result'] = res['result']
comments += [res['comment']]
if ret['result'] not in (True, None):
break
changes['old'] += [res['changes']['old']] if res['changes'].get('old') else []
changes['new'] += [res['changes']['new']] if res['changes'].get('new') else []
ret['changes'].update({'old': changes['old']}) if changes.get('old') else None
ret['changes'].update({'new': changes['new']}) if changes.get('new') else None
ret['comment'] = ' '.join(comments)
return ret
def distribution_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
distribution's status to Disabled, and once that returns success, to then
delete the resource. THIS CAN TAKE SOME TIME, so be patient :)
name (string)
Name of the state definition.
Name (string)
Name of the CloudFront distribution to be managed. If not provided, the
value of ``name`` will be used as a default. The purpose of this
parameter is only to resolve it to a Resource ID, so be aware that an
explicit value for ``Id`` below will override any value provided, or
defaulted, here.
Id (string)
The Resource ID of a CloudFront distribution to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure a distribution named my_distribution is gone:
boto_cloudfront.distribution_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
if not Id:
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, **authargs)
if res is None:
msg = 'Error dereferencing CloudFront distribution `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = ('Multiple CloudFront distibutions matched `{}`, no way to know which to'
' delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'CloudFront Distribution `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = res[0]['Id']
if not __salt__['boto_cloudfront.distribution_exists'](Id=Id, **authargs):
msg = 'CloudFront distribution `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_distribution_v2'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront distribution `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
currETag = old['ETag']
Enabled = old['DistributionConfig']['Enabled']
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be {}deleted.'.format(ref,
('disabled and ' if Enabled else ''))
ret['pchanges'] = {'old': old, 'new': None}
return ret
comments = []
if Enabled:
disabled = __salt__['boto_cloudfront.disable_distribution'](Id=Id, **authargs)
if disabled is None:
ret['result'] = False
msg = 'Error disabling CloudFront distribution `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
comments += ['CloudFront distribution `{}` disabled.'.format(ref)]
currETag = disabled['ETag']
deleted = __salt__['boto_cloudfront.delete_distribution'](Id=Id, IfMatch=currETag, **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront distribution `{}`'.format(ref)
comments += [msg]
log.error(msg)
ret['comment'] = ' '.join(comments)
return ret
msg = 'CloudFront distribution `{}` deleted.'.format(ref)
comments += [msg]
log.info(msg)
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': None}
return ret
def origin_access_identity_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity exists.
.. note::
Due to the unavailibity of ANY other way to store stateful idempotency
information about Origin Access Identities (including resource tags),
the Comment attribute (as the only user-settable attribute without
weird self-blocking semantics) is necessarily utilized to store the
Salt state signifier, which is used to determine resource existence and
state. That said, to enable SOME usability of this field, only the
value up to the first colon character is taken as the signifier, while
anything afterward is free-form and ignored by Salt.
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not provided, the value of
`name` will be used.
Comment
Free-form text description of the origin access identity.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_OAI:
boto_cloudfront.origin_access_identity_present:
- Comment: Simply ensures an OAI named my_OAI exists
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.get('Name', name)
# Munge Name into the Comment field...
Comment = '{}:{}'.format(Name, kwargs['Comment']) if kwargs.get('Comment') else Name
# Current state of the thing?
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront origin access identities matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
exists = bool(res)
if not exists:
CloudFrontOriginAccessIdentityConfig = {'Comment': Comment,
'CallerReference': str(uuid.uuid4())}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be created.'.format(Name)
new = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.create_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Failed to create CloudFront origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'Created CloudFrong origin access identity`{}`.'.format(Name)
ret['changes'] = {'old': None, 'new': res}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=currentId,
**authargs)
currentETag = current['ETag']
currentOAIC = current['CloudFrontOriginAccessIdentity']['CloudFrontOriginAccessIdentityConfig']
new = copy.deepcopy(currentOAIC)
new.update({'Comment': Comment}) # Currently the only updatable element :-/
if currentOAIC == new:
msg = 'CloudFront origin access identity `{}` is in the correct state.'.format(Name)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be updated.'.format(Name)
ret['pchanges'] = {'old': currentOAIC, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': new,
'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.update_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'CloudFront origin access identity `{}` config updated.'.format(Name)
ret['changes'] = {'old': currentOAIC, 'new': new}
return ret
def origin_access_identity_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity is absent.
name
The name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
Id (string)
The Resource ID of a CloudFront origin access identity to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure an origin access identity named my_OAI is gone:
boto_cloudfront.origin_access_identity_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
current = None
if not Id:
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, **authargs)
if current is None:
msg = 'Error dereferencing origin access identity `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(current) > 1:
msg = ('Multiple CloudFront origin access identities matched `{}`, no way to know'
' which to delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not current:
msg = 'CloudFront origin access identity `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = current[0]['Id']
if not __salt__['boto_cloudfront.cloud_front_origin_access_identity_exists'](Id=Id, **authargs):
msg = 'CloudFront origin access identity `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront origin access identity `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be deleted.'.format(ref)
ret['pchanges'] = {'old': old, 'new': None}
return ret
deleted = __salt__['boto_cloudfront.delete_cloud_front_origin_access_identity'](Id=Id,
IfMatch=old['ETag'], **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront origin access identity `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
msg = 'CloudFront origin access identity `{}` deleted.'.format(ref)
log.info(msg)
ret['comment'] = msg
ret['changes'] = {'old': old, 'new': None}
return ret
|
saltstack/salt | salt/states/boto_cloudfront.py | distribution_present | python | def distribution_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure the given CloudFront distribution exists in the described state.
The implementation of this function, and all those following, is orthagonal
to that of :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>`. Resources created with
:py:mod:`boto_cloudfront.present <salt.states.boto_cloudfront.present>`
will not be correctly managed by this function, as a different method is
used to store Salt's state signifier. This function and those following are
a suite, designed to work together. As an extra bonus, they correctly
process updates of the managed resources, so it is recommended to use them
in preference to :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>` above.
Note that the semantics of DistributionConfig (below) are rather arcane,
and vary wildly depending on whether the distribution already exists or not
(e.g. is being initially created, or being updated in place). Many more
details can be found here__.
.. __: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-overview-required-fields.html
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
DistributionConfig (dict)
Configuration for the distribution.
Notes:
- The CallerReference field should NOT be provided - it will be
autopopulated by Salt.
- A large number of sub- (and sub-sub-) fields require a ``Quantity``
element, which simply COUNTS the number of items in the ``Items``
element. This is bluntly stupid, so as a convenience, Salt will
traverse the provided configuration, and add (or fix) a ``Quantity``
element for any ``Items`` elements of list-type it encounters. This
adds a bit of sanity to an otherwise error-prone situation. Note
that for this to work, zero-length lists must be inlined as ``[]``.
- Due to the unavailibity of a better way to store stateful idempotency
information about Distributions, the Comment sub-element (as the only
user-settable attribute without weird self-blocking semantics, and
which is available from the core ``get_distribution()`` API call) is
utilized to store the Salt state signifier, which is used to
determine resource existence and state. That said, to enable **some**
usability of this field, only the value up to the first colon
character is taken as the signifier, with everything afterward
free-form, and ignored (but preserved) by Salt.
Tags (dict)
Tags to associate with the distribution.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
plt-dev-spaapi-cf-dist-cf_dist-present:
boto_cloudfront.distribution_present:
- Name: plt-dev-spaapi-cf-dist
- DistributionConfig:
Comment: SPA
Logging:
Enabled: false
Prefix: ''
Bucket: ''
IncludeCookies: false
WebACLId: ''
Origins:
Items:
- S3OriginConfig:
OriginAccessIdentity: the-SPA-OAI
OriginPath: ''
CustomHeaders:
Items: []
Id: S3-hs-backend-srpms
DomainName: hs-backend-srpms.s3.amazonaws.com
PriceClass: PriceClass_All
DefaultRootObject: ''
Enabled: true
DefaultCacheBehavior:
ViewerProtocolPolicy: allow-all
TrustedSigners:
Items: []
Enabled: false
SmoothStreaming: false
TargetOriginId: S3-hs-backend-srpms
FieldLevelEncryptionId: ''
ForwardedValues:
Headers:
Items: []
Cookies:
Forward: none
QueryStringCacheKeys:
Items: []
QueryString: false
MaxTTL: 31536000
LambdaFunctionAssociations:
Items: []
DefaultTTL: 86400
AllowedMethods:
CachedMethods:
Items:
- HEAD
- GET
Items:
- HEAD
- GET
MinTTL: 0
Compress: false
IsIPV6Enabled: true
ViewerCertificate:
CloudFrontDefaultCertificate: true
MinimumProtocolVersion: TLSv1
CertificateSource: cloudfront
Aliases:
Items:
- bubba-hotep.bodhi-dev.io
HttpVersion: http2
- Tags:
Owner: dev_engrs
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.pop('Name', name)
Tags = kwargs.pop('Tags', None)
DistributionConfig = kwargs.get('DistributionConfig', {})
## Sub-element munging on config data should go in here, before we proceed:
# For instance, origin access identities must be of the form
# `origin-access-identity/cloudfront/ID-of-origin-access-identity`, but we can't really
# know that ID apriori, so any OAI state names inside the config data must be resolved
# and converted into that format before submission. Be aware that the `state names` of
# salt managed OAIs are stored in their Comment fields for lack of any better place...
for item in range(len(DistributionConfig.get('Origins', {}).get('Items', []))):
oai = DistributionConfig['Origins']['Items'][item].get('S3OriginConfig',
{}).get('OriginAccessIdentity', '')
if oai and not oai.startswith('origin-access-identity/cloudfront/'):
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=oai, region=region, key=key, keyid=keyid, profile=profile)
if res is None: # An error occurred, bubble it up...
log.warning('Error encountered while trying to determine the Resource ID of'
' CloudFront origin access identity `%s`. Passing as-is.', oai)
elif not res:
log.warning('Failed to determine the Resource ID of CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
elif len(res) > 1:
log.warning('Failed to find unique Resource ID for CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
else:
# One unique OAI resource found -- deref and replace it...
new = 'origin-access-identity/cloudfront/{}'.format(res[0]['Id'])
DistributionConfig['Origins']['Items'][item]['S3OriginConfig']['OriginAccessIdentity'] = new
# Munge Name into the Comment field...
DistributionConfig['Comment'] = '{}:{}'.format(Name, DistributionConfig['Comment']) \
if DistributionConfig.get('Comment') else Name
# Fix up any missing (or wrong) Quantity sub-elements...
DistributionConfig = _fix_quantities(DistributionConfig)
kwargs['DistributionConfig'] = DistributionConfig
# Current state of the thing?
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, region=region,
key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
# Luckily, the `DistributionConfig` structure returned by `get_distribution()` (as a sub-
# element of `Distribution`) is identical to that returned by `get_distribution_config(),
# and as a bonus, the ETag's are ALSO compatible...
# Since "updates" are actually "replace everything from scratch" events, this implies that
# it's enough to simply determine SOME update is necessary to trigger one, rather than
# exhaustively calculating all changes needed - this makes life MUCH EASIER :)
# Thus our workflow here is:
# - check if the distribution exists
# - if it doesn't, create it fresh with the requested DistributionConfig, and Tag it if needed
# - if it does, grab its ETag, and TWO copies of the current DistributionConfig
# - merge the requested DistributionConfig on top of one of them
# - compare the copy we just merged against the one we didn't
# - if they differ, send the merged copy, along with the ETag we got, back as an update
# - lastly, verify and set/unset any Tags which may need changing...
exists = bool(res)
if not exists:
if 'CallerReference' not in kwargs['DistributionConfig']:
kwargs['DistributionConfig']['CallerReference'] = str(uuid.uuid4())
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be created.'.format(Name)
new = {'DistributionConfig': kwargs['DistributionConfig']}
new.update({'Tags': Tags}) if Tags else None
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs.update(authargs)
comments = []
res = __salt__['boto_cloudfront.create_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while creating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
new = {'DistributionConfig': res['Distribution']['DistributionConfig']}
comments += ['Created distribution `{}`.'.format(Name)]
newARN = res.get('Distribution', {}).get('ARN')
tagged = __salt__['boto_cloudfront.tag_resource'](Tags=Tags, **authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while tagging distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['Tagged distribution `{}`.'.format(Name)]
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': None, 'new': new}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_distribution_v2'](Id=currentId, **authargs)
# Insanely unlikely given that we JUST got back this Id from the previous search, but....
if not current:
msg = 'Failed to lookup CloudFront distribution with Id `{}`.'.format(currentId)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
currentDC = current['Distribution']['DistributionConfig']
currentARN = current['Distribution']['ARN']
currentETag = current['ETag']
currentTags = __salt__['boto_cloudfront.list_tags_for_resource'](Resource=currentARN,
**authargs)
copyOne = copy.deepcopy(currentDC)
copyTwo = copy.deepcopy(currentDC)
copyTwo.update(kwargs['DistributionConfig'])
correct = __utils__['boto3.json_objs_equal'](copyOne, copyTwo)
tags_correct = (currentTags == Tags)
comments = []
old = {}
new = {}
if correct and tags_correct:
ret['comment'] = 'CloudFront distribution `{}` is in the correct state.'.format(Name)
return ret
if __opts__['test']:
ret['result'] = None
if not correct:
comments += ['CloudFront distribution `{}` config would be updated.'.format(Name)]
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = copyTwo
if not tags_correct:
comments += ['CloudFront distribution `{}` Tags would be updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['pchanges'] = {'old': old, 'new': new}
return ret
if not correct:
kwargs = {'DistributionConfig': copyTwo, 'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
log.debug('Calling `boto_cloudfront.update_distribution_v2()` with **kwargs =='
' %s', kwargs)
res = __salt__['boto_cloudfront.update_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = res['Distribution']['DistributionConfig']
comments += ['CloudFront distribution `{}` config updated.'.format(Name)]
if not tags_correct:
tagged = __salt__['boto_cloudfront.enforce_tags'](Resource=currentARN, Tags=Tags,
**authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while updating Tags on distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['CloudFront distribution `{}` Tags updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': new}
return ret | Ensure the given CloudFront distribution exists in the described state.
The implementation of this function, and all those following, is orthagonal
to that of :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>`. Resources created with
:py:mod:`boto_cloudfront.present <salt.states.boto_cloudfront.present>`
will not be correctly managed by this function, as a different method is
used to store Salt's state signifier. This function and those following are
a suite, designed to work together. As an extra bonus, they correctly
process updates of the managed resources, so it is recommended to use them
in preference to :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>` above.
Note that the semantics of DistributionConfig (below) are rather arcane,
and vary wildly depending on whether the distribution already exists or not
(e.g. is being initially created, or being updated in place). Many more
details can be found here__.
.. __: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-overview-required-fields.html
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
DistributionConfig (dict)
Configuration for the distribution.
Notes:
- The CallerReference field should NOT be provided - it will be
autopopulated by Salt.
- A large number of sub- (and sub-sub-) fields require a ``Quantity``
element, which simply COUNTS the number of items in the ``Items``
element. This is bluntly stupid, so as a convenience, Salt will
traverse the provided configuration, and add (or fix) a ``Quantity``
element for any ``Items`` elements of list-type it encounters. This
adds a bit of sanity to an otherwise error-prone situation. Note
that for this to work, zero-length lists must be inlined as ``[]``.
- Due to the unavailibity of a better way to store stateful idempotency
information about Distributions, the Comment sub-element (as the only
user-settable attribute without weird self-blocking semantics, and
which is available from the core ``get_distribution()`` API call) is
utilized to store the Salt state signifier, which is used to
determine resource existence and state. That said, to enable **some**
usability of this field, only the value up to the first colon
character is taken as the signifier, with everything afterward
free-form, and ignored (but preserved) by Salt.
Tags (dict)
Tags to associate with the distribution.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
plt-dev-spaapi-cf-dist-cf_dist-present:
boto_cloudfront.distribution_present:
- Name: plt-dev-spaapi-cf-dist
- DistributionConfig:
Comment: SPA
Logging:
Enabled: false
Prefix: ''
Bucket: ''
IncludeCookies: false
WebACLId: ''
Origins:
Items:
- S3OriginConfig:
OriginAccessIdentity: the-SPA-OAI
OriginPath: ''
CustomHeaders:
Items: []
Id: S3-hs-backend-srpms
DomainName: hs-backend-srpms.s3.amazonaws.com
PriceClass: PriceClass_All
DefaultRootObject: ''
Enabled: true
DefaultCacheBehavior:
ViewerProtocolPolicy: allow-all
TrustedSigners:
Items: []
Enabled: false
SmoothStreaming: false
TargetOriginId: S3-hs-backend-srpms
FieldLevelEncryptionId: ''
ForwardedValues:
Headers:
Items: []
Cookies:
Forward: none
QueryStringCacheKeys:
Items: []
QueryString: false
MaxTTL: 31536000
LambdaFunctionAssociations:
Items: []
DefaultTTL: 86400
AllowedMethods:
CachedMethods:
Items:
- HEAD
- GET
Items:
- HEAD
- GET
MinTTL: 0
Compress: false
IsIPV6Enabled: true
ViewerCertificate:
CloudFrontDefaultCertificate: true
MinimumProtocolVersion: TLSv1
CertificateSource: cloudfront
Aliases:
Items:
- bubba-hotep.bodhi-dev.io
HttpVersion: http2
- Tags:
Owner: dev_engrs | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudfront.py#L259-L575 | [
"def _fix_quantities(tree):\n '''\n Stupidly simple function to fix any Items/Quantity disparities inside a\n DistributionConfig block before use. Since AWS only accepts JSON-encodable\n data types, this implementation is \"good enough\" for our purposes.\n '''\n if isinstance(tree, dict):\n tree = {k: _fix_quantities(v) for k, v in tree.items()}\n if isinstance(tree.get('Items'), list):\n tree['Quantity'] = len(tree['Items'])\n if not tree['Items']:\n tree.pop('Items') # Silly, but AWS requires it....\n return tree\n elif isinstance(tree, list):\n return [_fix_quantities(t) for t in tree]\n else:\n return tree\n"
] | # -*- coding: utf-8 -*-
'''
Manage CloudFront distributions
.. versionadded:: 2018.3.0
Create, update and destroy CloudFront distributions.
This module accepts explicit AWS credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API
and no further configuration is necessary.
More information available `here
<https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them,
either in a pillar file or in the minion's config file:
.. code-block:: yaml
cloudfront.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudfront.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid``, and ``region`` via a profile,
either passed in as a dict, or a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
aws:
region:
us-east-1:
profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import uuid
import copy
import json
# Import Salt conveniences
from salt.ext import six
from salt.ext.six.moves import range
#pylint: disable=W0106
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
if 'boto_cloudfront.get_distribution' not in __salt__:
msg = 'The boto_cloudfront state module could not be loaded: {}.'
return (False, msg.format('boto_cloudfront exec module unavailable.'))
return 'boto_cloudfront'
def present(
name,
config,
tags,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the CloudFront distribution is present.
name (string)
Name of the CloudFront distribution
config (dict)
Configuration for the distribution
tags (dict)
Tags to associate with the distribution
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
Example:
.. code-block:: yaml
Manage my_distribution CloudFront distribution:
boto_cloudfront.present:
- name: my_distribution
- config:
Comment: 'partial config shown, most parameters elided'
Enabled: True
- tags:
testing_key: testing_value
'''
ret = {
'name': name,
'comment': '',
'changes': {},
}
res = __salt__['boto_cloudfront.get_distribution'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error checking distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
old = res['result']
if old is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Distribution {0} set for creation.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
res = __salt__['boto_cloudfront.create_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error creating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Created distribution {0}.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
else:
full_config_old = {
'config': old['distribution']['DistributionConfig'],
'tags': old['tags'],
}
full_config_new = {
'config': config,
'tags': tags,
}
diffed_config = __utils__['dictdiffer.deep_diff'](
full_config_old,
full_config_new,
)
def _yaml_safe_dump(attrs):
'''
Safely dump YAML using a readable flow style
'''
dumper_name = 'IndentedSafeOrderedDumper'
dumper = __utils__['yaml.get_dumper'](dumper_name)
return __utils__['yaml.dump'](
attrs,
default_flow_style=False,
Dumper=dumper)
changes_diff = ''.join(difflib.unified_diff(
_yaml_safe_dump(full_config_old).splitlines(True),
_yaml_safe_dump(full_config_new).splitlines(True),
))
any_changes = bool('old' in diffed_config or 'new' in diffed_config)
if not any_changes:
ret['result'] = True
ret['comment'] = 'Distribution {0} has correct config.'.format(
name,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join([
'Distribution {0} set for new config:'.format(name),
changes_diff,
])
ret['changes'] = {'diff': changes_diff}
return ret
res = __salt__['boto_cloudfront.update_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error updating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Updated distribution {0}.'.format(name)
ret['changes'] = {'diff': changes_diff}
return ret
def _fix_quantities(tree):
'''
Stupidly simple function to fix any Items/Quantity disparities inside a
DistributionConfig block before use. Since AWS only accepts JSON-encodable
data types, this implementation is "good enough" for our purposes.
'''
if isinstance(tree, dict):
tree = {k: _fix_quantities(v) for k, v in tree.items()}
if isinstance(tree.get('Items'), list):
tree['Quantity'] = len(tree['Items'])
if not tree['Items']:
tree.pop('Items') # Silly, but AWS requires it....
return tree
elif isinstance(tree, list):
return [_fix_quantities(t) for t in tree]
else:
return tree
def oai_bucket_policy_present(name, Bucket, OAI, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the given policy exists on an S3 bucket, granting access for the given origin access
identity to do the things specified in the policy.
name
The name of the state definition
Bucket
The S3 bucket which CloudFront needs access to. Note that this policy
is exclusive - it will be the only policy definition on the bucket (and
objects inside the bucket if you specify such permissions in the
policy). Note that this likely SHOULD reflect the bucket mentioned in
the Resource section of the Policy, but this is not enforced...
OAI
The value of `Name` passed to the state definition for the origin
access identity which will be accessing the bucket.
Policy
The full policy document which should be set on the S3 bucket. If a
``Principal`` clause is not provided in the policy, one will be
automatically added, and pointed at the correct value as dereferenced
from the OAI provided above. If one IS provided, then this is not
done, and you are responsible for providing the correct values.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_oai_s3_policy:
boto_cloudfront.oai_bucket_policy_present:
- Bucket: the_bucket_for_my_distribution
- OAI: the_OAI_I_just_created_and_attached_to_my_distribution
- Policy:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::the_bucket_for_my_distribution/*
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
oais = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=OAI, region=region, key=key, keyid=keyid, profile=profile)
if len(oais) > 1:
msg = 'Multiple origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not oais:
msg = 'No origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
canonical_user = oais[0].get('S3CanonicalUserId')
oai_id = oais[0].get('Id')
if isinstance(Policy, six.string_types):
Policy = json.loads(Policy)
for stanza in range(len(Policy.get('Statement', []))):
if 'Principal' not in Policy['Statement'][stanza]:
Policy['Statement'][stanza]['Principal'] = {"CanonicalUser": canonical_user}
bucket = __salt__['boto_s3_bucket.describe'](Bucket=Bucket, region=region, key=key,
keyid=keyid, profile=profile)
if not bucket or 'bucket' not in bucket:
msg = 'S3 bucket `{}` not found.'.format(Bucket)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
curr_policy = bucket['bucket'].get('Policy', {}).get('Policy', {}) # ?!? dunno, that's just how it gets returned...
curr_policy = json.loads(curr_policy) if isinstance(curr_policy,
six.string_types) else curr_policy
# Sooooo, you have to SUBMIT Principals of the form
# Principal: {'S3CanonicalUserId': someCrazyLongMagicValueAsDerivedAbove}
# BUT, they RETURN the Principal as something WILDLY different
# Principal: {'AWS': arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E30ABCDEF12345}
# which obviously compare different on every run... So we fake it thusly.
fake_Policy = copy.deepcopy(Policy)
for stanza in range(len(fake_Policy.get('Statement', []))):
# Warning: unavoidable hardcoded magic values HO!
fake_Policy['Statement'][stanza].update({'Principal': {'AWS':
'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity {}'.format(oai_id)}})
if __utils__['boto3.json_objs_equal'](curr_policy, fake_Policy):
msg = 'Policy of S3 bucket `{}` is in the correct state.'.format(Bucket)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['comment'] = 'Policy on S3 bucket `{}` would be updated.'.format(Bucket)
ret['result'] = None
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
res = __salt__['boto_s3_bucket.put_policy'](Bucket=Bucket, Policy=Policy,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in res:
ret['comment'] = 'Failed to update policy on S3 bucket `{}`: {}'.format(Bucket,
res['error'])
ret['return'] = False
return ret
ret['comment'] = 'Policy on S3 bucket `{}` updated.'.format(Bucket)
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
def route53_alias_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a Route53 Alias exists and is pointing at the given CloudFront
distribution. An ``A`` record is always created, and if IPV6 is enabled on
the given distribution, an ``AAAA`` record will be created as well. Also be
aware that Alias records for CloudFront distributions are only permitted in
non-private zones.
name
The name of the state definition.
Distribution
The name of the CloudFront distribution. Defaults to the value of
``name`` if not provided.
HostedZoneId
Id of the Route53 hosted zone within which the records should be created.
DomainName
The domain name associated with the Hosted Zone. Exclusive with HostedZoneId.
ResourceRecordSet
A Route53 Record Set (with AliasTarget section, suitable for use as an
``Alias`` record, if non-default settings are needed on the Alias)
which should be pointed at the provided CloudFront distribution. Note
that this MUST correlate with the Aliases set within the
DistributionConfig section of the distribution.
Some notes *specifically* about the ``AliasTarget`` subsection of the
ResourceRecordSet:
- If not specified, the ``DNSName`` sub-field will be populated by
dereferencing ``Distribution`` above to the value of its
``DomainName`` attribute.
- The HostedZoneId sub-field should not be provided -- it will be
automatically populated with a ``magic`` AWS value.
- The EvaluateTargetHealth can only be False on a CloudFront Alias.
- The above items taken all together imply that, for most use-cases,
the AliasTarget sub-section can be entirely omitted, as seen in the
first code sample below.
Lastly, note that if you set ``name`` to the desired ResourceRecordSet
Name, you can entirely omit this parameter, as shown in the second
example below.
.. code-block:: yaml
Add a Route53 Alias for my_distribution:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
- ResourceRecordSet:
Name: the-alias.saltstack.org.
# This is even simpler - it uses the value of `name` for ResourceRecordSet.Name
another-alias.saltstack.org.:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
'''
MAGIC_CLOUDFRONT_HOSTED_ZONEID = 'Z2FDTNDATAQYW2'
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
Distribution = kwargs['Distribution'] if 'Distribution' in kwargs else name
ResourceRecordSet = kwargs.get('ResourceRecordSet', {})
Name = ResourceRecordSet.get('Name', name)
ResourceRecordSet['Name'] = Name
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Distribution,
region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error resolving CloudFront distribution `{}` to a Resource ID.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'No CloudFront distibutions matching `{}` found.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
dist = res[0]
Types = ('A', 'AAAA') if dist.get('IsIPV6Enabled', False) else ('A',)
DNSName = dist.get('DomainName', '')
Aliases = dist.get('Aliases', {}).get('Items', [])
# AWS annoyance #437:
# Route53 "FQDNs" (correctly!) REQUIRE trailing periods...
# while CloudFront "FQDNs" don't PERMIT trailing periods...
Aliases += [(a if a.endswith('.') else '{}.'.format(a)) for a in Aliases]
if Name not in Aliases:
msg = ('Route53 alias `{}` requested which is not mirrored in the `Aliases`'
' sub-section of the DistributionConfig.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
changes = {'old': [], 'new': []}
comments = []
# Now mock out a route53 state def, and use the route53 rr_exists state to enforce it...
AliasTarget = ResourceRecordSet.get('AliasTarget', {})
AliasTarget['DNSName'] = AliasTarget['DNSName'] if 'DNSName' in AliasTarget else DNSName
AliasTarget['DNSName'] += '' if AliasTarget['DNSName'].endswith('.') else '.' # GRRRR!
AliasTarget['HostedZoneId'] = MAGIC_CLOUDFRONT_HOSTED_ZONEID
AliasTarget['EvaluateTargetHealth'] = False # Route53 limitation
ResourceRecordSet['name'] = Name
ResourceRecordSet['AliasTarget'] = AliasTarget
ResourceRecordSet['PrivateZone'] = False # Route53 limitation
ResourceRecordSet['DomainName'] = kwargs.get('DomainName')
ResourceRecordSet['HostedZoneId'] = kwargs.get('HostedZoneId')
ResourceRecordSet.update({'region': region, 'key': key, 'keyid': keyid, 'profile': profile})
for Type in Types:
ResourceRecordSet['Type'] = Type
# Checking for `test=True` will occur in the called state....
log.debug('Calling state function `boto3_route53.rr_present()` with args: `%s`',
ResourceRecordSet)
res = __states__['boto3_route53.rr_present'](**ResourceRecordSet)
ret['result'] = res['result']
comments += [res['comment']]
if ret['result'] not in (True, None):
break
changes['old'] += [res['changes']['old']] if res['changes'].get('old') else []
changes['new'] += [res['changes']['new']] if res['changes'].get('new') else []
ret['changes'].update({'old': changes['old']}) if changes.get('old') else None
ret['changes'].update({'new': changes['new']}) if changes.get('new') else None
ret['comment'] = ' '.join(comments)
return ret
def distribution_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
distribution's status to Disabled, and once that returns success, to then
delete the resource. THIS CAN TAKE SOME TIME, so be patient :)
name (string)
Name of the state definition.
Name (string)
Name of the CloudFront distribution to be managed. If not provided, the
value of ``name`` will be used as a default. The purpose of this
parameter is only to resolve it to a Resource ID, so be aware that an
explicit value for ``Id`` below will override any value provided, or
defaulted, here.
Id (string)
The Resource ID of a CloudFront distribution to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure a distribution named my_distribution is gone:
boto_cloudfront.distribution_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
if not Id:
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, **authargs)
if res is None:
msg = 'Error dereferencing CloudFront distribution `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = ('Multiple CloudFront distibutions matched `{}`, no way to know which to'
' delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'CloudFront Distribution `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = res[0]['Id']
if not __salt__['boto_cloudfront.distribution_exists'](Id=Id, **authargs):
msg = 'CloudFront distribution `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_distribution_v2'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront distribution `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
currETag = old['ETag']
Enabled = old['DistributionConfig']['Enabled']
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be {}deleted.'.format(ref,
('disabled and ' if Enabled else ''))
ret['pchanges'] = {'old': old, 'new': None}
return ret
comments = []
if Enabled:
disabled = __salt__['boto_cloudfront.disable_distribution'](Id=Id, **authargs)
if disabled is None:
ret['result'] = False
msg = 'Error disabling CloudFront distribution `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
comments += ['CloudFront distribution `{}` disabled.'.format(ref)]
currETag = disabled['ETag']
deleted = __salt__['boto_cloudfront.delete_distribution'](Id=Id, IfMatch=currETag, **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront distribution `{}`'.format(ref)
comments += [msg]
log.error(msg)
ret['comment'] = ' '.join(comments)
return ret
msg = 'CloudFront distribution `{}` deleted.'.format(ref)
comments += [msg]
log.info(msg)
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': None}
return ret
def origin_access_identity_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity exists.
.. note::
Due to the unavailibity of ANY other way to store stateful idempotency
information about Origin Access Identities (including resource tags),
the Comment attribute (as the only user-settable attribute without
weird self-blocking semantics) is necessarily utilized to store the
Salt state signifier, which is used to determine resource existence and
state. That said, to enable SOME usability of this field, only the
value up to the first colon character is taken as the signifier, while
anything afterward is free-form and ignored by Salt.
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not provided, the value of
`name` will be used.
Comment
Free-form text description of the origin access identity.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_OAI:
boto_cloudfront.origin_access_identity_present:
- Comment: Simply ensures an OAI named my_OAI exists
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.get('Name', name)
# Munge Name into the Comment field...
Comment = '{}:{}'.format(Name, kwargs['Comment']) if kwargs.get('Comment') else Name
# Current state of the thing?
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront origin access identities matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
exists = bool(res)
if not exists:
CloudFrontOriginAccessIdentityConfig = {'Comment': Comment,
'CallerReference': str(uuid.uuid4())}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be created.'.format(Name)
new = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.create_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Failed to create CloudFront origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'Created CloudFrong origin access identity`{}`.'.format(Name)
ret['changes'] = {'old': None, 'new': res}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=currentId,
**authargs)
currentETag = current['ETag']
currentOAIC = current['CloudFrontOriginAccessIdentity']['CloudFrontOriginAccessIdentityConfig']
new = copy.deepcopy(currentOAIC)
new.update({'Comment': Comment}) # Currently the only updatable element :-/
if currentOAIC == new:
msg = 'CloudFront origin access identity `{}` is in the correct state.'.format(Name)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be updated.'.format(Name)
ret['pchanges'] = {'old': currentOAIC, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': new,
'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.update_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'CloudFront origin access identity `{}` config updated.'.format(Name)
ret['changes'] = {'old': currentOAIC, 'new': new}
return ret
def origin_access_identity_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity is absent.
name
The name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
Id (string)
The Resource ID of a CloudFront origin access identity to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure an origin access identity named my_OAI is gone:
boto_cloudfront.origin_access_identity_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
current = None
if not Id:
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, **authargs)
if current is None:
msg = 'Error dereferencing origin access identity `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(current) > 1:
msg = ('Multiple CloudFront origin access identities matched `{}`, no way to know'
' which to delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not current:
msg = 'CloudFront origin access identity `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = current[0]['Id']
if not __salt__['boto_cloudfront.cloud_front_origin_access_identity_exists'](Id=Id, **authargs):
msg = 'CloudFront origin access identity `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront origin access identity `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be deleted.'.format(ref)
ret['pchanges'] = {'old': old, 'new': None}
return ret
deleted = __salt__['boto_cloudfront.delete_cloud_front_origin_access_identity'](Id=Id,
IfMatch=old['ETag'], **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront origin access identity `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
msg = 'CloudFront origin access identity `{}` deleted.'.format(ref)
log.info(msg)
ret['comment'] = msg
ret['changes'] = {'old': old, 'new': None}
return ret
|
saltstack/salt | salt/states/boto_cloudfront.py | oai_bucket_policy_present | python | def oai_bucket_policy_present(name, Bucket, OAI, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the given policy exists on an S3 bucket, granting access for the given origin access
identity to do the things specified in the policy.
name
The name of the state definition
Bucket
The S3 bucket which CloudFront needs access to. Note that this policy
is exclusive - it will be the only policy definition on the bucket (and
objects inside the bucket if you specify such permissions in the
policy). Note that this likely SHOULD reflect the bucket mentioned in
the Resource section of the Policy, but this is not enforced...
OAI
The value of `Name` passed to the state definition for the origin
access identity which will be accessing the bucket.
Policy
The full policy document which should be set on the S3 bucket. If a
``Principal`` clause is not provided in the policy, one will be
automatically added, and pointed at the correct value as dereferenced
from the OAI provided above. If one IS provided, then this is not
done, and you are responsible for providing the correct values.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_oai_s3_policy:
boto_cloudfront.oai_bucket_policy_present:
- Bucket: the_bucket_for_my_distribution
- OAI: the_OAI_I_just_created_and_attached_to_my_distribution
- Policy:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::the_bucket_for_my_distribution/*
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
oais = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=OAI, region=region, key=key, keyid=keyid, profile=profile)
if len(oais) > 1:
msg = 'Multiple origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not oais:
msg = 'No origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
canonical_user = oais[0].get('S3CanonicalUserId')
oai_id = oais[0].get('Id')
if isinstance(Policy, six.string_types):
Policy = json.loads(Policy)
for stanza in range(len(Policy.get('Statement', []))):
if 'Principal' not in Policy['Statement'][stanza]:
Policy['Statement'][stanza]['Principal'] = {"CanonicalUser": canonical_user}
bucket = __salt__['boto_s3_bucket.describe'](Bucket=Bucket, region=region, key=key,
keyid=keyid, profile=profile)
if not bucket or 'bucket' not in bucket:
msg = 'S3 bucket `{}` not found.'.format(Bucket)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
curr_policy = bucket['bucket'].get('Policy', {}).get('Policy', {}) # ?!? dunno, that's just how it gets returned...
curr_policy = json.loads(curr_policy) if isinstance(curr_policy,
six.string_types) else curr_policy
# Sooooo, you have to SUBMIT Principals of the form
# Principal: {'S3CanonicalUserId': someCrazyLongMagicValueAsDerivedAbove}
# BUT, they RETURN the Principal as something WILDLY different
# Principal: {'AWS': arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E30ABCDEF12345}
# which obviously compare different on every run... So we fake it thusly.
fake_Policy = copy.deepcopy(Policy)
for stanza in range(len(fake_Policy.get('Statement', []))):
# Warning: unavoidable hardcoded magic values HO!
fake_Policy['Statement'][stanza].update({'Principal': {'AWS':
'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity {}'.format(oai_id)}})
if __utils__['boto3.json_objs_equal'](curr_policy, fake_Policy):
msg = 'Policy of S3 bucket `{}` is in the correct state.'.format(Bucket)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['comment'] = 'Policy on S3 bucket `{}` would be updated.'.format(Bucket)
ret['result'] = None
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
res = __salt__['boto_s3_bucket.put_policy'](Bucket=Bucket, Policy=Policy,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in res:
ret['comment'] = 'Failed to update policy on S3 bucket `{}`: {}'.format(Bucket,
res['error'])
ret['return'] = False
return ret
ret['comment'] = 'Policy on S3 bucket `{}` updated.'.format(Bucket)
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret | Ensure the given policy exists on an S3 bucket, granting access for the given origin access
identity to do the things specified in the policy.
name
The name of the state definition
Bucket
The S3 bucket which CloudFront needs access to. Note that this policy
is exclusive - it will be the only policy definition on the bucket (and
objects inside the bucket if you specify such permissions in the
policy). Note that this likely SHOULD reflect the bucket mentioned in
the Resource section of the Policy, but this is not enforced...
OAI
The value of `Name` passed to the state definition for the origin
access identity which will be accessing the bucket.
Policy
The full policy document which should be set on the S3 bucket. If a
``Principal`` clause is not provided in the policy, one will be
automatically added, and pointed at the correct value as dereferenced
from the OAI provided above. If one IS provided, then this is not
done, and you are responsible for providing the correct values.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_oai_s3_policy:
boto_cloudfront.oai_bucket_policy_present:
- Bucket: the_bucket_for_my_distribution
- OAI: the_OAI_I_just_created_and_attached_to_my_distribution
- Policy:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::the_bucket_for_my_distribution/* | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudfront.py#L578-L695 | null | # -*- coding: utf-8 -*-
'''
Manage CloudFront distributions
.. versionadded:: 2018.3.0
Create, update and destroy CloudFront distributions.
This module accepts explicit AWS credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API
and no further configuration is necessary.
More information available `here
<https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them,
either in a pillar file or in the minion's config file:
.. code-block:: yaml
cloudfront.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudfront.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid``, and ``region`` via a profile,
either passed in as a dict, or a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
aws:
region:
us-east-1:
profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import uuid
import copy
import json
# Import Salt conveniences
from salt.ext import six
from salt.ext.six.moves import range
#pylint: disable=W0106
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
if 'boto_cloudfront.get_distribution' not in __salt__:
msg = 'The boto_cloudfront state module could not be loaded: {}.'
return (False, msg.format('boto_cloudfront exec module unavailable.'))
return 'boto_cloudfront'
def present(
name,
config,
tags,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the CloudFront distribution is present.
name (string)
Name of the CloudFront distribution
config (dict)
Configuration for the distribution
tags (dict)
Tags to associate with the distribution
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
Example:
.. code-block:: yaml
Manage my_distribution CloudFront distribution:
boto_cloudfront.present:
- name: my_distribution
- config:
Comment: 'partial config shown, most parameters elided'
Enabled: True
- tags:
testing_key: testing_value
'''
ret = {
'name': name,
'comment': '',
'changes': {},
}
res = __salt__['boto_cloudfront.get_distribution'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error checking distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
old = res['result']
if old is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Distribution {0} set for creation.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
res = __salt__['boto_cloudfront.create_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error creating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Created distribution {0}.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
else:
full_config_old = {
'config': old['distribution']['DistributionConfig'],
'tags': old['tags'],
}
full_config_new = {
'config': config,
'tags': tags,
}
diffed_config = __utils__['dictdiffer.deep_diff'](
full_config_old,
full_config_new,
)
def _yaml_safe_dump(attrs):
'''
Safely dump YAML using a readable flow style
'''
dumper_name = 'IndentedSafeOrderedDumper'
dumper = __utils__['yaml.get_dumper'](dumper_name)
return __utils__['yaml.dump'](
attrs,
default_flow_style=False,
Dumper=dumper)
changes_diff = ''.join(difflib.unified_diff(
_yaml_safe_dump(full_config_old).splitlines(True),
_yaml_safe_dump(full_config_new).splitlines(True),
))
any_changes = bool('old' in diffed_config or 'new' in diffed_config)
if not any_changes:
ret['result'] = True
ret['comment'] = 'Distribution {0} has correct config.'.format(
name,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join([
'Distribution {0} set for new config:'.format(name),
changes_diff,
])
ret['changes'] = {'diff': changes_diff}
return ret
res = __salt__['boto_cloudfront.update_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error updating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Updated distribution {0}.'.format(name)
ret['changes'] = {'diff': changes_diff}
return ret
def _fix_quantities(tree):
'''
Stupidly simple function to fix any Items/Quantity disparities inside a
DistributionConfig block before use. Since AWS only accepts JSON-encodable
data types, this implementation is "good enough" for our purposes.
'''
if isinstance(tree, dict):
tree = {k: _fix_quantities(v) for k, v in tree.items()}
if isinstance(tree.get('Items'), list):
tree['Quantity'] = len(tree['Items'])
if not tree['Items']:
tree.pop('Items') # Silly, but AWS requires it....
return tree
elif isinstance(tree, list):
return [_fix_quantities(t) for t in tree]
else:
return tree
def distribution_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure the given CloudFront distribution exists in the described state.
The implementation of this function, and all those following, is orthagonal
to that of :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>`. Resources created with
:py:mod:`boto_cloudfront.present <salt.states.boto_cloudfront.present>`
will not be correctly managed by this function, as a different method is
used to store Salt's state signifier. This function and those following are
a suite, designed to work together. As an extra bonus, they correctly
process updates of the managed resources, so it is recommended to use them
in preference to :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>` above.
Note that the semantics of DistributionConfig (below) are rather arcane,
and vary wildly depending on whether the distribution already exists or not
(e.g. is being initially created, or being updated in place). Many more
details can be found here__.
.. __: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-overview-required-fields.html
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
DistributionConfig (dict)
Configuration for the distribution.
Notes:
- The CallerReference field should NOT be provided - it will be
autopopulated by Salt.
- A large number of sub- (and sub-sub-) fields require a ``Quantity``
element, which simply COUNTS the number of items in the ``Items``
element. This is bluntly stupid, so as a convenience, Salt will
traverse the provided configuration, and add (or fix) a ``Quantity``
element for any ``Items`` elements of list-type it encounters. This
adds a bit of sanity to an otherwise error-prone situation. Note
that for this to work, zero-length lists must be inlined as ``[]``.
- Due to the unavailibity of a better way to store stateful idempotency
information about Distributions, the Comment sub-element (as the only
user-settable attribute without weird self-blocking semantics, and
which is available from the core ``get_distribution()`` API call) is
utilized to store the Salt state signifier, which is used to
determine resource existence and state. That said, to enable **some**
usability of this field, only the value up to the first colon
character is taken as the signifier, with everything afterward
free-form, and ignored (but preserved) by Salt.
Tags (dict)
Tags to associate with the distribution.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
plt-dev-spaapi-cf-dist-cf_dist-present:
boto_cloudfront.distribution_present:
- Name: plt-dev-spaapi-cf-dist
- DistributionConfig:
Comment: SPA
Logging:
Enabled: false
Prefix: ''
Bucket: ''
IncludeCookies: false
WebACLId: ''
Origins:
Items:
- S3OriginConfig:
OriginAccessIdentity: the-SPA-OAI
OriginPath: ''
CustomHeaders:
Items: []
Id: S3-hs-backend-srpms
DomainName: hs-backend-srpms.s3.amazonaws.com
PriceClass: PriceClass_All
DefaultRootObject: ''
Enabled: true
DefaultCacheBehavior:
ViewerProtocolPolicy: allow-all
TrustedSigners:
Items: []
Enabled: false
SmoothStreaming: false
TargetOriginId: S3-hs-backend-srpms
FieldLevelEncryptionId: ''
ForwardedValues:
Headers:
Items: []
Cookies:
Forward: none
QueryStringCacheKeys:
Items: []
QueryString: false
MaxTTL: 31536000
LambdaFunctionAssociations:
Items: []
DefaultTTL: 86400
AllowedMethods:
CachedMethods:
Items:
- HEAD
- GET
Items:
- HEAD
- GET
MinTTL: 0
Compress: false
IsIPV6Enabled: true
ViewerCertificate:
CloudFrontDefaultCertificate: true
MinimumProtocolVersion: TLSv1
CertificateSource: cloudfront
Aliases:
Items:
- bubba-hotep.bodhi-dev.io
HttpVersion: http2
- Tags:
Owner: dev_engrs
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.pop('Name', name)
Tags = kwargs.pop('Tags', None)
DistributionConfig = kwargs.get('DistributionConfig', {})
## Sub-element munging on config data should go in here, before we proceed:
# For instance, origin access identities must be of the form
# `origin-access-identity/cloudfront/ID-of-origin-access-identity`, but we can't really
# know that ID apriori, so any OAI state names inside the config data must be resolved
# and converted into that format before submission. Be aware that the `state names` of
# salt managed OAIs are stored in their Comment fields for lack of any better place...
for item in range(len(DistributionConfig.get('Origins', {}).get('Items', []))):
oai = DistributionConfig['Origins']['Items'][item].get('S3OriginConfig',
{}).get('OriginAccessIdentity', '')
if oai and not oai.startswith('origin-access-identity/cloudfront/'):
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=oai, region=region, key=key, keyid=keyid, profile=profile)
if res is None: # An error occurred, bubble it up...
log.warning('Error encountered while trying to determine the Resource ID of'
' CloudFront origin access identity `%s`. Passing as-is.', oai)
elif not res:
log.warning('Failed to determine the Resource ID of CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
elif len(res) > 1:
log.warning('Failed to find unique Resource ID for CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
else:
# One unique OAI resource found -- deref and replace it...
new = 'origin-access-identity/cloudfront/{}'.format(res[0]['Id'])
DistributionConfig['Origins']['Items'][item]['S3OriginConfig']['OriginAccessIdentity'] = new
# Munge Name into the Comment field...
DistributionConfig['Comment'] = '{}:{}'.format(Name, DistributionConfig['Comment']) \
if DistributionConfig.get('Comment') else Name
# Fix up any missing (or wrong) Quantity sub-elements...
DistributionConfig = _fix_quantities(DistributionConfig)
kwargs['DistributionConfig'] = DistributionConfig
# Current state of the thing?
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, region=region,
key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
# Luckily, the `DistributionConfig` structure returned by `get_distribution()` (as a sub-
# element of `Distribution`) is identical to that returned by `get_distribution_config(),
# and as a bonus, the ETag's are ALSO compatible...
# Since "updates" are actually "replace everything from scratch" events, this implies that
# it's enough to simply determine SOME update is necessary to trigger one, rather than
# exhaustively calculating all changes needed - this makes life MUCH EASIER :)
# Thus our workflow here is:
# - check if the distribution exists
# - if it doesn't, create it fresh with the requested DistributionConfig, and Tag it if needed
# - if it does, grab its ETag, and TWO copies of the current DistributionConfig
# - merge the requested DistributionConfig on top of one of them
# - compare the copy we just merged against the one we didn't
# - if they differ, send the merged copy, along with the ETag we got, back as an update
# - lastly, verify and set/unset any Tags which may need changing...
exists = bool(res)
if not exists:
if 'CallerReference' not in kwargs['DistributionConfig']:
kwargs['DistributionConfig']['CallerReference'] = str(uuid.uuid4())
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be created.'.format(Name)
new = {'DistributionConfig': kwargs['DistributionConfig']}
new.update({'Tags': Tags}) if Tags else None
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs.update(authargs)
comments = []
res = __salt__['boto_cloudfront.create_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while creating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
new = {'DistributionConfig': res['Distribution']['DistributionConfig']}
comments += ['Created distribution `{}`.'.format(Name)]
newARN = res.get('Distribution', {}).get('ARN')
tagged = __salt__['boto_cloudfront.tag_resource'](Tags=Tags, **authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while tagging distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['Tagged distribution `{}`.'.format(Name)]
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': None, 'new': new}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_distribution_v2'](Id=currentId, **authargs)
# Insanely unlikely given that we JUST got back this Id from the previous search, but....
if not current:
msg = 'Failed to lookup CloudFront distribution with Id `{}`.'.format(currentId)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
currentDC = current['Distribution']['DistributionConfig']
currentARN = current['Distribution']['ARN']
currentETag = current['ETag']
currentTags = __salt__['boto_cloudfront.list_tags_for_resource'](Resource=currentARN,
**authargs)
copyOne = copy.deepcopy(currentDC)
copyTwo = copy.deepcopy(currentDC)
copyTwo.update(kwargs['DistributionConfig'])
correct = __utils__['boto3.json_objs_equal'](copyOne, copyTwo)
tags_correct = (currentTags == Tags)
comments = []
old = {}
new = {}
if correct and tags_correct:
ret['comment'] = 'CloudFront distribution `{}` is in the correct state.'.format(Name)
return ret
if __opts__['test']:
ret['result'] = None
if not correct:
comments += ['CloudFront distribution `{}` config would be updated.'.format(Name)]
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = copyTwo
if not tags_correct:
comments += ['CloudFront distribution `{}` Tags would be updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['pchanges'] = {'old': old, 'new': new}
return ret
if not correct:
kwargs = {'DistributionConfig': copyTwo, 'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
log.debug('Calling `boto_cloudfront.update_distribution_v2()` with **kwargs =='
' %s', kwargs)
res = __salt__['boto_cloudfront.update_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = res['Distribution']['DistributionConfig']
comments += ['CloudFront distribution `{}` config updated.'.format(Name)]
if not tags_correct:
tagged = __salt__['boto_cloudfront.enforce_tags'](Resource=currentARN, Tags=Tags,
**authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while updating Tags on distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['CloudFront distribution `{}` Tags updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': new}
return ret
def route53_alias_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a Route53 Alias exists and is pointing at the given CloudFront
distribution. An ``A`` record is always created, and if IPV6 is enabled on
the given distribution, an ``AAAA`` record will be created as well. Also be
aware that Alias records for CloudFront distributions are only permitted in
non-private zones.
name
The name of the state definition.
Distribution
The name of the CloudFront distribution. Defaults to the value of
``name`` if not provided.
HostedZoneId
Id of the Route53 hosted zone within which the records should be created.
DomainName
The domain name associated with the Hosted Zone. Exclusive with HostedZoneId.
ResourceRecordSet
A Route53 Record Set (with AliasTarget section, suitable for use as an
``Alias`` record, if non-default settings are needed on the Alias)
which should be pointed at the provided CloudFront distribution. Note
that this MUST correlate with the Aliases set within the
DistributionConfig section of the distribution.
Some notes *specifically* about the ``AliasTarget`` subsection of the
ResourceRecordSet:
- If not specified, the ``DNSName`` sub-field will be populated by
dereferencing ``Distribution`` above to the value of its
``DomainName`` attribute.
- The HostedZoneId sub-field should not be provided -- it will be
automatically populated with a ``magic`` AWS value.
- The EvaluateTargetHealth can only be False on a CloudFront Alias.
- The above items taken all together imply that, for most use-cases,
the AliasTarget sub-section can be entirely omitted, as seen in the
first code sample below.
Lastly, note that if you set ``name`` to the desired ResourceRecordSet
Name, you can entirely omit this parameter, as shown in the second
example below.
.. code-block:: yaml
Add a Route53 Alias for my_distribution:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
- ResourceRecordSet:
Name: the-alias.saltstack.org.
# This is even simpler - it uses the value of `name` for ResourceRecordSet.Name
another-alias.saltstack.org.:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
'''
MAGIC_CLOUDFRONT_HOSTED_ZONEID = 'Z2FDTNDATAQYW2'
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
Distribution = kwargs['Distribution'] if 'Distribution' in kwargs else name
ResourceRecordSet = kwargs.get('ResourceRecordSet', {})
Name = ResourceRecordSet.get('Name', name)
ResourceRecordSet['Name'] = Name
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Distribution,
region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error resolving CloudFront distribution `{}` to a Resource ID.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'No CloudFront distibutions matching `{}` found.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
dist = res[0]
Types = ('A', 'AAAA') if dist.get('IsIPV6Enabled', False) else ('A',)
DNSName = dist.get('DomainName', '')
Aliases = dist.get('Aliases', {}).get('Items', [])
# AWS annoyance #437:
# Route53 "FQDNs" (correctly!) REQUIRE trailing periods...
# while CloudFront "FQDNs" don't PERMIT trailing periods...
Aliases += [(a if a.endswith('.') else '{}.'.format(a)) for a in Aliases]
if Name not in Aliases:
msg = ('Route53 alias `{}` requested which is not mirrored in the `Aliases`'
' sub-section of the DistributionConfig.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
changes = {'old': [], 'new': []}
comments = []
# Now mock out a route53 state def, and use the route53 rr_exists state to enforce it...
AliasTarget = ResourceRecordSet.get('AliasTarget', {})
AliasTarget['DNSName'] = AliasTarget['DNSName'] if 'DNSName' in AliasTarget else DNSName
AliasTarget['DNSName'] += '' if AliasTarget['DNSName'].endswith('.') else '.' # GRRRR!
AliasTarget['HostedZoneId'] = MAGIC_CLOUDFRONT_HOSTED_ZONEID
AliasTarget['EvaluateTargetHealth'] = False # Route53 limitation
ResourceRecordSet['name'] = Name
ResourceRecordSet['AliasTarget'] = AliasTarget
ResourceRecordSet['PrivateZone'] = False # Route53 limitation
ResourceRecordSet['DomainName'] = kwargs.get('DomainName')
ResourceRecordSet['HostedZoneId'] = kwargs.get('HostedZoneId')
ResourceRecordSet.update({'region': region, 'key': key, 'keyid': keyid, 'profile': profile})
for Type in Types:
ResourceRecordSet['Type'] = Type
# Checking for `test=True` will occur in the called state....
log.debug('Calling state function `boto3_route53.rr_present()` with args: `%s`',
ResourceRecordSet)
res = __states__['boto3_route53.rr_present'](**ResourceRecordSet)
ret['result'] = res['result']
comments += [res['comment']]
if ret['result'] not in (True, None):
break
changes['old'] += [res['changes']['old']] if res['changes'].get('old') else []
changes['new'] += [res['changes']['new']] if res['changes'].get('new') else []
ret['changes'].update({'old': changes['old']}) if changes.get('old') else None
ret['changes'].update({'new': changes['new']}) if changes.get('new') else None
ret['comment'] = ' '.join(comments)
return ret
def distribution_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
distribution's status to Disabled, and once that returns success, to then
delete the resource. THIS CAN TAKE SOME TIME, so be patient :)
name (string)
Name of the state definition.
Name (string)
Name of the CloudFront distribution to be managed. If not provided, the
value of ``name`` will be used as a default. The purpose of this
parameter is only to resolve it to a Resource ID, so be aware that an
explicit value for ``Id`` below will override any value provided, or
defaulted, here.
Id (string)
The Resource ID of a CloudFront distribution to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure a distribution named my_distribution is gone:
boto_cloudfront.distribution_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
if not Id:
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, **authargs)
if res is None:
msg = 'Error dereferencing CloudFront distribution `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = ('Multiple CloudFront distibutions matched `{}`, no way to know which to'
' delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'CloudFront Distribution `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = res[0]['Id']
if not __salt__['boto_cloudfront.distribution_exists'](Id=Id, **authargs):
msg = 'CloudFront distribution `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_distribution_v2'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront distribution `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
currETag = old['ETag']
Enabled = old['DistributionConfig']['Enabled']
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be {}deleted.'.format(ref,
('disabled and ' if Enabled else ''))
ret['pchanges'] = {'old': old, 'new': None}
return ret
comments = []
if Enabled:
disabled = __salt__['boto_cloudfront.disable_distribution'](Id=Id, **authargs)
if disabled is None:
ret['result'] = False
msg = 'Error disabling CloudFront distribution `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
comments += ['CloudFront distribution `{}` disabled.'.format(ref)]
currETag = disabled['ETag']
deleted = __salt__['boto_cloudfront.delete_distribution'](Id=Id, IfMatch=currETag, **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront distribution `{}`'.format(ref)
comments += [msg]
log.error(msg)
ret['comment'] = ' '.join(comments)
return ret
msg = 'CloudFront distribution `{}` deleted.'.format(ref)
comments += [msg]
log.info(msg)
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': None}
return ret
def origin_access_identity_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity exists.
.. note::
Due to the unavailibity of ANY other way to store stateful idempotency
information about Origin Access Identities (including resource tags),
the Comment attribute (as the only user-settable attribute without
weird self-blocking semantics) is necessarily utilized to store the
Salt state signifier, which is used to determine resource existence and
state. That said, to enable SOME usability of this field, only the
value up to the first colon character is taken as the signifier, while
anything afterward is free-form and ignored by Salt.
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not provided, the value of
`name` will be used.
Comment
Free-form text description of the origin access identity.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_OAI:
boto_cloudfront.origin_access_identity_present:
- Comment: Simply ensures an OAI named my_OAI exists
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.get('Name', name)
# Munge Name into the Comment field...
Comment = '{}:{}'.format(Name, kwargs['Comment']) if kwargs.get('Comment') else Name
# Current state of the thing?
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront origin access identities matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
exists = bool(res)
if not exists:
CloudFrontOriginAccessIdentityConfig = {'Comment': Comment,
'CallerReference': str(uuid.uuid4())}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be created.'.format(Name)
new = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.create_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Failed to create CloudFront origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'Created CloudFrong origin access identity`{}`.'.format(Name)
ret['changes'] = {'old': None, 'new': res}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=currentId,
**authargs)
currentETag = current['ETag']
currentOAIC = current['CloudFrontOriginAccessIdentity']['CloudFrontOriginAccessIdentityConfig']
new = copy.deepcopy(currentOAIC)
new.update({'Comment': Comment}) # Currently the only updatable element :-/
if currentOAIC == new:
msg = 'CloudFront origin access identity `{}` is in the correct state.'.format(Name)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be updated.'.format(Name)
ret['pchanges'] = {'old': currentOAIC, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': new,
'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.update_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'CloudFront origin access identity `{}` config updated.'.format(Name)
ret['changes'] = {'old': currentOAIC, 'new': new}
return ret
def origin_access_identity_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity is absent.
name
The name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
Id (string)
The Resource ID of a CloudFront origin access identity to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure an origin access identity named my_OAI is gone:
boto_cloudfront.origin_access_identity_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
current = None
if not Id:
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, **authargs)
if current is None:
msg = 'Error dereferencing origin access identity `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(current) > 1:
msg = ('Multiple CloudFront origin access identities matched `{}`, no way to know'
' which to delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not current:
msg = 'CloudFront origin access identity `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = current[0]['Id']
if not __salt__['boto_cloudfront.cloud_front_origin_access_identity_exists'](Id=Id, **authargs):
msg = 'CloudFront origin access identity `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront origin access identity `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be deleted.'.format(ref)
ret['pchanges'] = {'old': old, 'new': None}
return ret
deleted = __salt__['boto_cloudfront.delete_cloud_front_origin_access_identity'](Id=Id,
IfMatch=old['ETag'], **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront origin access identity `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
msg = 'CloudFront origin access identity `{}` deleted.'.format(ref)
log.info(msg)
ret['comment'] = msg
ret['changes'] = {'old': old, 'new': None}
return ret
|
saltstack/salt | salt/states/boto_cloudfront.py | route53_alias_present | python | def route53_alias_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a Route53 Alias exists and is pointing at the given CloudFront
distribution. An ``A`` record is always created, and if IPV6 is enabled on
the given distribution, an ``AAAA`` record will be created as well. Also be
aware that Alias records for CloudFront distributions are only permitted in
non-private zones.
name
The name of the state definition.
Distribution
The name of the CloudFront distribution. Defaults to the value of
``name`` if not provided.
HostedZoneId
Id of the Route53 hosted zone within which the records should be created.
DomainName
The domain name associated with the Hosted Zone. Exclusive with HostedZoneId.
ResourceRecordSet
A Route53 Record Set (with AliasTarget section, suitable for use as an
``Alias`` record, if non-default settings are needed on the Alias)
which should be pointed at the provided CloudFront distribution. Note
that this MUST correlate with the Aliases set within the
DistributionConfig section of the distribution.
Some notes *specifically* about the ``AliasTarget`` subsection of the
ResourceRecordSet:
- If not specified, the ``DNSName`` sub-field will be populated by
dereferencing ``Distribution`` above to the value of its
``DomainName`` attribute.
- The HostedZoneId sub-field should not be provided -- it will be
automatically populated with a ``magic`` AWS value.
- The EvaluateTargetHealth can only be False on a CloudFront Alias.
- The above items taken all together imply that, for most use-cases,
the AliasTarget sub-section can be entirely omitted, as seen in the
first code sample below.
Lastly, note that if you set ``name`` to the desired ResourceRecordSet
Name, you can entirely omit this parameter, as shown in the second
example below.
.. code-block:: yaml
Add a Route53 Alias for my_distribution:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
- ResourceRecordSet:
Name: the-alias.saltstack.org.
# This is even simpler - it uses the value of `name` for ResourceRecordSet.Name
another-alias.saltstack.org.:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
'''
MAGIC_CLOUDFRONT_HOSTED_ZONEID = 'Z2FDTNDATAQYW2'
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
Distribution = kwargs['Distribution'] if 'Distribution' in kwargs else name
ResourceRecordSet = kwargs.get('ResourceRecordSet', {})
Name = ResourceRecordSet.get('Name', name)
ResourceRecordSet['Name'] = Name
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Distribution,
region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error resolving CloudFront distribution `{}` to a Resource ID.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'No CloudFront distibutions matching `{}` found.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
dist = res[0]
Types = ('A', 'AAAA') if dist.get('IsIPV6Enabled', False) else ('A',)
DNSName = dist.get('DomainName', '')
Aliases = dist.get('Aliases', {}).get('Items', [])
# AWS annoyance #437:
# Route53 "FQDNs" (correctly!) REQUIRE trailing periods...
# while CloudFront "FQDNs" don't PERMIT trailing periods...
Aliases += [(a if a.endswith('.') else '{}.'.format(a)) for a in Aliases]
if Name not in Aliases:
msg = ('Route53 alias `{}` requested which is not mirrored in the `Aliases`'
' sub-section of the DistributionConfig.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
changes = {'old': [], 'new': []}
comments = []
# Now mock out a route53 state def, and use the route53 rr_exists state to enforce it...
AliasTarget = ResourceRecordSet.get('AliasTarget', {})
AliasTarget['DNSName'] = AliasTarget['DNSName'] if 'DNSName' in AliasTarget else DNSName
AliasTarget['DNSName'] += '' if AliasTarget['DNSName'].endswith('.') else '.' # GRRRR!
AliasTarget['HostedZoneId'] = MAGIC_CLOUDFRONT_HOSTED_ZONEID
AliasTarget['EvaluateTargetHealth'] = False # Route53 limitation
ResourceRecordSet['name'] = Name
ResourceRecordSet['AliasTarget'] = AliasTarget
ResourceRecordSet['PrivateZone'] = False # Route53 limitation
ResourceRecordSet['DomainName'] = kwargs.get('DomainName')
ResourceRecordSet['HostedZoneId'] = kwargs.get('HostedZoneId')
ResourceRecordSet.update({'region': region, 'key': key, 'keyid': keyid, 'profile': profile})
for Type in Types:
ResourceRecordSet['Type'] = Type
# Checking for `test=True` will occur in the called state....
log.debug('Calling state function `boto3_route53.rr_present()` with args: `%s`',
ResourceRecordSet)
res = __states__['boto3_route53.rr_present'](**ResourceRecordSet)
ret['result'] = res['result']
comments += [res['comment']]
if ret['result'] not in (True, None):
break
changes['old'] += [res['changes']['old']] if res['changes'].get('old') else []
changes['new'] += [res['changes']['new']] if res['changes'].get('new') else []
ret['changes'].update({'old': changes['old']}) if changes.get('old') else None
ret['changes'].update({'new': changes['new']}) if changes.get('new') else None
ret['comment'] = ' '.join(comments)
return ret | Ensure a Route53 Alias exists and is pointing at the given CloudFront
distribution. An ``A`` record is always created, and if IPV6 is enabled on
the given distribution, an ``AAAA`` record will be created as well. Also be
aware that Alias records for CloudFront distributions are only permitted in
non-private zones.
name
The name of the state definition.
Distribution
The name of the CloudFront distribution. Defaults to the value of
``name`` if not provided.
HostedZoneId
Id of the Route53 hosted zone within which the records should be created.
DomainName
The domain name associated with the Hosted Zone. Exclusive with HostedZoneId.
ResourceRecordSet
A Route53 Record Set (with AliasTarget section, suitable for use as an
``Alias`` record, if non-default settings are needed on the Alias)
which should be pointed at the provided CloudFront distribution. Note
that this MUST correlate with the Aliases set within the
DistributionConfig section of the distribution.
Some notes *specifically* about the ``AliasTarget`` subsection of the
ResourceRecordSet:
- If not specified, the ``DNSName`` sub-field will be populated by
dereferencing ``Distribution`` above to the value of its
``DomainName`` attribute.
- The HostedZoneId sub-field should not be provided -- it will be
automatically populated with a ``magic`` AWS value.
- The EvaluateTargetHealth can only be False on a CloudFront Alias.
- The above items taken all together imply that, for most use-cases,
the AliasTarget sub-section can be entirely omitted, as seen in the
first code sample below.
Lastly, note that if you set ``name`` to the desired ResourceRecordSet
Name, you can entirely omit this parameter, as shown in the second
example below.
.. code-block:: yaml
Add a Route53 Alias for my_distribution:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
- ResourceRecordSet:
Name: the-alias.saltstack.org.
# This is even simpler - it uses the value of `name` for ResourceRecordSet.Name
another-alias.saltstack.org.:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudfront.py#L698-L834 | null | # -*- coding: utf-8 -*-
'''
Manage CloudFront distributions
.. versionadded:: 2018.3.0
Create, update and destroy CloudFront distributions.
This module accepts explicit AWS credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API
and no further configuration is necessary.
More information available `here
<https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them,
either in a pillar file or in the minion's config file:
.. code-block:: yaml
cloudfront.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudfront.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid``, and ``region`` via a profile,
either passed in as a dict, or a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
aws:
region:
us-east-1:
profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import uuid
import copy
import json
# Import Salt conveniences
from salt.ext import six
from salt.ext.six.moves import range
#pylint: disable=W0106
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
if 'boto_cloudfront.get_distribution' not in __salt__:
msg = 'The boto_cloudfront state module could not be loaded: {}.'
return (False, msg.format('boto_cloudfront exec module unavailable.'))
return 'boto_cloudfront'
def present(
name,
config,
tags,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the CloudFront distribution is present.
name (string)
Name of the CloudFront distribution
config (dict)
Configuration for the distribution
tags (dict)
Tags to associate with the distribution
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
Example:
.. code-block:: yaml
Manage my_distribution CloudFront distribution:
boto_cloudfront.present:
- name: my_distribution
- config:
Comment: 'partial config shown, most parameters elided'
Enabled: True
- tags:
testing_key: testing_value
'''
ret = {
'name': name,
'comment': '',
'changes': {},
}
res = __salt__['boto_cloudfront.get_distribution'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error checking distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
old = res['result']
if old is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Distribution {0} set for creation.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
res = __salt__['boto_cloudfront.create_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error creating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Created distribution {0}.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
else:
full_config_old = {
'config': old['distribution']['DistributionConfig'],
'tags': old['tags'],
}
full_config_new = {
'config': config,
'tags': tags,
}
diffed_config = __utils__['dictdiffer.deep_diff'](
full_config_old,
full_config_new,
)
def _yaml_safe_dump(attrs):
'''
Safely dump YAML using a readable flow style
'''
dumper_name = 'IndentedSafeOrderedDumper'
dumper = __utils__['yaml.get_dumper'](dumper_name)
return __utils__['yaml.dump'](
attrs,
default_flow_style=False,
Dumper=dumper)
changes_diff = ''.join(difflib.unified_diff(
_yaml_safe_dump(full_config_old).splitlines(True),
_yaml_safe_dump(full_config_new).splitlines(True),
))
any_changes = bool('old' in diffed_config or 'new' in diffed_config)
if not any_changes:
ret['result'] = True
ret['comment'] = 'Distribution {0} has correct config.'.format(
name,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join([
'Distribution {0} set for new config:'.format(name),
changes_diff,
])
ret['changes'] = {'diff': changes_diff}
return ret
res = __salt__['boto_cloudfront.update_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error updating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Updated distribution {0}.'.format(name)
ret['changes'] = {'diff': changes_diff}
return ret
def _fix_quantities(tree):
'''
Stupidly simple function to fix any Items/Quantity disparities inside a
DistributionConfig block before use. Since AWS only accepts JSON-encodable
data types, this implementation is "good enough" for our purposes.
'''
if isinstance(tree, dict):
tree = {k: _fix_quantities(v) for k, v in tree.items()}
if isinstance(tree.get('Items'), list):
tree['Quantity'] = len(tree['Items'])
if not tree['Items']:
tree.pop('Items') # Silly, but AWS requires it....
return tree
elif isinstance(tree, list):
return [_fix_quantities(t) for t in tree]
else:
return tree
def distribution_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure the given CloudFront distribution exists in the described state.
The implementation of this function, and all those following, is orthagonal
to that of :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>`. Resources created with
:py:mod:`boto_cloudfront.present <salt.states.boto_cloudfront.present>`
will not be correctly managed by this function, as a different method is
used to store Salt's state signifier. This function and those following are
a suite, designed to work together. As an extra bonus, they correctly
process updates of the managed resources, so it is recommended to use them
in preference to :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>` above.
Note that the semantics of DistributionConfig (below) are rather arcane,
and vary wildly depending on whether the distribution already exists or not
(e.g. is being initially created, or being updated in place). Many more
details can be found here__.
.. __: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-overview-required-fields.html
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
DistributionConfig (dict)
Configuration for the distribution.
Notes:
- The CallerReference field should NOT be provided - it will be
autopopulated by Salt.
- A large number of sub- (and sub-sub-) fields require a ``Quantity``
element, which simply COUNTS the number of items in the ``Items``
element. This is bluntly stupid, so as a convenience, Salt will
traverse the provided configuration, and add (or fix) a ``Quantity``
element for any ``Items`` elements of list-type it encounters. This
adds a bit of sanity to an otherwise error-prone situation. Note
that for this to work, zero-length lists must be inlined as ``[]``.
- Due to the unavailibity of a better way to store stateful idempotency
information about Distributions, the Comment sub-element (as the only
user-settable attribute without weird self-blocking semantics, and
which is available from the core ``get_distribution()`` API call) is
utilized to store the Salt state signifier, which is used to
determine resource existence and state. That said, to enable **some**
usability of this field, only the value up to the first colon
character is taken as the signifier, with everything afterward
free-form, and ignored (but preserved) by Salt.
Tags (dict)
Tags to associate with the distribution.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
plt-dev-spaapi-cf-dist-cf_dist-present:
boto_cloudfront.distribution_present:
- Name: plt-dev-spaapi-cf-dist
- DistributionConfig:
Comment: SPA
Logging:
Enabled: false
Prefix: ''
Bucket: ''
IncludeCookies: false
WebACLId: ''
Origins:
Items:
- S3OriginConfig:
OriginAccessIdentity: the-SPA-OAI
OriginPath: ''
CustomHeaders:
Items: []
Id: S3-hs-backend-srpms
DomainName: hs-backend-srpms.s3.amazonaws.com
PriceClass: PriceClass_All
DefaultRootObject: ''
Enabled: true
DefaultCacheBehavior:
ViewerProtocolPolicy: allow-all
TrustedSigners:
Items: []
Enabled: false
SmoothStreaming: false
TargetOriginId: S3-hs-backend-srpms
FieldLevelEncryptionId: ''
ForwardedValues:
Headers:
Items: []
Cookies:
Forward: none
QueryStringCacheKeys:
Items: []
QueryString: false
MaxTTL: 31536000
LambdaFunctionAssociations:
Items: []
DefaultTTL: 86400
AllowedMethods:
CachedMethods:
Items:
- HEAD
- GET
Items:
- HEAD
- GET
MinTTL: 0
Compress: false
IsIPV6Enabled: true
ViewerCertificate:
CloudFrontDefaultCertificate: true
MinimumProtocolVersion: TLSv1
CertificateSource: cloudfront
Aliases:
Items:
- bubba-hotep.bodhi-dev.io
HttpVersion: http2
- Tags:
Owner: dev_engrs
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.pop('Name', name)
Tags = kwargs.pop('Tags', None)
DistributionConfig = kwargs.get('DistributionConfig', {})
## Sub-element munging on config data should go in here, before we proceed:
# For instance, origin access identities must be of the form
# `origin-access-identity/cloudfront/ID-of-origin-access-identity`, but we can't really
# know that ID apriori, so any OAI state names inside the config data must be resolved
# and converted into that format before submission. Be aware that the `state names` of
# salt managed OAIs are stored in their Comment fields for lack of any better place...
for item in range(len(DistributionConfig.get('Origins', {}).get('Items', []))):
oai = DistributionConfig['Origins']['Items'][item].get('S3OriginConfig',
{}).get('OriginAccessIdentity', '')
if oai and not oai.startswith('origin-access-identity/cloudfront/'):
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=oai, region=region, key=key, keyid=keyid, profile=profile)
if res is None: # An error occurred, bubble it up...
log.warning('Error encountered while trying to determine the Resource ID of'
' CloudFront origin access identity `%s`. Passing as-is.', oai)
elif not res:
log.warning('Failed to determine the Resource ID of CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
elif len(res) > 1:
log.warning('Failed to find unique Resource ID for CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
else:
# One unique OAI resource found -- deref and replace it...
new = 'origin-access-identity/cloudfront/{}'.format(res[0]['Id'])
DistributionConfig['Origins']['Items'][item]['S3OriginConfig']['OriginAccessIdentity'] = new
# Munge Name into the Comment field...
DistributionConfig['Comment'] = '{}:{}'.format(Name, DistributionConfig['Comment']) \
if DistributionConfig.get('Comment') else Name
# Fix up any missing (or wrong) Quantity sub-elements...
DistributionConfig = _fix_quantities(DistributionConfig)
kwargs['DistributionConfig'] = DistributionConfig
# Current state of the thing?
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, region=region,
key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
# Luckily, the `DistributionConfig` structure returned by `get_distribution()` (as a sub-
# element of `Distribution`) is identical to that returned by `get_distribution_config(),
# and as a bonus, the ETag's are ALSO compatible...
# Since "updates" are actually "replace everything from scratch" events, this implies that
# it's enough to simply determine SOME update is necessary to trigger one, rather than
# exhaustively calculating all changes needed - this makes life MUCH EASIER :)
# Thus our workflow here is:
# - check if the distribution exists
# - if it doesn't, create it fresh with the requested DistributionConfig, and Tag it if needed
# - if it does, grab its ETag, and TWO copies of the current DistributionConfig
# - merge the requested DistributionConfig on top of one of them
# - compare the copy we just merged against the one we didn't
# - if they differ, send the merged copy, along with the ETag we got, back as an update
# - lastly, verify and set/unset any Tags which may need changing...
exists = bool(res)
if not exists:
if 'CallerReference' not in kwargs['DistributionConfig']:
kwargs['DistributionConfig']['CallerReference'] = str(uuid.uuid4())
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be created.'.format(Name)
new = {'DistributionConfig': kwargs['DistributionConfig']}
new.update({'Tags': Tags}) if Tags else None
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs.update(authargs)
comments = []
res = __salt__['boto_cloudfront.create_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while creating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
new = {'DistributionConfig': res['Distribution']['DistributionConfig']}
comments += ['Created distribution `{}`.'.format(Name)]
newARN = res.get('Distribution', {}).get('ARN')
tagged = __salt__['boto_cloudfront.tag_resource'](Tags=Tags, **authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while tagging distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['Tagged distribution `{}`.'.format(Name)]
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': None, 'new': new}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_distribution_v2'](Id=currentId, **authargs)
# Insanely unlikely given that we JUST got back this Id from the previous search, but....
if not current:
msg = 'Failed to lookup CloudFront distribution with Id `{}`.'.format(currentId)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
currentDC = current['Distribution']['DistributionConfig']
currentARN = current['Distribution']['ARN']
currentETag = current['ETag']
currentTags = __salt__['boto_cloudfront.list_tags_for_resource'](Resource=currentARN,
**authargs)
copyOne = copy.deepcopy(currentDC)
copyTwo = copy.deepcopy(currentDC)
copyTwo.update(kwargs['DistributionConfig'])
correct = __utils__['boto3.json_objs_equal'](copyOne, copyTwo)
tags_correct = (currentTags == Tags)
comments = []
old = {}
new = {}
if correct and tags_correct:
ret['comment'] = 'CloudFront distribution `{}` is in the correct state.'.format(Name)
return ret
if __opts__['test']:
ret['result'] = None
if not correct:
comments += ['CloudFront distribution `{}` config would be updated.'.format(Name)]
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = copyTwo
if not tags_correct:
comments += ['CloudFront distribution `{}` Tags would be updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['pchanges'] = {'old': old, 'new': new}
return ret
if not correct:
kwargs = {'DistributionConfig': copyTwo, 'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
log.debug('Calling `boto_cloudfront.update_distribution_v2()` with **kwargs =='
' %s', kwargs)
res = __salt__['boto_cloudfront.update_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = res['Distribution']['DistributionConfig']
comments += ['CloudFront distribution `{}` config updated.'.format(Name)]
if not tags_correct:
tagged = __salt__['boto_cloudfront.enforce_tags'](Resource=currentARN, Tags=Tags,
**authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while updating Tags on distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['CloudFront distribution `{}` Tags updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': new}
return ret
def oai_bucket_policy_present(name, Bucket, OAI, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the given policy exists on an S3 bucket, granting access for the given origin access
identity to do the things specified in the policy.
name
The name of the state definition
Bucket
The S3 bucket which CloudFront needs access to. Note that this policy
is exclusive - it will be the only policy definition on the bucket (and
objects inside the bucket if you specify such permissions in the
policy). Note that this likely SHOULD reflect the bucket mentioned in
the Resource section of the Policy, but this is not enforced...
OAI
The value of `Name` passed to the state definition for the origin
access identity which will be accessing the bucket.
Policy
The full policy document which should be set on the S3 bucket. If a
``Principal`` clause is not provided in the policy, one will be
automatically added, and pointed at the correct value as dereferenced
from the OAI provided above. If one IS provided, then this is not
done, and you are responsible for providing the correct values.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_oai_s3_policy:
boto_cloudfront.oai_bucket_policy_present:
- Bucket: the_bucket_for_my_distribution
- OAI: the_OAI_I_just_created_and_attached_to_my_distribution
- Policy:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::the_bucket_for_my_distribution/*
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
oais = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=OAI, region=region, key=key, keyid=keyid, profile=profile)
if len(oais) > 1:
msg = 'Multiple origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not oais:
msg = 'No origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
canonical_user = oais[0].get('S3CanonicalUserId')
oai_id = oais[0].get('Id')
if isinstance(Policy, six.string_types):
Policy = json.loads(Policy)
for stanza in range(len(Policy.get('Statement', []))):
if 'Principal' not in Policy['Statement'][stanza]:
Policy['Statement'][stanza]['Principal'] = {"CanonicalUser": canonical_user}
bucket = __salt__['boto_s3_bucket.describe'](Bucket=Bucket, region=region, key=key,
keyid=keyid, profile=profile)
if not bucket or 'bucket' not in bucket:
msg = 'S3 bucket `{}` not found.'.format(Bucket)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
curr_policy = bucket['bucket'].get('Policy', {}).get('Policy', {}) # ?!? dunno, that's just how it gets returned...
curr_policy = json.loads(curr_policy) if isinstance(curr_policy,
six.string_types) else curr_policy
# Sooooo, you have to SUBMIT Principals of the form
# Principal: {'S3CanonicalUserId': someCrazyLongMagicValueAsDerivedAbove}
# BUT, they RETURN the Principal as something WILDLY different
# Principal: {'AWS': arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E30ABCDEF12345}
# which obviously compare different on every run... So we fake it thusly.
fake_Policy = copy.deepcopy(Policy)
for stanza in range(len(fake_Policy.get('Statement', []))):
# Warning: unavoidable hardcoded magic values HO!
fake_Policy['Statement'][stanza].update({'Principal': {'AWS':
'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity {}'.format(oai_id)}})
if __utils__['boto3.json_objs_equal'](curr_policy, fake_Policy):
msg = 'Policy of S3 bucket `{}` is in the correct state.'.format(Bucket)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['comment'] = 'Policy on S3 bucket `{}` would be updated.'.format(Bucket)
ret['result'] = None
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
res = __salt__['boto_s3_bucket.put_policy'](Bucket=Bucket, Policy=Policy,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in res:
ret['comment'] = 'Failed to update policy on S3 bucket `{}`: {}'.format(Bucket,
res['error'])
ret['return'] = False
return ret
ret['comment'] = 'Policy on S3 bucket `{}` updated.'.format(Bucket)
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
def distribution_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
distribution's status to Disabled, and once that returns success, to then
delete the resource. THIS CAN TAKE SOME TIME, so be patient :)
name (string)
Name of the state definition.
Name (string)
Name of the CloudFront distribution to be managed. If not provided, the
value of ``name`` will be used as a default. The purpose of this
parameter is only to resolve it to a Resource ID, so be aware that an
explicit value for ``Id`` below will override any value provided, or
defaulted, here.
Id (string)
The Resource ID of a CloudFront distribution to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure a distribution named my_distribution is gone:
boto_cloudfront.distribution_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
if not Id:
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, **authargs)
if res is None:
msg = 'Error dereferencing CloudFront distribution `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = ('Multiple CloudFront distibutions matched `{}`, no way to know which to'
' delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'CloudFront Distribution `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = res[0]['Id']
if not __salt__['boto_cloudfront.distribution_exists'](Id=Id, **authargs):
msg = 'CloudFront distribution `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_distribution_v2'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront distribution `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
currETag = old['ETag']
Enabled = old['DistributionConfig']['Enabled']
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be {}deleted.'.format(ref,
('disabled and ' if Enabled else ''))
ret['pchanges'] = {'old': old, 'new': None}
return ret
comments = []
if Enabled:
disabled = __salt__['boto_cloudfront.disable_distribution'](Id=Id, **authargs)
if disabled is None:
ret['result'] = False
msg = 'Error disabling CloudFront distribution `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
comments += ['CloudFront distribution `{}` disabled.'.format(ref)]
currETag = disabled['ETag']
deleted = __salt__['boto_cloudfront.delete_distribution'](Id=Id, IfMatch=currETag, **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront distribution `{}`'.format(ref)
comments += [msg]
log.error(msg)
ret['comment'] = ' '.join(comments)
return ret
msg = 'CloudFront distribution `{}` deleted.'.format(ref)
comments += [msg]
log.info(msg)
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': None}
return ret
def origin_access_identity_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity exists.
.. note::
Due to the unavailibity of ANY other way to store stateful idempotency
information about Origin Access Identities (including resource tags),
the Comment attribute (as the only user-settable attribute without
weird self-blocking semantics) is necessarily utilized to store the
Salt state signifier, which is used to determine resource existence and
state. That said, to enable SOME usability of this field, only the
value up to the first colon character is taken as the signifier, while
anything afterward is free-form and ignored by Salt.
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not provided, the value of
`name` will be used.
Comment
Free-form text description of the origin access identity.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_OAI:
boto_cloudfront.origin_access_identity_present:
- Comment: Simply ensures an OAI named my_OAI exists
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.get('Name', name)
# Munge Name into the Comment field...
Comment = '{}:{}'.format(Name, kwargs['Comment']) if kwargs.get('Comment') else Name
# Current state of the thing?
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront origin access identities matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
exists = bool(res)
if not exists:
CloudFrontOriginAccessIdentityConfig = {'Comment': Comment,
'CallerReference': str(uuid.uuid4())}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be created.'.format(Name)
new = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.create_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Failed to create CloudFront origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'Created CloudFrong origin access identity`{}`.'.format(Name)
ret['changes'] = {'old': None, 'new': res}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=currentId,
**authargs)
currentETag = current['ETag']
currentOAIC = current['CloudFrontOriginAccessIdentity']['CloudFrontOriginAccessIdentityConfig']
new = copy.deepcopy(currentOAIC)
new.update({'Comment': Comment}) # Currently the only updatable element :-/
if currentOAIC == new:
msg = 'CloudFront origin access identity `{}` is in the correct state.'.format(Name)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be updated.'.format(Name)
ret['pchanges'] = {'old': currentOAIC, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': new,
'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.update_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'CloudFront origin access identity `{}` config updated.'.format(Name)
ret['changes'] = {'old': currentOAIC, 'new': new}
return ret
def origin_access_identity_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity is absent.
name
The name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
Id (string)
The Resource ID of a CloudFront origin access identity to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure an origin access identity named my_OAI is gone:
boto_cloudfront.origin_access_identity_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
current = None
if not Id:
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, **authargs)
if current is None:
msg = 'Error dereferencing origin access identity `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(current) > 1:
msg = ('Multiple CloudFront origin access identities matched `{}`, no way to know'
' which to delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not current:
msg = 'CloudFront origin access identity `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = current[0]['Id']
if not __salt__['boto_cloudfront.cloud_front_origin_access_identity_exists'](Id=Id, **authargs):
msg = 'CloudFront origin access identity `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront origin access identity `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be deleted.'.format(ref)
ret['pchanges'] = {'old': old, 'new': None}
return ret
deleted = __salt__['boto_cloudfront.delete_cloud_front_origin_access_identity'](Id=Id,
IfMatch=old['ETag'], **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront origin access identity `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
msg = 'CloudFront origin access identity `{}` deleted.'.format(ref)
log.info(msg)
ret['comment'] = msg
ret['changes'] = {'old': old, 'new': None}
return ret
|
saltstack/salt | salt/states/boto_cloudfront.py | distribution_absent | python | def distribution_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
distribution's status to Disabled, and once that returns success, to then
delete the resource. THIS CAN TAKE SOME TIME, so be patient :)
name (string)
Name of the state definition.
Name (string)
Name of the CloudFront distribution to be managed. If not provided, the
value of ``name`` will be used as a default. The purpose of this
parameter is only to resolve it to a Resource ID, so be aware that an
explicit value for ``Id`` below will override any value provided, or
defaulted, here.
Id (string)
The Resource ID of a CloudFront distribution to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure a distribution named my_distribution is gone:
boto_cloudfront.distribution_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
if not Id:
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, **authargs)
if res is None:
msg = 'Error dereferencing CloudFront distribution `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = ('Multiple CloudFront distibutions matched `{}`, no way to know which to'
' delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'CloudFront Distribution `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = res[0]['Id']
if not __salt__['boto_cloudfront.distribution_exists'](Id=Id, **authargs):
msg = 'CloudFront distribution `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_distribution_v2'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront distribution `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
currETag = old['ETag']
Enabled = old['DistributionConfig']['Enabled']
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be {}deleted.'.format(ref,
('disabled and ' if Enabled else ''))
ret['pchanges'] = {'old': old, 'new': None}
return ret
comments = []
if Enabled:
disabled = __salt__['boto_cloudfront.disable_distribution'](Id=Id, **authargs)
if disabled is None:
ret['result'] = False
msg = 'Error disabling CloudFront distribution `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
comments += ['CloudFront distribution `{}` disabled.'.format(ref)]
currETag = disabled['ETag']
deleted = __salt__['boto_cloudfront.delete_distribution'](Id=Id, IfMatch=currETag, **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront distribution `{}`'.format(ref)
comments += [msg]
log.error(msg)
ret['comment'] = ' '.join(comments)
return ret
msg = 'CloudFront distribution `{}` deleted.'.format(ref)
comments += [msg]
log.info(msg)
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': None}
return ret | Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
distribution's status to Disabled, and once that returns success, to then
delete the resource. THIS CAN TAKE SOME TIME, so be patient :)
name (string)
Name of the state definition.
Name (string)
Name of the CloudFront distribution to be managed. If not provided, the
value of ``name`` will be used as a default. The purpose of this
parameter is only to resolve it to a Resource ID, so be aware that an
explicit value for ``Id`` below will override any value provided, or
defaulted, here.
Id (string)
The Resource ID of a CloudFront distribution to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure a distribution named my_distribution is gone:
boto_cloudfront.distribution_absent:
- Name: my_distribution | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudfront.py#L837-L955 | null | # -*- coding: utf-8 -*-
'''
Manage CloudFront distributions
.. versionadded:: 2018.3.0
Create, update and destroy CloudFront distributions.
This module accepts explicit AWS credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API
and no further configuration is necessary.
More information available `here
<https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them,
either in a pillar file or in the minion's config file:
.. code-block:: yaml
cloudfront.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudfront.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid``, and ``region`` via a profile,
either passed in as a dict, or a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
aws:
region:
us-east-1:
profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import uuid
import copy
import json
# Import Salt conveniences
from salt.ext import six
from salt.ext.six.moves import range
#pylint: disable=W0106
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
if 'boto_cloudfront.get_distribution' not in __salt__:
msg = 'The boto_cloudfront state module could not be loaded: {}.'
return (False, msg.format('boto_cloudfront exec module unavailable.'))
return 'boto_cloudfront'
def present(
name,
config,
tags,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the CloudFront distribution is present.
name (string)
Name of the CloudFront distribution
config (dict)
Configuration for the distribution
tags (dict)
Tags to associate with the distribution
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
Example:
.. code-block:: yaml
Manage my_distribution CloudFront distribution:
boto_cloudfront.present:
- name: my_distribution
- config:
Comment: 'partial config shown, most parameters elided'
Enabled: True
- tags:
testing_key: testing_value
'''
ret = {
'name': name,
'comment': '',
'changes': {},
}
res = __salt__['boto_cloudfront.get_distribution'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error checking distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
old = res['result']
if old is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Distribution {0} set for creation.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
res = __salt__['boto_cloudfront.create_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error creating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Created distribution {0}.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
else:
full_config_old = {
'config': old['distribution']['DistributionConfig'],
'tags': old['tags'],
}
full_config_new = {
'config': config,
'tags': tags,
}
diffed_config = __utils__['dictdiffer.deep_diff'](
full_config_old,
full_config_new,
)
def _yaml_safe_dump(attrs):
'''
Safely dump YAML using a readable flow style
'''
dumper_name = 'IndentedSafeOrderedDumper'
dumper = __utils__['yaml.get_dumper'](dumper_name)
return __utils__['yaml.dump'](
attrs,
default_flow_style=False,
Dumper=dumper)
changes_diff = ''.join(difflib.unified_diff(
_yaml_safe_dump(full_config_old).splitlines(True),
_yaml_safe_dump(full_config_new).splitlines(True),
))
any_changes = bool('old' in diffed_config or 'new' in diffed_config)
if not any_changes:
ret['result'] = True
ret['comment'] = 'Distribution {0} has correct config.'.format(
name,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join([
'Distribution {0} set for new config:'.format(name),
changes_diff,
])
ret['changes'] = {'diff': changes_diff}
return ret
res = __salt__['boto_cloudfront.update_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error updating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Updated distribution {0}.'.format(name)
ret['changes'] = {'diff': changes_diff}
return ret
def _fix_quantities(tree):
'''
Stupidly simple function to fix any Items/Quantity disparities inside a
DistributionConfig block before use. Since AWS only accepts JSON-encodable
data types, this implementation is "good enough" for our purposes.
'''
if isinstance(tree, dict):
tree = {k: _fix_quantities(v) for k, v in tree.items()}
if isinstance(tree.get('Items'), list):
tree['Quantity'] = len(tree['Items'])
if not tree['Items']:
tree.pop('Items') # Silly, but AWS requires it....
return tree
elif isinstance(tree, list):
return [_fix_quantities(t) for t in tree]
else:
return tree
def distribution_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure the given CloudFront distribution exists in the described state.
The implementation of this function, and all those following, is orthagonal
to that of :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>`. Resources created with
:py:mod:`boto_cloudfront.present <salt.states.boto_cloudfront.present>`
will not be correctly managed by this function, as a different method is
used to store Salt's state signifier. This function and those following are
a suite, designed to work together. As an extra bonus, they correctly
process updates of the managed resources, so it is recommended to use them
in preference to :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>` above.
Note that the semantics of DistributionConfig (below) are rather arcane,
and vary wildly depending on whether the distribution already exists or not
(e.g. is being initially created, or being updated in place). Many more
details can be found here__.
.. __: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-overview-required-fields.html
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
DistributionConfig (dict)
Configuration for the distribution.
Notes:
- The CallerReference field should NOT be provided - it will be
autopopulated by Salt.
- A large number of sub- (and sub-sub-) fields require a ``Quantity``
element, which simply COUNTS the number of items in the ``Items``
element. This is bluntly stupid, so as a convenience, Salt will
traverse the provided configuration, and add (or fix) a ``Quantity``
element for any ``Items`` elements of list-type it encounters. This
adds a bit of sanity to an otherwise error-prone situation. Note
that for this to work, zero-length lists must be inlined as ``[]``.
- Due to the unavailibity of a better way to store stateful idempotency
information about Distributions, the Comment sub-element (as the only
user-settable attribute without weird self-blocking semantics, and
which is available from the core ``get_distribution()`` API call) is
utilized to store the Salt state signifier, which is used to
determine resource existence and state. That said, to enable **some**
usability of this field, only the value up to the first colon
character is taken as the signifier, with everything afterward
free-form, and ignored (but preserved) by Salt.
Tags (dict)
Tags to associate with the distribution.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
plt-dev-spaapi-cf-dist-cf_dist-present:
boto_cloudfront.distribution_present:
- Name: plt-dev-spaapi-cf-dist
- DistributionConfig:
Comment: SPA
Logging:
Enabled: false
Prefix: ''
Bucket: ''
IncludeCookies: false
WebACLId: ''
Origins:
Items:
- S3OriginConfig:
OriginAccessIdentity: the-SPA-OAI
OriginPath: ''
CustomHeaders:
Items: []
Id: S3-hs-backend-srpms
DomainName: hs-backend-srpms.s3.amazonaws.com
PriceClass: PriceClass_All
DefaultRootObject: ''
Enabled: true
DefaultCacheBehavior:
ViewerProtocolPolicy: allow-all
TrustedSigners:
Items: []
Enabled: false
SmoothStreaming: false
TargetOriginId: S3-hs-backend-srpms
FieldLevelEncryptionId: ''
ForwardedValues:
Headers:
Items: []
Cookies:
Forward: none
QueryStringCacheKeys:
Items: []
QueryString: false
MaxTTL: 31536000
LambdaFunctionAssociations:
Items: []
DefaultTTL: 86400
AllowedMethods:
CachedMethods:
Items:
- HEAD
- GET
Items:
- HEAD
- GET
MinTTL: 0
Compress: false
IsIPV6Enabled: true
ViewerCertificate:
CloudFrontDefaultCertificate: true
MinimumProtocolVersion: TLSv1
CertificateSource: cloudfront
Aliases:
Items:
- bubba-hotep.bodhi-dev.io
HttpVersion: http2
- Tags:
Owner: dev_engrs
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.pop('Name', name)
Tags = kwargs.pop('Tags', None)
DistributionConfig = kwargs.get('DistributionConfig', {})
## Sub-element munging on config data should go in here, before we proceed:
# For instance, origin access identities must be of the form
# `origin-access-identity/cloudfront/ID-of-origin-access-identity`, but we can't really
# know that ID apriori, so any OAI state names inside the config data must be resolved
# and converted into that format before submission. Be aware that the `state names` of
# salt managed OAIs are stored in their Comment fields for lack of any better place...
for item in range(len(DistributionConfig.get('Origins', {}).get('Items', []))):
oai = DistributionConfig['Origins']['Items'][item].get('S3OriginConfig',
{}).get('OriginAccessIdentity', '')
if oai and not oai.startswith('origin-access-identity/cloudfront/'):
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=oai, region=region, key=key, keyid=keyid, profile=profile)
if res is None: # An error occurred, bubble it up...
log.warning('Error encountered while trying to determine the Resource ID of'
' CloudFront origin access identity `%s`. Passing as-is.', oai)
elif not res:
log.warning('Failed to determine the Resource ID of CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
elif len(res) > 1:
log.warning('Failed to find unique Resource ID for CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
else:
# One unique OAI resource found -- deref and replace it...
new = 'origin-access-identity/cloudfront/{}'.format(res[0]['Id'])
DistributionConfig['Origins']['Items'][item]['S3OriginConfig']['OriginAccessIdentity'] = new
# Munge Name into the Comment field...
DistributionConfig['Comment'] = '{}:{}'.format(Name, DistributionConfig['Comment']) \
if DistributionConfig.get('Comment') else Name
# Fix up any missing (or wrong) Quantity sub-elements...
DistributionConfig = _fix_quantities(DistributionConfig)
kwargs['DistributionConfig'] = DistributionConfig
# Current state of the thing?
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, region=region,
key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
# Luckily, the `DistributionConfig` structure returned by `get_distribution()` (as a sub-
# element of `Distribution`) is identical to that returned by `get_distribution_config(),
# and as a bonus, the ETag's are ALSO compatible...
# Since "updates" are actually "replace everything from scratch" events, this implies that
# it's enough to simply determine SOME update is necessary to trigger one, rather than
# exhaustively calculating all changes needed - this makes life MUCH EASIER :)
# Thus our workflow here is:
# - check if the distribution exists
# - if it doesn't, create it fresh with the requested DistributionConfig, and Tag it if needed
# - if it does, grab its ETag, and TWO copies of the current DistributionConfig
# - merge the requested DistributionConfig on top of one of them
# - compare the copy we just merged against the one we didn't
# - if they differ, send the merged copy, along with the ETag we got, back as an update
# - lastly, verify and set/unset any Tags which may need changing...
exists = bool(res)
if not exists:
if 'CallerReference' not in kwargs['DistributionConfig']:
kwargs['DistributionConfig']['CallerReference'] = str(uuid.uuid4())
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be created.'.format(Name)
new = {'DistributionConfig': kwargs['DistributionConfig']}
new.update({'Tags': Tags}) if Tags else None
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs.update(authargs)
comments = []
res = __salt__['boto_cloudfront.create_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while creating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
new = {'DistributionConfig': res['Distribution']['DistributionConfig']}
comments += ['Created distribution `{}`.'.format(Name)]
newARN = res.get('Distribution', {}).get('ARN')
tagged = __salt__['boto_cloudfront.tag_resource'](Tags=Tags, **authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while tagging distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['Tagged distribution `{}`.'.format(Name)]
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': None, 'new': new}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_distribution_v2'](Id=currentId, **authargs)
# Insanely unlikely given that we JUST got back this Id from the previous search, but....
if not current:
msg = 'Failed to lookup CloudFront distribution with Id `{}`.'.format(currentId)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
currentDC = current['Distribution']['DistributionConfig']
currentARN = current['Distribution']['ARN']
currentETag = current['ETag']
currentTags = __salt__['boto_cloudfront.list_tags_for_resource'](Resource=currentARN,
**authargs)
copyOne = copy.deepcopy(currentDC)
copyTwo = copy.deepcopy(currentDC)
copyTwo.update(kwargs['DistributionConfig'])
correct = __utils__['boto3.json_objs_equal'](copyOne, copyTwo)
tags_correct = (currentTags == Tags)
comments = []
old = {}
new = {}
if correct and tags_correct:
ret['comment'] = 'CloudFront distribution `{}` is in the correct state.'.format(Name)
return ret
if __opts__['test']:
ret['result'] = None
if not correct:
comments += ['CloudFront distribution `{}` config would be updated.'.format(Name)]
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = copyTwo
if not tags_correct:
comments += ['CloudFront distribution `{}` Tags would be updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['pchanges'] = {'old': old, 'new': new}
return ret
if not correct:
kwargs = {'DistributionConfig': copyTwo, 'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
log.debug('Calling `boto_cloudfront.update_distribution_v2()` with **kwargs =='
' %s', kwargs)
res = __salt__['boto_cloudfront.update_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = res['Distribution']['DistributionConfig']
comments += ['CloudFront distribution `{}` config updated.'.format(Name)]
if not tags_correct:
tagged = __salt__['boto_cloudfront.enforce_tags'](Resource=currentARN, Tags=Tags,
**authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while updating Tags on distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['CloudFront distribution `{}` Tags updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': new}
return ret
def oai_bucket_policy_present(name, Bucket, OAI, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the given policy exists on an S3 bucket, granting access for the given origin access
identity to do the things specified in the policy.
name
The name of the state definition
Bucket
The S3 bucket which CloudFront needs access to. Note that this policy
is exclusive - it will be the only policy definition on the bucket (and
objects inside the bucket if you specify such permissions in the
policy). Note that this likely SHOULD reflect the bucket mentioned in
the Resource section of the Policy, but this is not enforced...
OAI
The value of `Name` passed to the state definition for the origin
access identity which will be accessing the bucket.
Policy
The full policy document which should be set on the S3 bucket. If a
``Principal`` clause is not provided in the policy, one will be
automatically added, and pointed at the correct value as dereferenced
from the OAI provided above. If one IS provided, then this is not
done, and you are responsible for providing the correct values.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_oai_s3_policy:
boto_cloudfront.oai_bucket_policy_present:
- Bucket: the_bucket_for_my_distribution
- OAI: the_OAI_I_just_created_and_attached_to_my_distribution
- Policy:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::the_bucket_for_my_distribution/*
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
oais = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=OAI, region=region, key=key, keyid=keyid, profile=profile)
if len(oais) > 1:
msg = 'Multiple origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not oais:
msg = 'No origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
canonical_user = oais[0].get('S3CanonicalUserId')
oai_id = oais[0].get('Id')
if isinstance(Policy, six.string_types):
Policy = json.loads(Policy)
for stanza in range(len(Policy.get('Statement', []))):
if 'Principal' not in Policy['Statement'][stanza]:
Policy['Statement'][stanza]['Principal'] = {"CanonicalUser": canonical_user}
bucket = __salt__['boto_s3_bucket.describe'](Bucket=Bucket, region=region, key=key,
keyid=keyid, profile=profile)
if not bucket or 'bucket' not in bucket:
msg = 'S3 bucket `{}` not found.'.format(Bucket)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
curr_policy = bucket['bucket'].get('Policy', {}).get('Policy', {}) # ?!? dunno, that's just how it gets returned...
curr_policy = json.loads(curr_policy) if isinstance(curr_policy,
six.string_types) else curr_policy
# Sooooo, you have to SUBMIT Principals of the form
# Principal: {'S3CanonicalUserId': someCrazyLongMagicValueAsDerivedAbove}
# BUT, they RETURN the Principal as something WILDLY different
# Principal: {'AWS': arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E30ABCDEF12345}
# which obviously compare different on every run... So we fake it thusly.
fake_Policy = copy.deepcopy(Policy)
for stanza in range(len(fake_Policy.get('Statement', []))):
# Warning: unavoidable hardcoded magic values HO!
fake_Policy['Statement'][stanza].update({'Principal': {'AWS':
'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity {}'.format(oai_id)}})
if __utils__['boto3.json_objs_equal'](curr_policy, fake_Policy):
msg = 'Policy of S3 bucket `{}` is in the correct state.'.format(Bucket)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['comment'] = 'Policy on S3 bucket `{}` would be updated.'.format(Bucket)
ret['result'] = None
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
res = __salt__['boto_s3_bucket.put_policy'](Bucket=Bucket, Policy=Policy,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in res:
ret['comment'] = 'Failed to update policy on S3 bucket `{}`: {}'.format(Bucket,
res['error'])
ret['return'] = False
return ret
ret['comment'] = 'Policy on S3 bucket `{}` updated.'.format(Bucket)
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
def route53_alias_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a Route53 Alias exists and is pointing at the given CloudFront
distribution. An ``A`` record is always created, and if IPV6 is enabled on
the given distribution, an ``AAAA`` record will be created as well. Also be
aware that Alias records for CloudFront distributions are only permitted in
non-private zones.
name
The name of the state definition.
Distribution
The name of the CloudFront distribution. Defaults to the value of
``name`` if not provided.
HostedZoneId
Id of the Route53 hosted zone within which the records should be created.
DomainName
The domain name associated with the Hosted Zone. Exclusive with HostedZoneId.
ResourceRecordSet
A Route53 Record Set (with AliasTarget section, suitable for use as an
``Alias`` record, if non-default settings are needed on the Alias)
which should be pointed at the provided CloudFront distribution. Note
that this MUST correlate with the Aliases set within the
DistributionConfig section of the distribution.
Some notes *specifically* about the ``AliasTarget`` subsection of the
ResourceRecordSet:
- If not specified, the ``DNSName`` sub-field will be populated by
dereferencing ``Distribution`` above to the value of its
``DomainName`` attribute.
- The HostedZoneId sub-field should not be provided -- it will be
automatically populated with a ``magic`` AWS value.
- The EvaluateTargetHealth can only be False on a CloudFront Alias.
- The above items taken all together imply that, for most use-cases,
the AliasTarget sub-section can be entirely omitted, as seen in the
first code sample below.
Lastly, note that if you set ``name`` to the desired ResourceRecordSet
Name, you can entirely omit this parameter, as shown in the second
example below.
.. code-block:: yaml
Add a Route53 Alias for my_distribution:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
- ResourceRecordSet:
Name: the-alias.saltstack.org.
# This is even simpler - it uses the value of `name` for ResourceRecordSet.Name
another-alias.saltstack.org.:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
'''
MAGIC_CLOUDFRONT_HOSTED_ZONEID = 'Z2FDTNDATAQYW2'
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
Distribution = kwargs['Distribution'] if 'Distribution' in kwargs else name
ResourceRecordSet = kwargs.get('ResourceRecordSet', {})
Name = ResourceRecordSet.get('Name', name)
ResourceRecordSet['Name'] = Name
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Distribution,
region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error resolving CloudFront distribution `{}` to a Resource ID.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'No CloudFront distibutions matching `{}` found.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
dist = res[0]
Types = ('A', 'AAAA') if dist.get('IsIPV6Enabled', False) else ('A',)
DNSName = dist.get('DomainName', '')
Aliases = dist.get('Aliases', {}).get('Items', [])
# AWS annoyance #437:
# Route53 "FQDNs" (correctly!) REQUIRE trailing periods...
# while CloudFront "FQDNs" don't PERMIT trailing periods...
Aliases += [(a if a.endswith('.') else '{}.'.format(a)) for a in Aliases]
if Name not in Aliases:
msg = ('Route53 alias `{}` requested which is not mirrored in the `Aliases`'
' sub-section of the DistributionConfig.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
changes = {'old': [], 'new': []}
comments = []
# Now mock out a route53 state def, and use the route53 rr_exists state to enforce it...
AliasTarget = ResourceRecordSet.get('AliasTarget', {})
AliasTarget['DNSName'] = AliasTarget['DNSName'] if 'DNSName' in AliasTarget else DNSName
AliasTarget['DNSName'] += '' if AliasTarget['DNSName'].endswith('.') else '.' # GRRRR!
AliasTarget['HostedZoneId'] = MAGIC_CLOUDFRONT_HOSTED_ZONEID
AliasTarget['EvaluateTargetHealth'] = False # Route53 limitation
ResourceRecordSet['name'] = Name
ResourceRecordSet['AliasTarget'] = AliasTarget
ResourceRecordSet['PrivateZone'] = False # Route53 limitation
ResourceRecordSet['DomainName'] = kwargs.get('DomainName')
ResourceRecordSet['HostedZoneId'] = kwargs.get('HostedZoneId')
ResourceRecordSet.update({'region': region, 'key': key, 'keyid': keyid, 'profile': profile})
for Type in Types:
ResourceRecordSet['Type'] = Type
# Checking for `test=True` will occur in the called state....
log.debug('Calling state function `boto3_route53.rr_present()` with args: `%s`',
ResourceRecordSet)
res = __states__['boto3_route53.rr_present'](**ResourceRecordSet)
ret['result'] = res['result']
comments += [res['comment']]
if ret['result'] not in (True, None):
break
changes['old'] += [res['changes']['old']] if res['changes'].get('old') else []
changes['new'] += [res['changes']['new']] if res['changes'].get('new') else []
ret['changes'].update({'old': changes['old']}) if changes.get('old') else None
ret['changes'].update({'new': changes['new']}) if changes.get('new') else None
ret['comment'] = ' '.join(comments)
return ret
def origin_access_identity_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity exists.
.. note::
Due to the unavailibity of ANY other way to store stateful idempotency
information about Origin Access Identities (including resource tags),
the Comment attribute (as the only user-settable attribute without
weird self-blocking semantics) is necessarily utilized to store the
Salt state signifier, which is used to determine resource existence and
state. That said, to enable SOME usability of this field, only the
value up to the first colon character is taken as the signifier, while
anything afterward is free-form and ignored by Salt.
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not provided, the value of
`name` will be used.
Comment
Free-form text description of the origin access identity.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_OAI:
boto_cloudfront.origin_access_identity_present:
- Comment: Simply ensures an OAI named my_OAI exists
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.get('Name', name)
# Munge Name into the Comment field...
Comment = '{}:{}'.format(Name, kwargs['Comment']) if kwargs.get('Comment') else Name
# Current state of the thing?
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront origin access identities matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
exists = bool(res)
if not exists:
CloudFrontOriginAccessIdentityConfig = {'Comment': Comment,
'CallerReference': str(uuid.uuid4())}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be created.'.format(Name)
new = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.create_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Failed to create CloudFront origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'Created CloudFrong origin access identity`{}`.'.format(Name)
ret['changes'] = {'old': None, 'new': res}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=currentId,
**authargs)
currentETag = current['ETag']
currentOAIC = current['CloudFrontOriginAccessIdentity']['CloudFrontOriginAccessIdentityConfig']
new = copy.deepcopy(currentOAIC)
new.update({'Comment': Comment}) # Currently the only updatable element :-/
if currentOAIC == new:
msg = 'CloudFront origin access identity `{}` is in the correct state.'.format(Name)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be updated.'.format(Name)
ret['pchanges'] = {'old': currentOAIC, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': new,
'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.update_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'CloudFront origin access identity `{}` config updated.'.format(Name)
ret['changes'] = {'old': currentOAIC, 'new': new}
return ret
def origin_access_identity_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity is absent.
name
The name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
Id (string)
The Resource ID of a CloudFront origin access identity to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure an origin access identity named my_OAI is gone:
boto_cloudfront.origin_access_identity_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
current = None
if not Id:
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, **authargs)
if current is None:
msg = 'Error dereferencing origin access identity `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(current) > 1:
msg = ('Multiple CloudFront origin access identities matched `{}`, no way to know'
' which to delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not current:
msg = 'CloudFront origin access identity `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = current[0]['Id']
if not __salt__['boto_cloudfront.cloud_front_origin_access_identity_exists'](Id=Id, **authargs):
msg = 'CloudFront origin access identity `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront origin access identity `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be deleted.'.format(ref)
ret['pchanges'] = {'old': old, 'new': None}
return ret
deleted = __salt__['boto_cloudfront.delete_cloud_front_origin_access_identity'](Id=Id,
IfMatch=old['ETag'], **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront origin access identity `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
msg = 'CloudFront origin access identity `{}` deleted.'.format(ref)
log.info(msg)
ret['comment'] = msg
ret['changes'] = {'old': old, 'new': None}
return ret
|
saltstack/salt | salt/states/boto_cloudfront.py | origin_access_identity_present | python | def origin_access_identity_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity exists.
.. note::
Due to the unavailibity of ANY other way to store stateful idempotency
information about Origin Access Identities (including resource tags),
the Comment attribute (as the only user-settable attribute without
weird self-blocking semantics) is necessarily utilized to store the
Salt state signifier, which is used to determine resource existence and
state. That said, to enable SOME usability of this field, only the
value up to the first colon character is taken as the signifier, while
anything afterward is free-form and ignored by Salt.
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not provided, the value of
`name` will be used.
Comment
Free-form text description of the origin access identity.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_OAI:
boto_cloudfront.origin_access_identity_present:
- Comment: Simply ensures an OAI named my_OAI exists
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.get('Name', name)
# Munge Name into the Comment field...
Comment = '{}:{}'.format(Name, kwargs['Comment']) if kwargs.get('Comment') else Name
# Current state of the thing?
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront origin access identities matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
exists = bool(res)
if not exists:
CloudFrontOriginAccessIdentityConfig = {'Comment': Comment,
'CallerReference': str(uuid.uuid4())}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be created.'.format(Name)
new = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.create_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Failed to create CloudFront origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'Created CloudFrong origin access identity`{}`.'.format(Name)
ret['changes'] = {'old': None, 'new': res}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=currentId,
**authargs)
currentETag = current['ETag']
currentOAIC = current['CloudFrontOriginAccessIdentity']['CloudFrontOriginAccessIdentityConfig']
new = copy.deepcopy(currentOAIC)
new.update({'Comment': Comment}) # Currently the only updatable element :-/
if currentOAIC == new:
msg = 'CloudFront origin access identity `{}` is in the correct state.'.format(Name)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be updated.'.format(Name)
ret['pchanges'] = {'old': currentOAIC, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': new,
'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.update_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'CloudFront origin access identity `{}` config updated.'.format(Name)
ret['changes'] = {'old': currentOAIC, 'new': new}
return ret | Ensure a given CloudFront Origin Access Identity exists.
.. note::
Due to the unavailibity of ANY other way to store stateful idempotency
information about Origin Access Identities (including resource tags),
the Comment attribute (as the only user-settable attribute without
weird self-blocking semantics) is necessarily utilized to store the
Salt state signifier, which is used to determine resource existence and
state. That said, to enable SOME usability of this field, only the
value up to the first colon character is taken as the signifier, while
anything afterward is free-form and ignored by Salt.
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not provided, the value of
`name` will be used.
Comment
Free-form text description of the origin access identity.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_OAI:
boto_cloudfront.origin_access_identity_present:
- Comment: Simply ensures an OAI named my_OAI exists | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudfront.py#L958-L1078 | null | # -*- coding: utf-8 -*-
'''
Manage CloudFront distributions
.. versionadded:: 2018.3.0
Create, update and destroy CloudFront distributions.
This module accepts explicit AWS credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API
and no further configuration is necessary.
More information available `here
<https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them,
either in a pillar file or in the minion's config file:
.. code-block:: yaml
cloudfront.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudfront.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid``, and ``region`` via a profile,
either passed in as a dict, or a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
aws:
region:
us-east-1:
profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import uuid
import copy
import json
# Import Salt conveniences
from salt.ext import six
from salt.ext.six.moves import range
#pylint: disable=W0106
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
if 'boto_cloudfront.get_distribution' not in __salt__:
msg = 'The boto_cloudfront state module could not be loaded: {}.'
return (False, msg.format('boto_cloudfront exec module unavailable.'))
return 'boto_cloudfront'
def present(
name,
config,
tags,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the CloudFront distribution is present.
name (string)
Name of the CloudFront distribution
config (dict)
Configuration for the distribution
tags (dict)
Tags to associate with the distribution
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
Example:
.. code-block:: yaml
Manage my_distribution CloudFront distribution:
boto_cloudfront.present:
- name: my_distribution
- config:
Comment: 'partial config shown, most parameters elided'
Enabled: True
- tags:
testing_key: testing_value
'''
ret = {
'name': name,
'comment': '',
'changes': {},
}
res = __salt__['boto_cloudfront.get_distribution'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error checking distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
old = res['result']
if old is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Distribution {0} set for creation.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
res = __salt__['boto_cloudfront.create_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error creating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Created distribution {0}.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
else:
full_config_old = {
'config': old['distribution']['DistributionConfig'],
'tags': old['tags'],
}
full_config_new = {
'config': config,
'tags': tags,
}
diffed_config = __utils__['dictdiffer.deep_diff'](
full_config_old,
full_config_new,
)
def _yaml_safe_dump(attrs):
'''
Safely dump YAML using a readable flow style
'''
dumper_name = 'IndentedSafeOrderedDumper'
dumper = __utils__['yaml.get_dumper'](dumper_name)
return __utils__['yaml.dump'](
attrs,
default_flow_style=False,
Dumper=dumper)
changes_diff = ''.join(difflib.unified_diff(
_yaml_safe_dump(full_config_old).splitlines(True),
_yaml_safe_dump(full_config_new).splitlines(True),
))
any_changes = bool('old' in diffed_config or 'new' in diffed_config)
if not any_changes:
ret['result'] = True
ret['comment'] = 'Distribution {0} has correct config.'.format(
name,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join([
'Distribution {0} set for new config:'.format(name),
changes_diff,
])
ret['changes'] = {'diff': changes_diff}
return ret
res = __salt__['boto_cloudfront.update_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error updating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Updated distribution {0}.'.format(name)
ret['changes'] = {'diff': changes_diff}
return ret
def _fix_quantities(tree):
'''
Stupidly simple function to fix any Items/Quantity disparities inside a
DistributionConfig block before use. Since AWS only accepts JSON-encodable
data types, this implementation is "good enough" for our purposes.
'''
if isinstance(tree, dict):
tree = {k: _fix_quantities(v) for k, v in tree.items()}
if isinstance(tree.get('Items'), list):
tree['Quantity'] = len(tree['Items'])
if not tree['Items']:
tree.pop('Items') # Silly, but AWS requires it....
return tree
elif isinstance(tree, list):
return [_fix_quantities(t) for t in tree]
else:
return tree
def distribution_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure the given CloudFront distribution exists in the described state.
The implementation of this function, and all those following, is orthagonal
to that of :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>`. Resources created with
:py:mod:`boto_cloudfront.present <salt.states.boto_cloudfront.present>`
will not be correctly managed by this function, as a different method is
used to store Salt's state signifier. This function and those following are
a suite, designed to work together. As an extra bonus, they correctly
process updates of the managed resources, so it is recommended to use them
in preference to :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>` above.
Note that the semantics of DistributionConfig (below) are rather arcane,
and vary wildly depending on whether the distribution already exists or not
(e.g. is being initially created, or being updated in place). Many more
details can be found here__.
.. __: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-overview-required-fields.html
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
DistributionConfig (dict)
Configuration for the distribution.
Notes:
- The CallerReference field should NOT be provided - it will be
autopopulated by Salt.
- A large number of sub- (and sub-sub-) fields require a ``Quantity``
element, which simply COUNTS the number of items in the ``Items``
element. This is bluntly stupid, so as a convenience, Salt will
traverse the provided configuration, and add (or fix) a ``Quantity``
element for any ``Items`` elements of list-type it encounters. This
adds a bit of sanity to an otherwise error-prone situation. Note
that for this to work, zero-length lists must be inlined as ``[]``.
- Due to the unavailibity of a better way to store stateful idempotency
information about Distributions, the Comment sub-element (as the only
user-settable attribute without weird self-blocking semantics, and
which is available from the core ``get_distribution()`` API call) is
utilized to store the Salt state signifier, which is used to
determine resource existence and state. That said, to enable **some**
usability of this field, only the value up to the first colon
character is taken as the signifier, with everything afterward
free-form, and ignored (but preserved) by Salt.
Tags (dict)
Tags to associate with the distribution.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
plt-dev-spaapi-cf-dist-cf_dist-present:
boto_cloudfront.distribution_present:
- Name: plt-dev-spaapi-cf-dist
- DistributionConfig:
Comment: SPA
Logging:
Enabled: false
Prefix: ''
Bucket: ''
IncludeCookies: false
WebACLId: ''
Origins:
Items:
- S3OriginConfig:
OriginAccessIdentity: the-SPA-OAI
OriginPath: ''
CustomHeaders:
Items: []
Id: S3-hs-backend-srpms
DomainName: hs-backend-srpms.s3.amazonaws.com
PriceClass: PriceClass_All
DefaultRootObject: ''
Enabled: true
DefaultCacheBehavior:
ViewerProtocolPolicy: allow-all
TrustedSigners:
Items: []
Enabled: false
SmoothStreaming: false
TargetOriginId: S3-hs-backend-srpms
FieldLevelEncryptionId: ''
ForwardedValues:
Headers:
Items: []
Cookies:
Forward: none
QueryStringCacheKeys:
Items: []
QueryString: false
MaxTTL: 31536000
LambdaFunctionAssociations:
Items: []
DefaultTTL: 86400
AllowedMethods:
CachedMethods:
Items:
- HEAD
- GET
Items:
- HEAD
- GET
MinTTL: 0
Compress: false
IsIPV6Enabled: true
ViewerCertificate:
CloudFrontDefaultCertificate: true
MinimumProtocolVersion: TLSv1
CertificateSource: cloudfront
Aliases:
Items:
- bubba-hotep.bodhi-dev.io
HttpVersion: http2
- Tags:
Owner: dev_engrs
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.pop('Name', name)
Tags = kwargs.pop('Tags', None)
DistributionConfig = kwargs.get('DistributionConfig', {})
## Sub-element munging on config data should go in here, before we proceed:
# For instance, origin access identities must be of the form
# `origin-access-identity/cloudfront/ID-of-origin-access-identity`, but we can't really
# know that ID apriori, so any OAI state names inside the config data must be resolved
# and converted into that format before submission. Be aware that the `state names` of
# salt managed OAIs are stored in their Comment fields for lack of any better place...
for item in range(len(DistributionConfig.get('Origins', {}).get('Items', []))):
oai = DistributionConfig['Origins']['Items'][item].get('S3OriginConfig',
{}).get('OriginAccessIdentity', '')
if oai and not oai.startswith('origin-access-identity/cloudfront/'):
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=oai, region=region, key=key, keyid=keyid, profile=profile)
if res is None: # An error occurred, bubble it up...
log.warning('Error encountered while trying to determine the Resource ID of'
' CloudFront origin access identity `%s`. Passing as-is.', oai)
elif not res:
log.warning('Failed to determine the Resource ID of CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
elif len(res) > 1:
log.warning('Failed to find unique Resource ID for CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
else:
# One unique OAI resource found -- deref and replace it...
new = 'origin-access-identity/cloudfront/{}'.format(res[0]['Id'])
DistributionConfig['Origins']['Items'][item]['S3OriginConfig']['OriginAccessIdentity'] = new
# Munge Name into the Comment field...
DistributionConfig['Comment'] = '{}:{}'.format(Name, DistributionConfig['Comment']) \
if DistributionConfig.get('Comment') else Name
# Fix up any missing (or wrong) Quantity sub-elements...
DistributionConfig = _fix_quantities(DistributionConfig)
kwargs['DistributionConfig'] = DistributionConfig
# Current state of the thing?
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, region=region,
key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
# Luckily, the `DistributionConfig` structure returned by `get_distribution()` (as a sub-
# element of `Distribution`) is identical to that returned by `get_distribution_config(),
# and as a bonus, the ETag's are ALSO compatible...
# Since "updates" are actually "replace everything from scratch" events, this implies that
# it's enough to simply determine SOME update is necessary to trigger one, rather than
# exhaustively calculating all changes needed - this makes life MUCH EASIER :)
# Thus our workflow here is:
# - check if the distribution exists
# - if it doesn't, create it fresh with the requested DistributionConfig, and Tag it if needed
# - if it does, grab its ETag, and TWO copies of the current DistributionConfig
# - merge the requested DistributionConfig on top of one of them
# - compare the copy we just merged against the one we didn't
# - if they differ, send the merged copy, along with the ETag we got, back as an update
# - lastly, verify and set/unset any Tags which may need changing...
exists = bool(res)
if not exists:
if 'CallerReference' not in kwargs['DistributionConfig']:
kwargs['DistributionConfig']['CallerReference'] = str(uuid.uuid4())
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be created.'.format(Name)
new = {'DistributionConfig': kwargs['DistributionConfig']}
new.update({'Tags': Tags}) if Tags else None
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs.update(authargs)
comments = []
res = __salt__['boto_cloudfront.create_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while creating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
new = {'DistributionConfig': res['Distribution']['DistributionConfig']}
comments += ['Created distribution `{}`.'.format(Name)]
newARN = res.get('Distribution', {}).get('ARN')
tagged = __salt__['boto_cloudfront.tag_resource'](Tags=Tags, **authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while tagging distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['Tagged distribution `{}`.'.format(Name)]
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': None, 'new': new}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_distribution_v2'](Id=currentId, **authargs)
# Insanely unlikely given that we JUST got back this Id from the previous search, but....
if not current:
msg = 'Failed to lookup CloudFront distribution with Id `{}`.'.format(currentId)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
currentDC = current['Distribution']['DistributionConfig']
currentARN = current['Distribution']['ARN']
currentETag = current['ETag']
currentTags = __salt__['boto_cloudfront.list_tags_for_resource'](Resource=currentARN,
**authargs)
copyOne = copy.deepcopy(currentDC)
copyTwo = copy.deepcopy(currentDC)
copyTwo.update(kwargs['DistributionConfig'])
correct = __utils__['boto3.json_objs_equal'](copyOne, copyTwo)
tags_correct = (currentTags == Tags)
comments = []
old = {}
new = {}
if correct and tags_correct:
ret['comment'] = 'CloudFront distribution `{}` is in the correct state.'.format(Name)
return ret
if __opts__['test']:
ret['result'] = None
if not correct:
comments += ['CloudFront distribution `{}` config would be updated.'.format(Name)]
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = copyTwo
if not tags_correct:
comments += ['CloudFront distribution `{}` Tags would be updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['pchanges'] = {'old': old, 'new': new}
return ret
if not correct:
kwargs = {'DistributionConfig': copyTwo, 'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
log.debug('Calling `boto_cloudfront.update_distribution_v2()` with **kwargs =='
' %s', kwargs)
res = __salt__['boto_cloudfront.update_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = res['Distribution']['DistributionConfig']
comments += ['CloudFront distribution `{}` config updated.'.format(Name)]
if not tags_correct:
tagged = __salt__['boto_cloudfront.enforce_tags'](Resource=currentARN, Tags=Tags,
**authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while updating Tags on distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['CloudFront distribution `{}` Tags updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': new}
return ret
def oai_bucket_policy_present(name, Bucket, OAI, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the given policy exists on an S3 bucket, granting access for the given origin access
identity to do the things specified in the policy.
name
The name of the state definition
Bucket
The S3 bucket which CloudFront needs access to. Note that this policy
is exclusive - it will be the only policy definition on the bucket (and
objects inside the bucket if you specify such permissions in the
policy). Note that this likely SHOULD reflect the bucket mentioned in
the Resource section of the Policy, but this is not enforced...
OAI
The value of `Name` passed to the state definition for the origin
access identity which will be accessing the bucket.
Policy
The full policy document which should be set on the S3 bucket. If a
``Principal`` clause is not provided in the policy, one will be
automatically added, and pointed at the correct value as dereferenced
from the OAI provided above. If one IS provided, then this is not
done, and you are responsible for providing the correct values.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_oai_s3_policy:
boto_cloudfront.oai_bucket_policy_present:
- Bucket: the_bucket_for_my_distribution
- OAI: the_OAI_I_just_created_and_attached_to_my_distribution
- Policy:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::the_bucket_for_my_distribution/*
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
oais = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=OAI, region=region, key=key, keyid=keyid, profile=profile)
if len(oais) > 1:
msg = 'Multiple origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not oais:
msg = 'No origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
canonical_user = oais[0].get('S3CanonicalUserId')
oai_id = oais[0].get('Id')
if isinstance(Policy, six.string_types):
Policy = json.loads(Policy)
for stanza in range(len(Policy.get('Statement', []))):
if 'Principal' not in Policy['Statement'][stanza]:
Policy['Statement'][stanza]['Principal'] = {"CanonicalUser": canonical_user}
bucket = __salt__['boto_s3_bucket.describe'](Bucket=Bucket, region=region, key=key,
keyid=keyid, profile=profile)
if not bucket or 'bucket' not in bucket:
msg = 'S3 bucket `{}` not found.'.format(Bucket)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
curr_policy = bucket['bucket'].get('Policy', {}).get('Policy', {}) # ?!? dunno, that's just how it gets returned...
curr_policy = json.loads(curr_policy) if isinstance(curr_policy,
six.string_types) else curr_policy
# Sooooo, you have to SUBMIT Principals of the form
# Principal: {'S3CanonicalUserId': someCrazyLongMagicValueAsDerivedAbove}
# BUT, they RETURN the Principal as something WILDLY different
# Principal: {'AWS': arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E30ABCDEF12345}
# which obviously compare different on every run... So we fake it thusly.
fake_Policy = copy.deepcopy(Policy)
for stanza in range(len(fake_Policy.get('Statement', []))):
# Warning: unavoidable hardcoded magic values HO!
fake_Policy['Statement'][stanza].update({'Principal': {'AWS':
'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity {}'.format(oai_id)}})
if __utils__['boto3.json_objs_equal'](curr_policy, fake_Policy):
msg = 'Policy of S3 bucket `{}` is in the correct state.'.format(Bucket)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['comment'] = 'Policy on S3 bucket `{}` would be updated.'.format(Bucket)
ret['result'] = None
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
res = __salt__['boto_s3_bucket.put_policy'](Bucket=Bucket, Policy=Policy,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in res:
ret['comment'] = 'Failed to update policy on S3 bucket `{}`: {}'.format(Bucket,
res['error'])
ret['return'] = False
return ret
ret['comment'] = 'Policy on S3 bucket `{}` updated.'.format(Bucket)
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
def route53_alias_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a Route53 Alias exists and is pointing at the given CloudFront
distribution. An ``A`` record is always created, and if IPV6 is enabled on
the given distribution, an ``AAAA`` record will be created as well. Also be
aware that Alias records for CloudFront distributions are only permitted in
non-private zones.
name
The name of the state definition.
Distribution
The name of the CloudFront distribution. Defaults to the value of
``name`` if not provided.
HostedZoneId
Id of the Route53 hosted zone within which the records should be created.
DomainName
The domain name associated with the Hosted Zone. Exclusive with HostedZoneId.
ResourceRecordSet
A Route53 Record Set (with AliasTarget section, suitable for use as an
``Alias`` record, if non-default settings are needed on the Alias)
which should be pointed at the provided CloudFront distribution. Note
that this MUST correlate with the Aliases set within the
DistributionConfig section of the distribution.
Some notes *specifically* about the ``AliasTarget`` subsection of the
ResourceRecordSet:
- If not specified, the ``DNSName`` sub-field will be populated by
dereferencing ``Distribution`` above to the value of its
``DomainName`` attribute.
- The HostedZoneId sub-field should not be provided -- it will be
automatically populated with a ``magic`` AWS value.
- The EvaluateTargetHealth can only be False on a CloudFront Alias.
- The above items taken all together imply that, for most use-cases,
the AliasTarget sub-section can be entirely omitted, as seen in the
first code sample below.
Lastly, note that if you set ``name`` to the desired ResourceRecordSet
Name, you can entirely omit this parameter, as shown in the second
example below.
.. code-block:: yaml
Add a Route53 Alias for my_distribution:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
- ResourceRecordSet:
Name: the-alias.saltstack.org.
# This is even simpler - it uses the value of `name` for ResourceRecordSet.Name
another-alias.saltstack.org.:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
'''
MAGIC_CLOUDFRONT_HOSTED_ZONEID = 'Z2FDTNDATAQYW2'
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
Distribution = kwargs['Distribution'] if 'Distribution' in kwargs else name
ResourceRecordSet = kwargs.get('ResourceRecordSet', {})
Name = ResourceRecordSet.get('Name', name)
ResourceRecordSet['Name'] = Name
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Distribution,
region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error resolving CloudFront distribution `{}` to a Resource ID.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'No CloudFront distibutions matching `{}` found.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
dist = res[0]
Types = ('A', 'AAAA') if dist.get('IsIPV6Enabled', False) else ('A',)
DNSName = dist.get('DomainName', '')
Aliases = dist.get('Aliases', {}).get('Items', [])
# AWS annoyance #437:
# Route53 "FQDNs" (correctly!) REQUIRE trailing periods...
# while CloudFront "FQDNs" don't PERMIT trailing periods...
Aliases += [(a if a.endswith('.') else '{}.'.format(a)) for a in Aliases]
if Name not in Aliases:
msg = ('Route53 alias `{}` requested which is not mirrored in the `Aliases`'
' sub-section of the DistributionConfig.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
changes = {'old': [], 'new': []}
comments = []
# Now mock out a route53 state def, and use the route53 rr_exists state to enforce it...
AliasTarget = ResourceRecordSet.get('AliasTarget', {})
AliasTarget['DNSName'] = AliasTarget['DNSName'] if 'DNSName' in AliasTarget else DNSName
AliasTarget['DNSName'] += '' if AliasTarget['DNSName'].endswith('.') else '.' # GRRRR!
AliasTarget['HostedZoneId'] = MAGIC_CLOUDFRONT_HOSTED_ZONEID
AliasTarget['EvaluateTargetHealth'] = False # Route53 limitation
ResourceRecordSet['name'] = Name
ResourceRecordSet['AliasTarget'] = AliasTarget
ResourceRecordSet['PrivateZone'] = False # Route53 limitation
ResourceRecordSet['DomainName'] = kwargs.get('DomainName')
ResourceRecordSet['HostedZoneId'] = kwargs.get('HostedZoneId')
ResourceRecordSet.update({'region': region, 'key': key, 'keyid': keyid, 'profile': profile})
for Type in Types:
ResourceRecordSet['Type'] = Type
# Checking for `test=True` will occur in the called state....
log.debug('Calling state function `boto3_route53.rr_present()` with args: `%s`',
ResourceRecordSet)
res = __states__['boto3_route53.rr_present'](**ResourceRecordSet)
ret['result'] = res['result']
comments += [res['comment']]
if ret['result'] not in (True, None):
break
changes['old'] += [res['changes']['old']] if res['changes'].get('old') else []
changes['new'] += [res['changes']['new']] if res['changes'].get('new') else []
ret['changes'].update({'old': changes['old']}) if changes.get('old') else None
ret['changes'].update({'new': changes['new']}) if changes.get('new') else None
ret['comment'] = ' '.join(comments)
return ret
def distribution_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
distribution's status to Disabled, and once that returns success, to then
delete the resource. THIS CAN TAKE SOME TIME, so be patient :)
name (string)
Name of the state definition.
Name (string)
Name of the CloudFront distribution to be managed. If not provided, the
value of ``name`` will be used as a default. The purpose of this
parameter is only to resolve it to a Resource ID, so be aware that an
explicit value for ``Id`` below will override any value provided, or
defaulted, here.
Id (string)
The Resource ID of a CloudFront distribution to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure a distribution named my_distribution is gone:
boto_cloudfront.distribution_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
if not Id:
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, **authargs)
if res is None:
msg = 'Error dereferencing CloudFront distribution `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = ('Multiple CloudFront distibutions matched `{}`, no way to know which to'
' delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'CloudFront Distribution `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = res[0]['Id']
if not __salt__['boto_cloudfront.distribution_exists'](Id=Id, **authargs):
msg = 'CloudFront distribution `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_distribution_v2'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront distribution `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
currETag = old['ETag']
Enabled = old['DistributionConfig']['Enabled']
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be {}deleted.'.format(ref,
('disabled and ' if Enabled else ''))
ret['pchanges'] = {'old': old, 'new': None}
return ret
comments = []
if Enabled:
disabled = __salt__['boto_cloudfront.disable_distribution'](Id=Id, **authargs)
if disabled is None:
ret['result'] = False
msg = 'Error disabling CloudFront distribution `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
comments += ['CloudFront distribution `{}` disabled.'.format(ref)]
currETag = disabled['ETag']
deleted = __salt__['boto_cloudfront.delete_distribution'](Id=Id, IfMatch=currETag, **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront distribution `{}`'.format(ref)
comments += [msg]
log.error(msg)
ret['comment'] = ' '.join(comments)
return ret
msg = 'CloudFront distribution `{}` deleted.'.format(ref)
comments += [msg]
log.info(msg)
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': None}
return ret
def origin_access_identity_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity is absent.
name
The name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
Id (string)
The Resource ID of a CloudFront origin access identity to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure an origin access identity named my_OAI is gone:
boto_cloudfront.origin_access_identity_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
current = None
if not Id:
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, **authargs)
if current is None:
msg = 'Error dereferencing origin access identity `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(current) > 1:
msg = ('Multiple CloudFront origin access identities matched `{}`, no way to know'
' which to delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not current:
msg = 'CloudFront origin access identity `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = current[0]['Id']
if not __salt__['boto_cloudfront.cloud_front_origin_access_identity_exists'](Id=Id, **authargs):
msg = 'CloudFront origin access identity `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront origin access identity `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be deleted.'.format(ref)
ret['pchanges'] = {'old': old, 'new': None}
return ret
deleted = __salt__['boto_cloudfront.delete_cloud_front_origin_access_identity'](Id=Id,
IfMatch=old['ETag'], **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront origin access identity `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
msg = 'CloudFront origin access identity `{}` deleted.'.format(ref)
log.info(msg)
ret['comment'] = msg
ret['changes'] = {'old': old, 'new': None}
return ret
|
saltstack/salt | salt/states/boto_cloudfront.py | origin_access_identity_absent | python | def origin_access_identity_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity is absent.
name
The name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
Id (string)
The Resource ID of a CloudFront origin access identity to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure an origin access identity named my_OAI is gone:
boto_cloudfront.origin_access_identity_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
current = None
if not Id:
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, **authargs)
if current is None:
msg = 'Error dereferencing origin access identity `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(current) > 1:
msg = ('Multiple CloudFront origin access identities matched `{}`, no way to know'
' which to delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not current:
msg = 'CloudFront origin access identity `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = current[0]['Id']
if not __salt__['boto_cloudfront.cloud_front_origin_access_identity_exists'](Id=Id, **authargs):
msg = 'CloudFront origin access identity `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront origin access identity `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be deleted.'.format(ref)
ret['pchanges'] = {'old': old, 'new': None}
return ret
deleted = __salt__['boto_cloudfront.delete_cloud_front_origin_access_identity'](Id=Id,
IfMatch=old['ETag'], **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront origin access identity `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
msg = 'CloudFront origin access identity `{}` deleted.'.format(ref)
log.info(msg)
ret['comment'] = msg
ret['changes'] = {'old': old, 'new': None}
return ret | Ensure a given CloudFront Origin Access Identity is absent.
name
The name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
Id (string)
The Resource ID of a CloudFront origin access identity to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure an origin access identity named my_OAI is gone:
boto_cloudfront.origin_access_identity_absent:
- Name: my_distribution | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudfront.py#L1081-L1178 | null | # -*- coding: utf-8 -*-
'''
Manage CloudFront distributions
.. versionadded:: 2018.3.0
Create, update and destroy CloudFront distributions.
This module accepts explicit AWS credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API
and no further configuration is necessary.
More information available `here
<https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them,
either in a pillar file or in the minion's config file:
.. code-block:: yaml
cloudfront.keyid: GKTADJGHEIQSXMKKRBJ08H
cloudfront.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid``, and ``region`` via a profile,
either passed in as a dict, or a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
aws:
region:
us-east-1:
profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto3
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import difflib
import logging
import uuid
import copy
import json
# Import Salt conveniences
from salt.ext import six
from salt.ext.six.moves import range
#pylint: disable=W0106
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
if 'boto_cloudfront.get_distribution' not in __salt__:
msg = 'The boto_cloudfront state module could not be loaded: {}.'
return (False, msg.format('boto_cloudfront exec module unavailable.'))
return 'boto_cloudfront'
def present(
name,
config,
tags,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the CloudFront distribution is present.
name (string)
Name of the CloudFront distribution
config (dict)
Configuration for the distribution
tags (dict)
Tags to associate with the distribution
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
Example:
.. code-block:: yaml
Manage my_distribution CloudFront distribution:
boto_cloudfront.present:
- name: my_distribution
- config:
Comment: 'partial config shown, most parameters elided'
Enabled: True
- tags:
testing_key: testing_value
'''
ret = {
'name': name,
'comment': '',
'changes': {},
}
res = __salt__['boto_cloudfront.get_distribution'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error checking distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
old = res['result']
if old is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Distribution {0} set for creation.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
res = __salt__['boto_cloudfront.create_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error creating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Created distribution {0}.'.format(name)
ret['changes'] = {'old': None, 'new': name}
return ret
else:
full_config_old = {
'config': old['distribution']['DistributionConfig'],
'tags': old['tags'],
}
full_config_new = {
'config': config,
'tags': tags,
}
diffed_config = __utils__['dictdiffer.deep_diff'](
full_config_old,
full_config_new,
)
def _yaml_safe_dump(attrs):
'''
Safely dump YAML using a readable flow style
'''
dumper_name = 'IndentedSafeOrderedDumper'
dumper = __utils__['yaml.get_dumper'](dumper_name)
return __utils__['yaml.dump'](
attrs,
default_flow_style=False,
Dumper=dumper)
changes_diff = ''.join(difflib.unified_diff(
_yaml_safe_dump(full_config_old).splitlines(True),
_yaml_safe_dump(full_config_new).splitlines(True),
))
any_changes = bool('old' in diffed_config or 'new' in diffed_config)
if not any_changes:
ret['result'] = True
ret['comment'] = 'Distribution {0} has correct config.'.format(
name,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = '\n'.join([
'Distribution {0} set for new config:'.format(name),
changes_diff,
])
ret['changes'] = {'diff': changes_diff}
return ret
res = __salt__['boto_cloudfront.update_distribution'](
name,
config,
tags,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in res:
ret['result'] = False
ret['comment'] = 'Error updating distribution {0}: {1}'.format(
name,
res['error'],
)
return ret
ret['result'] = True
ret['comment'] = 'Updated distribution {0}.'.format(name)
ret['changes'] = {'diff': changes_diff}
return ret
def _fix_quantities(tree):
'''
Stupidly simple function to fix any Items/Quantity disparities inside a
DistributionConfig block before use. Since AWS only accepts JSON-encodable
data types, this implementation is "good enough" for our purposes.
'''
if isinstance(tree, dict):
tree = {k: _fix_quantities(v) for k, v in tree.items()}
if isinstance(tree.get('Items'), list):
tree['Quantity'] = len(tree['Items'])
if not tree['Items']:
tree.pop('Items') # Silly, but AWS requires it....
return tree
elif isinstance(tree, list):
return [_fix_quantities(t) for t in tree]
else:
return tree
def distribution_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure the given CloudFront distribution exists in the described state.
The implementation of this function, and all those following, is orthagonal
to that of :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>`. Resources created with
:py:mod:`boto_cloudfront.present <salt.states.boto_cloudfront.present>`
will not be correctly managed by this function, as a different method is
used to store Salt's state signifier. This function and those following are
a suite, designed to work together. As an extra bonus, they correctly
process updates of the managed resources, so it is recommended to use them
in preference to :py:mod:`boto_cloudfront.present
<salt.states.boto_cloudfront.present>` above.
Note that the semantics of DistributionConfig (below) are rather arcane,
and vary wildly depending on whether the distribution already exists or not
(e.g. is being initially created, or being updated in place). Many more
details can be found here__.
.. __: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-overview-required-fields.html
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not
provided, the value of ``name`` will be used.
DistributionConfig (dict)
Configuration for the distribution.
Notes:
- The CallerReference field should NOT be provided - it will be
autopopulated by Salt.
- A large number of sub- (and sub-sub-) fields require a ``Quantity``
element, which simply COUNTS the number of items in the ``Items``
element. This is bluntly stupid, so as a convenience, Salt will
traverse the provided configuration, and add (or fix) a ``Quantity``
element for any ``Items`` elements of list-type it encounters. This
adds a bit of sanity to an otherwise error-prone situation. Note
that for this to work, zero-length lists must be inlined as ``[]``.
- Due to the unavailibity of a better way to store stateful idempotency
information about Distributions, the Comment sub-element (as the only
user-settable attribute without weird self-blocking semantics, and
which is available from the core ``get_distribution()`` API call) is
utilized to store the Salt state signifier, which is used to
determine resource existence and state. That said, to enable **some**
usability of this field, only the value up to the first colon
character is taken as the signifier, with everything afterward
free-form, and ignored (but preserved) by Salt.
Tags (dict)
Tags to associate with the distribution.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
plt-dev-spaapi-cf-dist-cf_dist-present:
boto_cloudfront.distribution_present:
- Name: plt-dev-spaapi-cf-dist
- DistributionConfig:
Comment: SPA
Logging:
Enabled: false
Prefix: ''
Bucket: ''
IncludeCookies: false
WebACLId: ''
Origins:
Items:
- S3OriginConfig:
OriginAccessIdentity: the-SPA-OAI
OriginPath: ''
CustomHeaders:
Items: []
Id: S3-hs-backend-srpms
DomainName: hs-backend-srpms.s3.amazonaws.com
PriceClass: PriceClass_All
DefaultRootObject: ''
Enabled: true
DefaultCacheBehavior:
ViewerProtocolPolicy: allow-all
TrustedSigners:
Items: []
Enabled: false
SmoothStreaming: false
TargetOriginId: S3-hs-backend-srpms
FieldLevelEncryptionId: ''
ForwardedValues:
Headers:
Items: []
Cookies:
Forward: none
QueryStringCacheKeys:
Items: []
QueryString: false
MaxTTL: 31536000
LambdaFunctionAssociations:
Items: []
DefaultTTL: 86400
AllowedMethods:
CachedMethods:
Items:
- HEAD
- GET
Items:
- HEAD
- GET
MinTTL: 0
Compress: false
IsIPV6Enabled: true
ViewerCertificate:
CloudFrontDefaultCertificate: true
MinimumProtocolVersion: TLSv1
CertificateSource: cloudfront
Aliases:
Items:
- bubba-hotep.bodhi-dev.io
HttpVersion: http2
- Tags:
Owner: dev_engrs
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.pop('Name', name)
Tags = kwargs.pop('Tags', None)
DistributionConfig = kwargs.get('DistributionConfig', {})
## Sub-element munging on config data should go in here, before we proceed:
# For instance, origin access identities must be of the form
# `origin-access-identity/cloudfront/ID-of-origin-access-identity`, but we can't really
# know that ID apriori, so any OAI state names inside the config data must be resolved
# and converted into that format before submission. Be aware that the `state names` of
# salt managed OAIs are stored in their Comment fields for lack of any better place...
for item in range(len(DistributionConfig.get('Origins', {}).get('Items', []))):
oai = DistributionConfig['Origins']['Items'][item].get('S3OriginConfig',
{}).get('OriginAccessIdentity', '')
if oai and not oai.startswith('origin-access-identity/cloudfront/'):
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=oai, region=region, key=key, keyid=keyid, profile=profile)
if res is None: # An error occurred, bubble it up...
log.warning('Error encountered while trying to determine the Resource ID of'
' CloudFront origin access identity `%s`. Passing as-is.', oai)
elif not res:
log.warning('Failed to determine the Resource ID of CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
elif len(res) > 1:
log.warning('Failed to find unique Resource ID for CloudFront origin access'
' identity `%s`. Passing as-is.', oai)
else:
# One unique OAI resource found -- deref and replace it...
new = 'origin-access-identity/cloudfront/{}'.format(res[0]['Id'])
DistributionConfig['Origins']['Items'][item]['S3OriginConfig']['OriginAccessIdentity'] = new
# Munge Name into the Comment field...
DistributionConfig['Comment'] = '{}:{}'.format(Name, DistributionConfig['Comment']) \
if DistributionConfig.get('Comment') else Name
# Fix up any missing (or wrong) Quantity sub-elements...
DistributionConfig = _fix_quantities(DistributionConfig)
kwargs['DistributionConfig'] = DistributionConfig
# Current state of the thing?
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, region=region,
key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
# Luckily, the `DistributionConfig` structure returned by `get_distribution()` (as a sub-
# element of `Distribution`) is identical to that returned by `get_distribution_config(),
# and as a bonus, the ETag's are ALSO compatible...
# Since "updates" are actually "replace everything from scratch" events, this implies that
# it's enough to simply determine SOME update is necessary to trigger one, rather than
# exhaustively calculating all changes needed - this makes life MUCH EASIER :)
# Thus our workflow here is:
# - check if the distribution exists
# - if it doesn't, create it fresh with the requested DistributionConfig, and Tag it if needed
# - if it does, grab its ETag, and TWO copies of the current DistributionConfig
# - merge the requested DistributionConfig on top of one of them
# - compare the copy we just merged against the one we didn't
# - if they differ, send the merged copy, along with the ETag we got, back as an update
# - lastly, verify and set/unset any Tags which may need changing...
exists = bool(res)
if not exists:
if 'CallerReference' not in kwargs['DistributionConfig']:
kwargs['DistributionConfig']['CallerReference'] = str(uuid.uuid4())
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be created.'.format(Name)
new = {'DistributionConfig': kwargs['DistributionConfig']}
new.update({'Tags': Tags}) if Tags else None
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs.update(authargs)
comments = []
res = __salt__['boto_cloudfront.create_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while creating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
new = {'DistributionConfig': res['Distribution']['DistributionConfig']}
comments += ['Created distribution `{}`.'.format(Name)]
newARN = res.get('Distribution', {}).get('ARN')
tagged = __salt__['boto_cloudfront.tag_resource'](Tags=Tags, **authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while tagging distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['Tagged distribution `{}`.'.format(Name)]
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': None, 'new': new}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_distribution_v2'](Id=currentId, **authargs)
# Insanely unlikely given that we JUST got back this Id from the previous search, but....
if not current:
msg = 'Failed to lookup CloudFront distribution with Id `{}`.'.format(currentId)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
currentDC = current['Distribution']['DistributionConfig']
currentARN = current['Distribution']['ARN']
currentETag = current['ETag']
currentTags = __salt__['boto_cloudfront.list_tags_for_resource'](Resource=currentARN,
**authargs)
copyOne = copy.deepcopy(currentDC)
copyTwo = copy.deepcopy(currentDC)
copyTwo.update(kwargs['DistributionConfig'])
correct = __utils__['boto3.json_objs_equal'](copyOne, copyTwo)
tags_correct = (currentTags == Tags)
comments = []
old = {}
new = {}
if correct and tags_correct:
ret['comment'] = 'CloudFront distribution `{}` is in the correct state.'.format(Name)
return ret
if __opts__['test']:
ret['result'] = None
if not correct:
comments += ['CloudFront distribution `{}` config would be updated.'.format(Name)]
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = copyTwo
if not tags_correct:
comments += ['CloudFront distribution `{}` Tags would be updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['pchanges'] = {'old': old, 'new': new}
return ret
if not correct:
kwargs = {'DistributionConfig': copyTwo, 'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
log.debug('Calling `boto_cloudfront.update_distribution_v2()` with **kwargs =='
' %s', kwargs)
res = __salt__['boto_cloudfront.update_distribution_v2'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating distribution `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
old['DistributionConfig'] = copyOne
new['DistributionConfig'] = res['Distribution']['DistributionConfig']
comments += ['CloudFront distribution `{}` config updated.'.format(Name)]
if not tags_correct:
tagged = __salt__['boto_cloudfront.enforce_tags'](Resource=currentARN, Tags=Tags,
**authargs)
if tagged is False:
ret['result'] = False
msg = 'Error occurred while updating Tags on distribution `{}`.'.format(Name)
log.error(msg)
comments += [msg]
ret['comment'] = ' '.join(comments)
return ret
comments += ['CloudFront distribution `{}` Tags updated.'.format(Name)]
old['Tags'] = currentTags
new['Tags'] = Tags
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': new}
return ret
def oai_bucket_policy_present(name, Bucket, OAI, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the given policy exists on an S3 bucket, granting access for the given origin access
identity to do the things specified in the policy.
name
The name of the state definition
Bucket
The S3 bucket which CloudFront needs access to. Note that this policy
is exclusive - it will be the only policy definition on the bucket (and
objects inside the bucket if you specify such permissions in the
policy). Note that this likely SHOULD reflect the bucket mentioned in
the Resource section of the Policy, but this is not enforced...
OAI
The value of `Name` passed to the state definition for the origin
access identity which will be accessing the bucket.
Policy
The full policy document which should be set on the S3 bucket. If a
``Principal`` clause is not provided in the policy, one will be
automatically added, and pointed at the correct value as dereferenced
from the OAI provided above. If one IS provided, then this is not
done, and you are responsible for providing the correct values.
region (string)
Region to connect to.
key (string)
Secret key to use.
keyid (string)
Access key to use.
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_oai_s3_policy:
boto_cloudfront.oai_bucket_policy_present:
- Bucket: the_bucket_for_my_distribution
- OAI: the_OAI_I_just_created_and_attached_to_my_distribution
- Policy:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::the_bucket_for_my_distribution/*
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
oais = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=OAI, region=region, key=key, keyid=keyid, profile=profile)
if len(oais) > 1:
msg = 'Multiple origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not oais:
msg = 'No origin access identities matched `{}`.'.format(OAI)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
canonical_user = oais[0].get('S3CanonicalUserId')
oai_id = oais[0].get('Id')
if isinstance(Policy, six.string_types):
Policy = json.loads(Policy)
for stanza in range(len(Policy.get('Statement', []))):
if 'Principal' not in Policy['Statement'][stanza]:
Policy['Statement'][stanza]['Principal'] = {"CanonicalUser": canonical_user}
bucket = __salt__['boto_s3_bucket.describe'](Bucket=Bucket, region=region, key=key,
keyid=keyid, profile=profile)
if not bucket or 'bucket' not in bucket:
msg = 'S3 bucket `{}` not found.'.format(Bucket)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
curr_policy = bucket['bucket'].get('Policy', {}).get('Policy', {}) # ?!? dunno, that's just how it gets returned...
curr_policy = json.loads(curr_policy) if isinstance(curr_policy,
six.string_types) else curr_policy
# Sooooo, you have to SUBMIT Principals of the form
# Principal: {'S3CanonicalUserId': someCrazyLongMagicValueAsDerivedAbove}
# BUT, they RETURN the Principal as something WILDLY different
# Principal: {'AWS': arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E30ABCDEF12345}
# which obviously compare different on every run... So we fake it thusly.
fake_Policy = copy.deepcopy(Policy)
for stanza in range(len(fake_Policy.get('Statement', []))):
# Warning: unavoidable hardcoded magic values HO!
fake_Policy['Statement'][stanza].update({'Principal': {'AWS':
'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity {}'.format(oai_id)}})
if __utils__['boto3.json_objs_equal'](curr_policy, fake_Policy):
msg = 'Policy of S3 bucket `{}` is in the correct state.'.format(Bucket)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['comment'] = 'Policy on S3 bucket `{}` would be updated.'.format(Bucket)
ret['result'] = None
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
res = __salt__['boto_s3_bucket.put_policy'](Bucket=Bucket, Policy=Policy,
region=region, key=key, keyid=keyid, profile=profile)
if 'error' in res:
ret['comment'] = 'Failed to update policy on S3 bucket `{}`: {}'.format(Bucket,
res['error'])
ret['return'] = False
return ret
ret['comment'] = 'Policy on S3 bucket `{}` updated.'.format(Bucket)
ret['changes'] = {'old': curr_policy, 'new': fake_Policy}
return ret
def route53_alias_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a Route53 Alias exists and is pointing at the given CloudFront
distribution. An ``A`` record is always created, and if IPV6 is enabled on
the given distribution, an ``AAAA`` record will be created as well. Also be
aware that Alias records for CloudFront distributions are only permitted in
non-private zones.
name
The name of the state definition.
Distribution
The name of the CloudFront distribution. Defaults to the value of
``name`` if not provided.
HostedZoneId
Id of the Route53 hosted zone within which the records should be created.
DomainName
The domain name associated with the Hosted Zone. Exclusive with HostedZoneId.
ResourceRecordSet
A Route53 Record Set (with AliasTarget section, suitable for use as an
``Alias`` record, if non-default settings are needed on the Alias)
which should be pointed at the provided CloudFront distribution. Note
that this MUST correlate with the Aliases set within the
DistributionConfig section of the distribution.
Some notes *specifically* about the ``AliasTarget`` subsection of the
ResourceRecordSet:
- If not specified, the ``DNSName`` sub-field will be populated by
dereferencing ``Distribution`` above to the value of its
``DomainName`` attribute.
- The HostedZoneId sub-field should not be provided -- it will be
automatically populated with a ``magic`` AWS value.
- The EvaluateTargetHealth can only be False on a CloudFront Alias.
- The above items taken all together imply that, for most use-cases,
the AliasTarget sub-section can be entirely omitted, as seen in the
first code sample below.
Lastly, note that if you set ``name`` to the desired ResourceRecordSet
Name, you can entirely omit this parameter, as shown in the second
example below.
.. code-block:: yaml
Add a Route53 Alias for my_distribution:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
- ResourceRecordSet:
Name: the-alias.saltstack.org.
# This is even simpler - it uses the value of `name` for ResourceRecordSet.Name
another-alias.saltstack.org.:
boto_cloudfront.present:
- Distribution: my_distribution
- DomainName: saltstack.org.
'''
MAGIC_CLOUDFRONT_HOSTED_ZONEID = 'Z2FDTNDATAQYW2'
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
Distribution = kwargs['Distribution'] if 'Distribution' in kwargs else name
ResourceRecordSet = kwargs.get('ResourceRecordSet', {})
Name = ResourceRecordSet.get('Name', name)
ResourceRecordSet['Name'] = Name
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Distribution,
region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error resolving CloudFront distribution `{}` to a Resource ID.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront distibutions matched `{}`.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'No CloudFront distibutions matching `{}` found.'.format(Distribution)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
dist = res[0]
Types = ('A', 'AAAA') if dist.get('IsIPV6Enabled', False) else ('A',)
DNSName = dist.get('DomainName', '')
Aliases = dist.get('Aliases', {}).get('Items', [])
# AWS annoyance #437:
# Route53 "FQDNs" (correctly!) REQUIRE trailing periods...
# while CloudFront "FQDNs" don't PERMIT trailing periods...
Aliases += [(a if a.endswith('.') else '{}.'.format(a)) for a in Aliases]
if Name not in Aliases:
msg = ('Route53 alias `{}` requested which is not mirrored in the `Aliases`'
' sub-section of the DistributionConfig.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
changes = {'old': [], 'new': []}
comments = []
# Now mock out a route53 state def, and use the route53 rr_exists state to enforce it...
AliasTarget = ResourceRecordSet.get('AliasTarget', {})
AliasTarget['DNSName'] = AliasTarget['DNSName'] if 'DNSName' in AliasTarget else DNSName
AliasTarget['DNSName'] += '' if AliasTarget['DNSName'].endswith('.') else '.' # GRRRR!
AliasTarget['HostedZoneId'] = MAGIC_CLOUDFRONT_HOSTED_ZONEID
AliasTarget['EvaluateTargetHealth'] = False # Route53 limitation
ResourceRecordSet['name'] = Name
ResourceRecordSet['AliasTarget'] = AliasTarget
ResourceRecordSet['PrivateZone'] = False # Route53 limitation
ResourceRecordSet['DomainName'] = kwargs.get('DomainName')
ResourceRecordSet['HostedZoneId'] = kwargs.get('HostedZoneId')
ResourceRecordSet.update({'region': region, 'key': key, 'keyid': keyid, 'profile': profile})
for Type in Types:
ResourceRecordSet['Type'] = Type
# Checking for `test=True` will occur in the called state....
log.debug('Calling state function `boto3_route53.rr_present()` with args: `%s`',
ResourceRecordSet)
res = __states__['boto3_route53.rr_present'](**ResourceRecordSet)
ret['result'] = res['result']
comments += [res['comment']]
if ret['result'] not in (True, None):
break
changes['old'] += [res['changes']['old']] if res['changes'].get('old') else []
changes['new'] += [res['changes']['new']] if res['changes'].get('new') else []
ret['changes'].update({'old': changes['old']}) if changes.get('old') else None
ret['changes'].update({'new': changes['new']}) if changes.get('new') else None
ret['comment'] = ' '.join(comments)
return ret
def distribution_absent(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a distribution with the given Name tag does not exist.
Note that CloudFront does not allow directly deleting an enabled
Distribution. If such is requested, Salt will attempt to first update the
distribution's status to Disabled, and once that returns success, to then
delete the resource. THIS CAN TAKE SOME TIME, so be patient :)
name (string)
Name of the state definition.
Name (string)
Name of the CloudFront distribution to be managed. If not provided, the
value of ``name`` will be used as a default. The purpose of this
parameter is only to resolve it to a Resource ID, so be aware that an
explicit value for ``Id`` below will override any value provided, or
defaulted, here.
Id (string)
The Resource ID of a CloudFront distribution to be managed.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
Ensure a distribution named my_distribution is gone:
boto_cloudfront.distribution_absent:
- Name: my_distribution
'''
Name = kwargs['Name'] if 'Name' in kwargs else name
Id = kwargs.get('Id')
ref = kwargs['Id'] if 'Id' in kwargs else Name
ret = {'name': Id if Id else Name, 'comment': '', 'changes': {}, 'result': True}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
if not Id:
res = __salt__['boto_cloudfront.get_distributions_by_comment'](Comment=Name, **authargs)
if res is None:
msg = 'Error dereferencing CloudFront distribution `{}` to a Resource ID.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = ('Multiple CloudFront distibutions matched `{}`, no way to know which to'
' delete.`.'.format(Name))
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if not res:
msg = 'CloudFront Distribution `{}` already absent.'.format(Name)
log.info(msg)
ret['comment'] = msg
ret['result'] = True
return ret
Id = res[0]['Id']
if not __salt__['boto_cloudfront.distribution_exists'](Id=Id, **authargs):
msg = 'CloudFront distribution `{}` already absent.'.format(ref)
log.info(msg)
ret['comment'] = msg
return ret
old = __salt__['boto_cloudfront.get_distribution_v2'](Id=Id, **authargs)
if old is None:
ret['result'] = False
msg = 'Error getting state of CloudFront distribution `{}`.'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
currETag = old['ETag']
Enabled = old['DistributionConfig']['Enabled']
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront distribution `{}` would be {}deleted.'.format(ref,
('disabled and ' if Enabled else ''))
ret['pchanges'] = {'old': old, 'new': None}
return ret
comments = []
if Enabled:
disabled = __salt__['boto_cloudfront.disable_distribution'](Id=Id, **authargs)
if disabled is None:
ret['result'] = False
msg = 'Error disabling CloudFront distribution `{}`'.format(ref)
log.error(msg)
ret['comment'] = msg
return ret
comments += ['CloudFront distribution `{}` disabled.'.format(ref)]
currETag = disabled['ETag']
deleted = __salt__['boto_cloudfront.delete_distribution'](Id=Id, IfMatch=currETag, **authargs)
if deleted is False:
ret['result'] = False
msg = 'Error deleting CloudFront distribution `{}`'.format(ref)
comments += [msg]
log.error(msg)
ret['comment'] = ' '.join(comments)
return ret
msg = 'CloudFront distribution `{}` deleted.'.format(ref)
comments += [msg]
log.info(msg)
ret['comment'] = ' '.join(comments)
ret['changes'] = {'old': old, 'new': None}
return ret
def origin_access_identity_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure a given CloudFront Origin Access Identity exists.
.. note::
Due to the unavailibity of ANY other way to store stateful idempotency
information about Origin Access Identities (including resource tags),
the Comment attribute (as the only user-settable attribute without
weird self-blocking semantics) is necessarily utilized to store the
Salt state signifier, which is used to determine resource existence and
state. That said, to enable SOME usability of this field, only the
value up to the first colon character is taken as the signifier, while
anything afterward is free-form and ignored by Salt.
name (string)
Name of the state definition.
Name (string)
Name of the resource (for purposes of Salt's idempotency). If not provided, the value of
`name` will be used.
Comment
Free-form text description of the origin access identity.
region (string)
Region to connect to
key (string)
Secret key to use
keyid (string)
Access key to use
profile (dict or string)
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
Example:
.. code-block:: yaml
my_OAI:
boto_cloudfront.origin_access_identity_present:
- Comment: Simply ensures an OAI named my_OAI exists
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
Name = kwargs.get('Name', name)
# Munge Name into the Comment field...
Comment = '{}:{}'.format(Name, kwargs['Comment']) if kwargs.get('Comment') else Name
# Current state of the thing?
res = __salt__['boto_cloudfront.get_cloud_front_origin_access_identities_by_comment'](
Comment=Name, region=region, key=key, keyid=keyid, profile=profile)
if res is None:
msg = 'Error determining current state of origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
if len(res) > 1:
msg = 'Multiple CloudFront origin access identities matched `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
ret['result'] = False
return ret
exists = bool(res)
if not exists:
CloudFrontOriginAccessIdentityConfig = {'Comment': Comment,
'CallerReference': str(uuid.uuid4())}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be created.'.format(Name)
new = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
ret['pchanges'] = {'old': None, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': CloudFrontOriginAccessIdentityConfig}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.create_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Failed to create CloudFront origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'Created CloudFrong origin access identity`{}`.'.format(Name)
ret['changes'] = {'old': None, 'new': res}
return ret
else:
currentId = res[0]['Id']
current = __salt__['boto_cloudfront.get_cloud_front_origin_access_identity'](Id=currentId,
**authargs)
currentETag = current['ETag']
currentOAIC = current['CloudFrontOriginAccessIdentity']['CloudFrontOriginAccessIdentityConfig']
new = copy.deepcopy(currentOAIC)
new.update({'Comment': Comment}) # Currently the only updatable element :-/
if currentOAIC == new:
msg = 'CloudFront origin access identity `{}` is in the correct state.'.format(Name)
log.info(msg)
ret['comment'] = msg
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'CloudFront origin access identity `{}` would be updated.'.format(Name)
ret['pchanges'] = {'old': currentOAIC, 'new': new}
return ret
kwargs = {'CloudFrontOriginAccessIdentityConfig': new,
'Id': currentId, 'IfMatch': currentETag}
kwargs.update(authargs)
res = __salt__['boto_cloudfront.update_cloud_front_origin_access_identity'](**kwargs)
if res is None:
ret['result'] = False
msg = 'Error occurred while updating origin access identity `{}`.'.format(Name)
log.error(msg)
ret['comment'] = msg
return ret
ret['comment'] = 'CloudFront origin access identity `{}` config updated.'.format(Name)
ret['changes'] = {'old': currentOAIC, 'new': new}
return ret
|
saltstack/salt | salt/modules/snap.py | install | python | def install(pkg, channel=None, refresh=False):
'''
Install the specified snap package from the specified channel.
Returns a dictionary of "result" and "output".
pkg
The snap package name
channel
Optional. The snap channel to install from, eg "beta"
refresh : False
If True, use "snap refresh" instead of "snap install".
This allows changing the channel of a previously installed package.
'''
args = []
ret = {'result': None, 'output': ""}
if refresh:
cmd = 'refresh'
else:
cmd = 'install'
if channel:
args.append('--channel=' + channel)
try:
# Try to run it, merging stderr into output
ret['output'] = subprocess.check_output([SNAP_BINARY_NAME, cmd, pkg] + args, stderr=subprocess.STDOUT)
ret['result'] = True
except subprocess.CalledProcessError as e:
ret['output'] = e.output
ret['result'] = False
return ret | Install the specified snap package from the specified channel.
Returns a dictionary of "result" and "output".
pkg
The snap package name
channel
Optional. The snap channel to install from, eg "beta"
refresh : False
If True, use "snap refresh" instead of "snap install".
This allows changing the channel of a previously installed package. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/snap.py#L26-L60 | null | # -*- coding: utf-8 -*-
'''
Manage snap packages via Salt
:depends: snapd for distribution
'''
from __future__ import absolute_import, print_function, unicode_literals
import subprocess
import salt.utils.path
SNAP_BINARY_NAME = 'snap'
__virtualname__ = 'snap'
def __virtual__():
if salt.utils.path.which('snap'):
return __virtualname__
return (False, 'The snap execution module cannot be loaded: the "snap" binary is not in the path.')
def is_installed(pkg):
'''
Returns True if there is any version of the specified package installed.
pkg
The package name
'''
return bool(versions_installed(pkg))
def remove(pkg):
'''
Remove the specified snap package. Returns a dictionary of "result" and "output".
pkg
The package name
'''
ret = {'result': None, 'output': ""}
try:
ret['output'] = subprocess.check_output([SNAP_BINARY_NAME, 'remove', pkg])
ret['result'] = True
except subprocess.CalledProcessError as e:
ret['output'] = e.output
ret['result'] = False
# Parse 'snap list' into a dict
def versions_installed(pkg):
'''
Query which version(s) of the specified snap package are installed.
Returns a list of 0 or more dictionaries.
pkg
The package name
'''
try:
# Try to run it, merging stderr into output
output = subprocess.check_output([SNAP_BINARY_NAME, 'list', pkg], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
return []
lines = output.splitlines()[1:]
ret = []
for item in lines:
# If fields contain spaces this will break.
i = item.split()
# Ignore 'Notes' field
ret.append({
'name': i[0],
'version': i[1],
'rev': i[2],
'tracking': i[3],
'publisher': i[4]
})
return ret
|
saltstack/salt | salt/modules/snap.py | remove | python | def remove(pkg):
'''
Remove the specified snap package. Returns a dictionary of "result" and "output".
pkg
The package name
'''
ret = {'result': None, 'output': ""}
try:
ret['output'] = subprocess.check_output([SNAP_BINARY_NAME, 'remove', pkg])
ret['result'] = True
except subprocess.CalledProcessError as e:
ret['output'] = e.output
ret['result'] = False | Remove the specified snap package. Returns a dictionary of "result" and "output".
pkg
The package name | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/snap.py#L73-L86 | null | # -*- coding: utf-8 -*-
'''
Manage snap packages via Salt
:depends: snapd for distribution
'''
from __future__ import absolute_import, print_function, unicode_literals
import subprocess
import salt.utils.path
SNAP_BINARY_NAME = 'snap'
__virtualname__ = 'snap'
def __virtual__():
if salt.utils.path.which('snap'):
return __virtualname__
return (False, 'The snap execution module cannot be loaded: the "snap" binary is not in the path.')
def install(pkg, channel=None, refresh=False):
'''
Install the specified snap package from the specified channel.
Returns a dictionary of "result" and "output".
pkg
The snap package name
channel
Optional. The snap channel to install from, eg "beta"
refresh : False
If True, use "snap refresh" instead of "snap install".
This allows changing the channel of a previously installed package.
'''
args = []
ret = {'result': None, 'output': ""}
if refresh:
cmd = 'refresh'
else:
cmd = 'install'
if channel:
args.append('--channel=' + channel)
try:
# Try to run it, merging stderr into output
ret['output'] = subprocess.check_output([SNAP_BINARY_NAME, cmd, pkg] + args, stderr=subprocess.STDOUT)
ret['result'] = True
except subprocess.CalledProcessError as e:
ret['output'] = e.output
ret['result'] = False
return ret
def is_installed(pkg):
'''
Returns True if there is any version of the specified package installed.
pkg
The package name
'''
return bool(versions_installed(pkg))
# Parse 'snap list' into a dict
def versions_installed(pkg):
'''
Query which version(s) of the specified snap package are installed.
Returns a list of 0 or more dictionaries.
pkg
The package name
'''
try:
# Try to run it, merging stderr into output
output = subprocess.check_output([SNAP_BINARY_NAME, 'list', pkg], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
return []
lines = output.splitlines()[1:]
ret = []
for item in lines:
# If fields contain spaces this will break.
i = item.split()
# Ignore 'Notes' field
ret.append({
'name': i[0],
'version': i[1],
'rev': i[2],
'tracking': i[3],
'publisher': i[4]
})
return ret
|
saltstack/salt | salt/modules/snap.py | versions_installed | python | def versions_installed(pkg):
'''
Query which version(s) of the specified snap package are installed.
Returns a list of 0 or more dictionaries.
pkg
The package name
'''
try:
# Try to run it, merging stderr into output
output = subprocess.check_output([SNAP_BINARY_NAME, 'list', pkg], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
return []
lines = output.splitlines()[1:]
ret = []
for item in lines:
# If fields contain spaces this will break.
i = item.split()
# Ignore 'Notes' field
ret.append({
'name': i[0],
'version': i[1],
'rev': i[2],
'tracking': i[3],
'publisher': i[4]
})
return ret | Query which version(s) of the specified snap package are installed.
Returns a list of 0 or more dictionaries.
pkg
The package name | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/snap.py#L90-L119 | null | # -*- coding: utf-8 -*-
'''
Manage snap packages via Salt
:depends: snapd for distribution
'''
from __future__ import absolute_import, print_function, unicode_literals
import subprocess
import salt.utils.path
SNAP_BINARY_NAME = 'snap'
__virtualname__ = 'snap'
def __virtual__():
if salt.utils.path.which('snap'):
return __virtualname__
return (False, 'The snap execution module cannot be loaded: the "snap" binary is not in the path.')
def install(pkg, channel=None, refresh=False):
'''
Install the specified snap package from the specified channel.
Returns a dictionary of "result" and "output".
pkg
The snap package name
channel
Optional. The snap channel to install from, eg "beta"
refresh : False
If True, use "snap refresh" instead of "snap install".
This allows changing the channel of a previously installed package.
'''
args = []
ret = {'result': None, 'output': ""}
if refresh:
cmd = 'refresh'
else:
cmd = 'install'
if channel:
args.append('--channel=' + channel)
try:
# Try to run it, merging stderr into output
ret['output'] = subprocess.check_output([SNAP_BINARY_NAME, cmd, pkg] + args, stderr=subprocess.STDOUT)
ret['result'] = True
except subprocess.CalledProcessError as e:
ret['output'] = e.output
ret['result'] = False
return ret
def is_installed(pkg):
'''
Returns True if there is any version of the specified package installed.
pkg
The package name
'''
return bool(versions_installed(pkg))
def remove(pkg):
'''
Remove the specified snap package. Returns a dictionary of "result" and "output".
pkg
The package name
'''
ret = {'result': None, 'output': ""}
try:
ret['output'] = subprocess.check_output([SNAP_BINARY_NAME, 'remove', pkg])
ret['result'] = True
except subprocess.CalledProcessError as e:
ret['output'] = e.output
ret['result'] = False
# Parse 'snap list' into a dict
|
saltstack/salt | salt/modules/virtualenv_mod.py | create | python | def create(path,
venv_bin=None,
system_site_packages=False,
distribute=False,
clear=False,
python=None,
extra_search_dir=None,
never_download=None,
prompt=None,
pip=False,
symlinks=None,
upgrade=None,
user=None,
use_vt=False,
saltenv='base',
**kwargs):
'''
Create a virtualenv
path
The path to the virtualenv to be created
venv_bin
The name (and optionally path) of the virtualenv command. This can also
be set globally in the pillar data as ``venv_bin``.
Defaults to ``pyvenv`` or ``virtualenv``, depending on what is installed.
system_site_packages : False
Passthrough argument given to virtualenv or pyvenv
distribute : False
Passthrough argument given to virtualenv
pip : False
Install pip after creating a virtual environment. Implies
``distribute=True``
clear : False
Passthrough argument given to virtualenv or pyvenv
python : None (default)
Passthrough argument given to virtualenv
extra_search_dir : None (default)
Passthrough argument given to virtualenv
never_download : None (default)
Passthrough argument given to virtualenv if True
prompt : None (default)
Passthrough argument given to virtualenv if not None
symlinks : None
Passthrough argument given to pyvenv if True
upgrade : None
Passthrough argument given to pyvenv if True
user : None
Set ownership for the virtualenv
.. note::
On Windows you must also pass a ``password`` parameter. Additionally,
the user must have permissions to the location where the virtual
environment is being created
runas : None
Set ownership for the virtualenv
.. deprecated:: 2014.1.0
``user`` should be used instead
use_vt : False
Use VT terminal emulation (see output while installing)
.. versionadded:: 2015.5.0
saltenv : 'base'
Specify a different environment. The default environment is ``base``.
.. versionadded:: 2014.1.0
.. note::
The ``runas`` argument is deprecated as of 2014.1.0. ``user`` should be
used instead.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.create /path/to/new/virtualenv
'''
if venv_bin is None:
# Beginning in 3.6, pyvenv has been deprecated
# in favor of "python3 -m venv"
if sys.version_info >= (3, 6):
venv_bin = ['python3', '-m', 'venv']
else:
venv_bin = __pillar__.get('venv_bin') or __opts__.get('venv_bin')
if not isinstance(venv_bin, list):
cmd = [venv_bin]
else:
cmd = venv_bin
if 'pyvenv' not in venv_bin:
# ----- Stop the user if pyvenv only options are used --------------->
# If any of the following values are not None, it means that the user
# is actually passing a True or False value. Stop Him!
if upgrade is not None:
raise CommandExecutionError(
'The `upgrade`(`--upgrade`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
elif symlinks is not None:
raise CommandExecutionError(
'The `symlinks`(`--symlinks`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
# <---- Stop the user if pyvenv only options are used ----------------
# Virtualenv package
try:
import virtualenv
version = getattr(virtualenv, '__version__',
virtualenv.virtualenv_version)
virtualenv_version_info = tuple(
[int(i) for i in version.split('rc')[0].split('.')]
)
except ImportError:
# Unable to import?? Let's parse the version from the console
version_cmd = [venv_bin, '--version']
ret = __salt__['cmd.run_all'](
version_cmd, runas=user, python_shell=False, **kwargs
)
if ret['retcode'] > 0 or not ret['stdout'].strip():
raise CommandExecutionError(
'Unable to get the virtualenv version output using \'{0}\'. '
'Returned data: {1}'.format(version_cmd, ret)
)
virtualenv_version_info = tuple(
[int(i) for i in
ret['stdout'].strip().split('rc')[0].split('.')]
)
if distribute:
if virtualenv_version_info >= (1, 10):
log.info(
'The virtualenv \'--distribute\' option has been '
'deprecated in virtualenv(>=1.10), as such, the '
'\'distribute\' option to `virtualenv.create()` has '
'also been deprecated and it\'s not necessary anymore.'
)
else:
cmd.append('--distribute')
if python is not None and python.strip() != '':
if not salt.utils.path.which(python):
raise CommandExecutionError(
'Cannot find requested python ({0}).'.format(python)
)
cmd.append('--python={0}'.format(python))
if extra_search_dir is not None:
if isinstance(extra_search_dir, string_types) and \
extra_search_dir.strip() != '':
extra_search_dir = [
e.strip() for e in extra_search_dir.split(',')
]
for entry in extra_search_dir:
cmd.append('--extra-search-dir={0}'.format(entry))
if never_download is True:
if (1, 10) <= virtualenv_version_info < (14, 0, 0):
log.info(
'--never-download was deprecated in 1.10.0, but reimplemented in 14.0.0. '
'If this feature is needed, please install a supported virtualenv version.'
)
else:
cmd.append('--never-download')
if prompt is not None and prompt.strip() != '':
cmd.append('--prompt=\'{0}\''.format(prompt))
else:
# venv module from the Python >= 3.3 standard library
# ----- Stop the user if virtualenv only options are being used ----->
# If any of the following values are not None, it means that the user
# is actually passing a True or False value. Stop Him!
if python is not None and python.strip() != '':
raise CommandExecutionError(
'The `python`(`--python`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
elif extra_search_dir is not None and extra_search_dir.strip() != '':
raise CommandExecutionError(
'The `extra_search_dir`(`--extra-search-dir`) option is not '
'supported by \'{0}\''.format(venv_bin)
)
elif never_download is not None:
raise CommandExecutionError(
'The `never_download`(`--never-download`) option is not '
'supported by \'{0}\''.format(venv_bin)
)
elif prompt is not None and prompt.strip() != '':
raise CommandExecutionError(
'The `prompt`(`--prompt`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
# <---- Stop the user if virtualenv only options are being used ------
if upgrade is True:
cmd.append('--upgrade')
if symlinks is True:
cmd.append('--symlinks')
# Common options to virtualenv and pyvenv
if clear is True:
cmd.append('--clear')
if system_site_packages is True:
cmd.append('--system-site-packages')
# Finally the virtualenv path
cmd.append(path)
# Let's create the virtualenv
ret = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False, **kwargs)
if ret['retcode'] != 0:
# Something went wrong. Let's bail out now!
return ret
# Check if distribute and pip are already installed
if salt.utils.platform.is_windows():
venv_python = os.path.join(path, 'Scripts', 'python.exe')
venv_pip = os.path.join(path, 'Scripts', 'pip.exe')
venv_setuptools = os.path.join(path, 'Scripts', 'easy_install.exe')
else:
venv_python = os.path.join(path, 'bin', 'python')
venv_pip = os.path.join(path, 'bin', 'pip')
venv_setuptools = os.path.join(path, 'bin', 'easy_install')
# Install setuptools
if (pip or distribute) and not os.path.exists(venv_setuptools):
_install_script(
'https://bitbucket.org/pypa/setuptools/raw/default/ez_setup.py',
path, venv_python, user, saltenv=saltenv, use_vt=use_vt
)
# clear up the distribute archive which gets downloaded
for fpath in glob.glob(os.path.join(path, 'distribute-*.tar.gz*')):
os.unlink(fpath)
if ret['retcode'] != 0:
# Something went wrong. Let's bail out now!
return ret
# Install pip
if pip and not os.path.exists(venv_pip):
_ret = _install_script(
'https://bootstrap.pypa.io/get-pip.py',
path, venv_python, user, saltenv=saltenv, use_vt=use_vt
)
# Let's update the return dictionary with the details from the pip
# installation
ret.update(
retcode=_ret['retcode'],
stdout='{0}\n{1}'.format(ret['stdout'], _ret['stdout']).strip(),
stderr='{0}\n{1}'.format(ret['stderr'], _ret['stderr']).strip(),
)
return ret | Create a virtualenv
path
The path to the virtualenv to be created
venv_bin
The name (and optionally path) of the virtualenv command. This can also
be set globally in the pillar data as ``venv_bin``.
Defaults to ``pyvenv`` or ``virtualenv``, depending on what is installed.
system_site_packages : False
Passthrough argument given to virtualenv or pyvenv
distribute : False
Passthrough argument given to virtualenv
pip : False
Install pip after creating a virtual environment. Implies
``distribute=True``
clear : False
Passthrough argument given to virtualenv or pyvenv
python : None (default)
Passthrough argument given to virtualenv
extra_search_dir : None (default)
Passthrough argument given to virtualenv
never_download : None (default)
Passthrough argument given to virtualenv if True
prompt : None (default)
Passthrough argument given to virtualenv if not None
symlinks : None
Passthrough argument given to pyvenv if True
upgrade : None
Passthrough argument given to pyvenv if True
user : None
Set ownership for the virtualenv
.. note::
On Windows you must also pass a ``password`` parameter. Additionally,
the user must have permissions to the location where the virtual
environment is being created
runas : None
Set ownership for the virtualenv
.. deprecated:: 2014.1.0
``user`` should be used instead
use_vt : False
Use VT terminal emulation (see output while installing)
.. versionadded:: 2015.5.0
saltenv : 'base'
Specify a different environment. The default environment is ``base``.
.. versionadded:: 2014.1.0
.. note::
The ``runas`` argument is deprecated as of 2014.1.0. ``user`` should be
used instead.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.create /path/to/new/virtualenv | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virtualenv_mod.py#L49-L316 | [
"def _install_script(source, cwd, python, user, saltenv='base', use_vt=False):\n if not salt.utils.platform.is_windows():\n tmppath = salt.utils.files.mkstemp(dir=cwd)\n else:\n tmppath = __salt__['cp.cache_file'](source, saltenv)\n\n if not salt.utils.platform.is_windows():\n fn_ = __salt__['cp.cache_file'](source, saltenv)\n shutil.copyfile(fn_, tmppath)\n os.chmod(tmppath, 0o500)\n os.chown(tmppath, __salt__['file.user_to_uid'](user), -1)\n try:\n return __salt__['cmd.run_all'](\n [python, tmppath],\n runas=user,\n cwd=cwd,\n env={'VIRTUAL_ENV': cwd},\n use_vt=use_vt,\n python_shell=False,\n )\n finally:\n os.remove(tmppath)\n"
] | # -*- coding: utf-8 -*-
'''
Create virtualenv environments.
.. versionadded:: 0.17.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import glob
import shutil
import logging
import os
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.verify
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext.six import string_types
KNOWN_BINARY_NAMES = frozenset([
'pyvenv-{0}.{1}'.format(*sys.version_info[:2]),
'virtualenv-{0}.{1}'.format(*sys.version_info[:2]),
'pyvenv{0}'.format(sys.version_info[0]),
'virtualenv{0}'.format(sys.version_info[0]),
'pyvenv',
'virtualenv',
])
log = logging.getLogger(__name__)
__opts__ = {
'venv_bin': salt.utils.path.which_bin(KNOWN_BINARY_NAMES) or 'virtualenv'
}
__pillar__ = {}
# Define the module's virtual name
__virtualname__ = 'virtualenv'
def __virtual__():
return __virtualname__
def get_site_packages(venv):
'''
Return the path to the site-packages directory of a virtualenv
venv
Path to the virtualenv.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_site_packages /path/to/my/venv
'''
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'from distutils import sysconfig; '
'print(sysconfig.get_python_lib())'
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def get_distribution_path(venv, distribution):
'''
Return the path to a distribution installed inside a virtualenv
.. versionadded:: 2016.3.0
venv
Path to the virtualenv.
distribution
Name of the distribution. Note, all non-alphanumeric characters
will be converted to dashes.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_distribution_path /path/to/my/venv my_distribution
'''
_verify_safe_py_code(distribution)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.get_distribution('{0}').location)".format(
distribution
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def get_resource_path(venv,
package=None,
resource=None):
'''
Return the path to a package resource installed inside a virtualenv
.. versionadded:: 2015.5.0
venv
Path to the virtualenv
package
Name of the package in which the resource resides
.. versionadded:: 2016.3.0
resource
Name of the resource of which the path is to be returned
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_resource_path /path/to/my/venv my_package my/resource.xml
'''
_verify_safe_py_code(package, resource)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.resource_filename('{0}', '{1}'))".format(
package,
resource
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def get_resource_content(venv,
package=None,
resource=None):
'''
Return the content of a package resource installed inside a virtualenv
.. versionadded:: 2015.5.0
venv
Path to the virtualenv
package
Name of the package in which the resource resides
.. versionadded:: 2016.3.0
resource
Name of the resource of which the content is to be returned
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_resource_content /path/to/my/venv my_package my/resource.xml
'''
_verify_safe_py_code(package, resource)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.resource_string('{0}', '{1}'))".format(
package,
resource
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def _install_script(source, cwd, python, user, saltenv='base', use_vt=False):
if not salt.utils.platform.is_windows():
tmppath = salt.utils.files.mkstemp(dir=cwd)
else:
tmppath = __salt__['cp.cache_file'](source, saltenv)
if not salt.utils.platform.is_windows():
fn_ = __salt__['cp.cache_file'](source, saltenv)
shutil.copyfile(fn_, tmppath)
os.chmod(tmppath, 0o500)
os.chown(tmppath, __salt__['file.user_to_uid'](user), -1)
try:
return __salt__['cmd.run_all'](
[python, tmppath],
runas=user,
cwd=cwd,
env={'VIRTUAL_ENV': cwd},
use_vt=use_vt,
python_shell=False,
)
finally:
os.remove(tmppath)
def _verify_safe_py_code(*args):
for arg in args:
if not salt.utils.verify.safe_py_code(arg):
raise SaltInvocationError(
'Unsafe python code detected in \'{0}\''.format(arg)
)
def _verify_virtualenv(venv_path):
bin_path = os.path.join(venv_path, 'bin/python')
if not os.path.exists(bin_path):
raise CommandExecutionError(
'Path \'{0}\' does not appear to be a virtualenv: bin/python not found.'.format(venv_path)
)
return bin_path
|
saltstack/salt | salt/modules/virtualenv_mod.py | get_site_packages | python | def get_site_packages(venv):
'''
Return the path to the site-packages directory of a virtualenv
venv
Path to the virtualenv.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_site_packages /path/to/my/venv
'''
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'from distutils import sysconfig; '
'print(sysconfig.get_python_lib())'
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout'] | Return the path to the site-packages directory of a virtualenv
venv
Path to the virtualenv.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_site_packages /path/to/my/venv | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virtualenv_mod.py#L319-L343 | [
"def _verify_virtualenv(venv_path):\n bin_path = os.path.join(venv_path, 'bin/python')\n if not os.path.exists(bin_path):\n raise CommandExecutionError(\n 'Path \\'{0}\\' does not appear to be a virtualenv: bin/python not found.'.format(venv_path)\n )\n return bin_path\n"
] | # -*- coding: utf-8 -*-
'''
Create virtualenv environments.
.. versionadded:: 0.17.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import glob
import shutil
import logging
import os
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.verify
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext.six import string_types
KNOWN_BINARY_NAMES = frozenset([
'pyvenv-{0}.{1}'.format(*sys.version_info[:2]),
'virtualenv-{0}.{1}'.format(*sys.version_info[:2]),
'pyvenv{0}'.format(sys.version_info[0]),
'virtualenv{0}'.format(sys.version_info[0]),
'pyvenv',
'virtualenv',
])
log = logging.getLogger(__name__)
__opts__ = {
'venv_bin': salt.utils.path.which_bin(KNOWN_BINARY_NAMES) or 'virtualenv'
}
__pillar__ = {}
# Define the module's virtual name
__virtualname__ = 'virtualenv'
def __virtual__():
return __virtualname__
def create(path,
venv_bin=None,
system_site_packages=False,
distribute=False,
clear=False,
python=None,
extra_search_dir=None,
never_download=None,
prompt=None,
pip=False,
symlinks=None,
upgrade=None,
user=None,
use_vt=False,
saltenv='base',
**kwargs):
'''
Create a virtualenv
path
The path to the virtualenv to be created
venv_bin
The name (and optionally path) of the virtualenv command. This can also
be set globally in the pillar data as ``venv_bin``.
Defaults to ``pyvenv`` or ``virtualenv``, depending on what is installed.
system_site_packages : False
Passthrough argument given to virtualenv or pyvenv
distribute : False
Passthrough argument given to virtualenv
pip : False
Install pip after creating a virtual environment. Implies
``distribute=True``
clear : False
Passthrough argument given to virtualenv or pyvenv
python : None (default)
Passthrough argument given to virtualenv
extra_search_dir : None (default)
Passthrough argument given to virtualenv
never_download : None (default)
Passthrough argument given to virtualenv if True
prompt : None (default)
Passthrough argument given to virtualenv if not None
symlinks : None
Passthrough argument given to pyvenv if True
upgrade : None
Passthrough argument given to pyvenv if True
user : None
Set ownership for the virtualenv
.. note::
On Windows you must also pass a ``password`` parameter. Additionally,
the user must have permissions to the location where the virtual
environment is being created
runas : None
Set ownership for the virtualenv
.. deprecated:: 2014.1.0
``user`` should be used instead
use_vt : False
Use VT terminal emulation (see output while installing)
.. versionadded:: 2015.5.0
saltenv : 'base'
Specify a different environment. The default environment is ``base``.
.. versionadded:: 2014.1.0
.. note::
The ``runas`` argument is deprecated as of 2014.1.0. ``user`` should be
used instead.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.create /path/to/new/virtualenv
'''
if venv_bin is None:
# Beginning in 3.6, pyvenv has been deprecated
# in favor of "python3 -m venv"
if sys.version_info >= (3, 6):
venv_bin = ['python3', '-m', 'venv']
else:
venv_bin = __pillar__.get('venv_bin') or __opts__.get('venv_bin')
if not isinstance(venv_bin, list):
cmd = [venv_bin]
else:
cmd = venv_bin
if 'pyvenv' not in venv_bin:
# ----- Stop the user if pyvenv only options are used --------------->
# If any of the following values are not None, it means that the user
# is actually passing a True or False value. Stop Him!
if upgrade is not None:
raise CommandExecutionError(
'The `upgrade`(`--upgrade`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
elif symlinks is not None:
raise CommandExecutionError(
'The `symlinks`(`--symlinks`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
# <---- Stop the user if pyvenv only options are used ----------------
# Virtualenv package
try:
import virtualenv
version = getattr(virtualenv, '__version__',
virtualenv.virtualenv_version)
virtualenv_version_info = tuple(
[int(i) for i in version.split('rc')[0].split('.')]
)
except ImportError:
# Unable to import?? Let's parse the version from the console
version_cmd = [venv_bin, '--version']
ret = __salt__['cmd.run_all'](
version_cmd, runas=user, python_shell=False, **kwargs
)
if ret['retcode'] > 0 or not ret['stdout'].strip():
raise CommandExecutionError(
'Unable to get the virtualenv version output using \'{0}\'. '
'Returned data: {1}'.format(version_cmd, ret)
)
virtualenv_version_info = tuple(
[int(i) for i in
ret['stdout'].strip().split('rc')[0].split('.')]
)
if distribute:
if virtualenv_version_info >= (1, 10):
log.info(
'The virtualenv \'--distribute\' option has been '
'deprecated in virtualenv(>=1.10), as such, the '
'\'distribute\' option to `virtualenv.create()` has '
'also been deprecated and it\'s not necessary anymore.'
)
else:
cmd.append('--distribute')
if python is not None and python.strip() != '':
if not salt.utils.path.which(python):
raise CommandExecutionError(
'Cannot find requested python ({0}).'.format(python)
)
cmd.append('--python={0}'.format(python))
if extra_search_dir is not None:
if isinstance(extra_search_dir, string_types) and \
extra_search_dir.strip() != '':
extra_search_dir = [
e.strip() for e in extra_search_dir.split(',')
]
for entry in extra_search_dir:
cmd.append('--extra-search-dir={0}'.format(entry))
if never_download is True:
if (1, 10) <= virtualenv_version_info < (14, 0, 0):
log.info(
'--never-download was deprecated in 1.10.0, but reimplemented in 14.0.0. '
'If this feature is needed, please install a supported virtualenv version.'
)
else:
cmd.append('--never-download')
if prompt is not None and prompt.strip() != '':
cmd.append('--prompt=\'{0}\''.format(prompt))
else:
# venv module from the Python >= 3.3 standard library
# ----- Stop the user if virtualenv only options are being used ----->
# If any of the following values are not None, it means that the user
# is actually passing a True or False value. Stop Him!
if python is not None and python.strip() != '':
raise CommandExecutionError(
'The `python`(`--python`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
elif extra_search_dir is not None and extra_search_dir.strip() != '':
raise CommandExecutionError(
'The `extra_search_dir`(`--extra-search-dir`) option is not '
'supported by \'{0}\''.format(venv_bin)
)
elif never_download is not None:
raise CommandExecutionError(
'The `never_download`(`--never-download`) option is not '
'supported by \'{0}\''.format(venv_bin)
)
elif prompt is not None and prompt.strip() != '':
raise CommandExecutionError(
'The `prompt`(`--prompt`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
# <---- Stop the user if virtualenv only options are being used ------
if upgrade is True:
cmd.append('--upgrade')
if symlinks is True:
cmd.append('--symlinks')
# Common options to virtualenv and pyvenv
if clear is True:
cmd.append('--clear')
if system_site_packages is True:
cmd.append('--system-site-packages')
# Finally the virtualenv path
cmd.append(path)
# Let's create the virtualenv
ret = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False, **kwargs)
if ret['retcode'] != 0:
# Something went wrong. Let's bail out now!
return ret
# Check if distribute and pip are already installed
if salt.utils.platform.is_windows():
venv_python = os.path.join(path, 'Scripts', 'python.exe')
venv_pip = os.path.join(path, 'Scripts', 'pip.exe')
venv_setuptools = os.path.join(path, 'Scripts', 'easy_install.exe')
else:
venv_python = os.path.join(path, 'bin', 'python')
venv_pip = os.path.join(path, 'bin', 'pip')
venv_setuptools = os.path.join(path, 'bin', 'easy_install')
# Install setuptools
if (pip or distribute) and not os.path.exists(venv_setuptools):
_install_script(
'https://bitbucket.org/pypa/setuptools/raw/default/ez_setup.py',
path, venv_python, user, saltenv=saltenv, use_vt=use_vt
)
# clear up the distribute archive which gets downloaded
for fpath in glob.glob(os.path.join(path, 'distribute-*.tar.gz*')):
os.unlink(fpath)
if ret['retcode'] != 0:
# Something went wrong. Let's bail out now!
return ret
# Install pip
if pip and not os.path.exists(venv_pip):
_ret = _install_script(
'https://bootstrap.pypa.io/get-pip.py',
path, venv_python, user, saltenv=saltenv, use_vt=use_vt
)
# Let's update the return dictionary with the details from the pip
# installation
ret.update(
retcode=_ret['retcode'],
stdout='{0}\n{1}'.format(ret['stdout'], _ret['stdout']).strip(),
stderr='{0}\n{1}'.format(ret['stderr'], _ret['stderr']).strip(),
)
return ret
def get_distribution_path(venv, distribution):
'''
Return the path to a distribution installed inside a virtualenv
.. versionadded:: 2016.3.0
venv
Path to the virtualenv.
distribution
Name of the distribution. Note, all non-alphanumeric characters
will be converted to dashes.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_distribution_path /path/to/my/venv my_distribution
'''
_verify_safe_py_code(distribution)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.get_distribution('{0}').location)".format(
distribution
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def get_resource_path(venv,
package=None,
resource=None):
'''
Return the path to a package resource installed inside a virtualenv
.. versionadded:: 2015.5.0
venv
Path to the virtualenv
package
Name of the package in which the resource resides
.. versionadded:: 2016.3.0
resource
Name of the resource of which the path is to be returned
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_resource_path /path/to/my/venv my_package my/resource.xml
'''
_verify_safe_py_code(package, resource)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.resource_filename('{0}', '{1}'))".format(
package,
resource
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def get_resource_content(venv,
package=None,
resource=None):
'''
Return the content of a package resource installed inside a virtualenv
.. versionadded:: 2015.5.0
venv
Path to the virtualenv
package
Name of the package in which the resource resides
.. versionadded:: 2016.3.0
resource
Name of the resource of which the content is to be returned
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_resource_content /path/to/my/venv my_package my/resource.xml
'''
_verify_safe_py_code(package, resource)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.resource_string('{0}', '{1}'))".format(
package,
resource
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def _install_script(source, cwd, python, user, saltenv='base', use_vt=False):
if not salt.utils.platform.is_windows():
tmppath = salt.utils.files.mkstemp(dir=cwd)
else:
tmppath = __salt__['cp.cache_file'](source, saltenv)
if not salt.utils.platform.is_windows():
fn_ = __salt__['cp.cache_file'](source, saltenv)
shutil.copyfile(fn_, tmppath)
os.chmod(tmppath, 0o500)
os.chown(tmppath, __salt__['file.user_to_uid'](user), -1)
try:
return __salt__['cmd.run_all'](
[python, tmppath],
runas=user,
cwd=cwd,
env={'VIRTUAL_ENV': cwd},
use_vt=use_vt,
python_shell=False,
)
finally:
os.remove(tmppath)
def _verify_safe_py_code(*args):
for arg in args:
if not salt.utils.verify.safe_py_code(arg):
raise SaltInvocationError(
'Unsafe python code detected in \'{0}\''.format(arg)
)
def _verify_virtualenv(venv_path):
bin_path = os.path.join(venv_path, 'bin/python')
if not os.path.exists(bin_path):
raise CommandExecutionError(
'Path \'{0}\' does not appear to be a virtualenv: bin/python not found.'.format(venv_path)
)
return bin_path
|
saltstack/salt | salt/modules/virtualenv_mod.py | get_distribution_path | python | def get_distribution_path(venv, distribution):
'''
Return the path to a distribution installed inside a virtualenv
.. versionadded:: 2016.3.0
venv
Path to the virtualenv.
distribution
Name of the distribution. Note, all non-alphanumeric characters
will be converted to dashes.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_distribution_path /path/to/my/venv my_distribution
'''
_verify_safe_py_code(distribution)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.get_distribution('{0}').location)".format(
distribution
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout'] | Return the path to a distribution installed inside a virtualenv
.. versionadded:: 2016.3.0
venv
Path to the virtualenv.
distribution
Name of the distribution. Note, all non-alphanumeric characters
will be converted to dashes.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_distribution_path /path/to/my/venv my_distribution | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virtualenv_mod.py#L346-L378 | [
"def _verify_virtualenv(venv_path):\n bin_path = os.path.join(venv_path, 'bin/python')\n if not os.path.exists(bin_path):\n raise CommandExecutionError(\n 'Path \\'{0}\\' does not appear to be a virtualenv: bin/python not found.'.format(venv_path)\n )\n return bin_path\n",
"def _verify_safe_py_code(*args):\n for arg in args:\n if not salt.utils.verify.safe_py_code(arg):\n raise SaltInvocationError(\n 'Unsafe python code detected in \\'{0}\\''.format(arg)\n )\n"
] | # -*- coding: utf-8 -*-
'''
Create virtualenv environments.
.. versionadded:: 0.17.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import glob
import shutil
import logging
import os
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.verify
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext.six import string_types
KNOWN_BINARY_NAMES = frozenset([
'pyvenv-{0}.{1}'.format(*sys.version_info[:2]),
'virtualenv-{0}.{1}'.format(*sys.version_info[:2]),
'pyvenv{0}'.format(sys.version_info[0]),
'virtualenv{0}'.format(sys.version_info[0]),
'pyvenv',
'virtualenv',
])
log = logging.getLogger(__name__)
__opts__ = {
'venv_bin': salt.utils.path.which_bin(KNOWN_BINARY_NAMES) or 'virtualenv'
}
__pillar__ = {}
# Define the module's virtual name
__virtualname__ = 'virtualenv'
def __virtual__():
return __virtualname__
def create(path,
venv_bin=None,
system_site_packages=False,
distribute=False,
clear=False,
python=None,
extra_search_dir=None,
never_download=None,
prompt=None,
pip=False,
symlinks=None,
upgrade=None,
user=None,
use_vt=False,
saltenv='base',
**kwargs):
'''
Create a virtualenv
path
The path to the virtualenv to be created
venv_bin
The name (and optionally path) of the virtualenv command. This can also
be set globally in the pillar data as ``venv_bin``.
Defaults to ``pyvenv`` or ``virtualenv``, depending on what is installed.
system_site_packages : False
Passthrough argument given to virtualenv or pyvenv
distribute : False
Passthrough argument given to virtualenv
pip : False
Install pip after creating a virtual environment. Implies
``distribute=True``
clear : False
Passthrough argument given to virtualenv or pyvenv
python : None (default)
Passthrough argument given to virtualenv
extra_search_dir : None (default)
Passthrough argument given to virtualenv
never_download : None (default)
Passthrough argument given to virtualenv if True
prompt : None (default)
Passthrough argument given to virtualenv if not None
symlinks : None
Passthrough argument given to pyvenv if True
upgrade : None
Passthrough argument given to pyvenv if True
user : None
Set ownership for the virtualenv
.. note::
On Windows you must also pass a ``password`` parameter. Additionally,
the user must have permissions to the location where the virtual
environment is being created
runas : None
Set ownership for the virtualenv
.. deprecated:: 2014.1.0
``user`` should be used instead
use_vt : False
Use VT terminal emulation (see output while installing)
.. versionadded:: 2015.5.0
saltenv : 'base'
Specify a different environment. The default environment is ``base``.
.. versionadded:: 2014.1.0
.. note::
The ``runas`` argument is deprecated as of 2014.1.0. ``user`` should be
used instead.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.create /path/to/new/virtualenv
'''
if venv_bin is None:
# Beginning in 3.6, pyvenv has been deprecated
# in favor of "python3 -m venv"
if sys.version_info >= (3, 6):
venv_bin = ['python3', '-m', 'venv']
else:
venv_bin = __pillar__.get('venv_bin') or __opts__.get('venv_bin')
if not isinstance(venv_bin, list):
cmd = [venv_bin]
else:
cmd = venv_bin
if 'pyvenv' not in venv_bin:
# ----- Stop the user if pyvenv only options are used --------------->
# If any of the following values are not None, it means that the user
# is actually passing a True or False value. Stop Him!
if upgrade is not None:
raise CommandExecutionError(
'The `upgrade`(`--upgrade`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
elif symlinks is not None:
raise CommandExecutionError(
'The `symlinks`(`--symlinks`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
# <---- Stop the user if pyvenv only options are used ----------------
# Virtualenv package
try:
import virtualenv
version = getattr(virtualenv, '__version__',
virtualenv.virtualenv_version)
virtualenv_version_info = tuple(
[int(i) for i in version.split('rc')[0].split('.')]
)
except ImportError:
# Unable to import?? Let's parse the version from the console
version_cmd = [venv_bin, '--version']
ret = __salt__['cmd.run_all'](
version_cmd, runas=user, python_shell=False, **kwargs
)
if ret['retcode'] > 0 or not ret['stdout'].strip():
raise CommandExecutionError(
'Unable to get the virtualenv version output using \'{0}\'. '
'Returned data: {1}'.format(version_cmd, ret)
)
virtualenv_version_info = tuple(
[int(i) for i in
ret['stdout'].strip().split('rc')[0].split('.')]
)
if distribute:
if virtualenv_version_info >= (1, 10):
log.info(
'The virtualenv \'--distribute\' option has been '
'deprecated in virtualenv(>=1.10), as such, the '
'\'distribute\' option to `virtualenv.create()` has '
'also been deprecated and it\'s not necessary anymore.'
)
else:
cmd.append('--distribute')
if python is not None and python.strip() != '':
if not salt.utils.path.which(python):
raise CommandExecutionError(
'Cannot find requested python ({0}).'.format(python)
)
cmd.append('--python={0}'.format(python))
if extra_search_dir is not None:
if isinstance(extra_search_dir, string_types) and \
extra_search_dir.strip() != '':
extra_search_dir = [
e.strip() for e in extra_search_dir.split(',')
]
for entry in extra_search_dir:
cmd.append('--extra-search-dir={0}'.format(entry))
if never_download is True:
if (1, 10) <= virtualenv_version_info < (14, 0, 0):
log.info(
'--never-download was deprecated in 1.10.0, but reimplemented in 14.0.0. '
'If this feature is needed, please install a supported virtualenv version.'
)
else:
cmd.append('--never-download')
if prompt is not None and prompt.strip() != '':
cmd.append('--prompt=\'{0}\''.format(prompt))
else:
# venv module from the Python >= 3.3 standard library
# ----- Stop the user if virtualenv only options are being used ----->
# If any of the following values are not None, it means that the user
# is actually passing a True or False value. Stop Him!
if python is not None and python.strip() != '':
raise CommandExecutionError(
'The `python`(`--python`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
elif extra_search_dir is not None and extra_search_dir.strip() != '':
raise CommandExecutionError(
'The `extra_search_dir`(`--extra-search-dir`) option is not '
'supported by \'{0}\''.format(venv_bin)
)
elif never_download is not None:
raise CommandExecutionError(
'The `never_download`(`--never-download`) option is not '
'supported by \'{0}\''.format(venv_bin)
)
elif prompt is not None and prompt.strip() != '':
raise CommandExecutionError(
'The `prompt`(`--prompt`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
# <---- Stop the user if virtualenv only options are being used ------
if upgrade is True:
cmd.append('--upgrade')
if symlinks is True:
cmd.append('--symlinks')
# Common options to virtualenv and pyvenv
if clear is True:
cmd.append('--clear')
if system_site_packages is True:
cmd.append('--system-site-packages')
# Finally the virtualenv path
cmd.append(path)
# Let's create the virtualenv
ret = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False, **kwargs)
if ret['retcode'] != 0:
# Something went wrong. Let's bail out now!
return ret
# Check if distribute and pip are already installed
if salt.utils.platform.is_windows():
venv_python = os.path.join(path, 'Scripts', 'python.exe')
venv_pip = os.path.join(path, 'Scripts', 'pip.exe')
venv_setuptools = os.path.join(path, 'Scripts', 'easy_install.exe')
else:
venv_python = os.path.join(path, 'bin', 'python')
venv_pip = os.path.join(path, 'bin', 'pip')
venv_setuptools = os.path.join(path, 'bin', 'easy_install')
# Install setuptools
if (pip or distribute) and not os.path.exists(venv_setuptools):
_install_script(
'https://bitbucket.org/pypa/setuptools/raw/default/ez_setup.py',
path, venv_python, user, saltenv=saltenv, use_vt=use_vt
)
# clear up the distribute archive which gets downloaded
for fpath in glob.glob(os.path.join(path, 'distribute-*.tar.gz*')):
os.unlink(fpath)
if ret['retcode'] != 0:
# Something went wrong. Let's bail out now!
return ret
# Install pip
if pip and not os.path.exists(venv_pip):
_ret = _install_script(
'https://bootstrap.pypa.io/get-pip.py',
path, venv_python, user, saltenv=saltenv, use_vt=use_vt
)
# Let's update the return dictionary with the details from the pip
# installation
ret.update(
retcode=_ret['retcode'],
stdout='{0}\n{1}'.format(ret['stdout'], _ret['stdout']).strip(),
stderr='{0}\n{1}'.format(ret['stderr'], _ret['stderr']).strip(),
)
return ret
def get_site_packages(venv):
'''
Return the path to the site-packages directory of a virtualenv
venv
Path to the virtualenv.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_site_packages /path/to/my/venv
'''
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'from distutils import sysconfig; '
'print(sysconfig.get_python_lib())'
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def get_resource_path(venv,
package=None,
resource=None):
'''
Return the path to a package resource installed inside a virtualenv
.. versionadded:: 2015.5.0
venv
Path to the virtualenv
package
Name of the package in which the resource resides
.. versionadded:: 2016.3.0
resource
Name of the resource of which the path is to be returned
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_resource_path /path/to/my/venv my_package my/resource.xml
'''
_verify_safe_py_code(package, resource)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.resource_filename('{0}', '{1}'))".format(
package,
resource
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def get_resource_content(venv,
package=None,
resource=None):
'''
Return the content of a package resource installed inside a virtualenv
.. versionadded:: 2015.5.0
venv
Path to the virtualenv
package
Name of the package in which the resource resides
.. versionadded:: 2016.3.0
resource
Name of the resource of which the content is to be returned
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_resource_content /path/to/my/venv my_package my/resource.xml
'''
_verify_safe_py_code(package, resource)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.resource_string('{0}', '{1}'))".format(
package,
resource
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def _install_script(source, cwd, python, user, saltenv='base', use_vt=False):
if not salt.utils.platform.is_windows():
tmppath = salt.utils.files.mkstemp(dir=cwd)
else:
tmppath = __salt__['cp.cache_file'](source, saltenv)
if not salt.utils.platform.is_windows():
fn_ = __salt__['cp.cache_file'](source, saltenv)
shutil.copyfile(fn_, tmppath)
os.chmod(tmppath, 0o500)
os.chown(tmppath, __salt__['file.user_to_uid'](user), -1)
try:
return __salt__['cmd.run_all'](
[python, tmppath],
runas=user,
cwd=cwd,
env={'VIRTUAL_ENV': cwd},
use_vt=use_vt,
python_shell=False,
)
finally:
os.remove(tmppath)
def _verify_safe_py_code(*args):
for arg in args:
if not salt.utils.verify.safe_py_code(arg):
raise SaltInvocationError(
'Unsafe python code detected in \'{0}\''.format(arg)
)
def _verify_virtualenv(venv_path):
bin_path = os.path.join(venv_path, 'bin/python')
if not os.path.exists(bin_path):
raise CommandExecutionError(
'Path \'{0}\' does not appear to be a virtualenv: bin/python not found.'.format(venv_path)
)
return bin_path
|
saltstack/salt | salt/modules/virtualenv_mod.py | get_resource_path | python | def get_resource_path(venv,
package=None,
resource=None):
'''
Return the path to a package resource installed inside a virtualenv
.. versionadded:: 2015.5.0
venv
Path to the virtualenv
package
Name of the package in which the resource resides
.. versionadded:: 2016.3.0
resource
Name of the resource of which the path is to be returned
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_resource_path /path/to/my/venv my_package my/resource.xml
'''
_verify_safe_py_code(package, resource)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.resource_filename('{0}', '{1}'))".format(
package,
resource
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout'] | Return the path to a package resource installed inside a virtualenv
.. versionadded:: 2015.5.0
venv
Path to the virtualenv
package
Name of the package in which the resource resides
.. versionadded:: 2016.3.0
resource
Name of the resource of which the path is to be returned
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_resource_path /path/to/my/venv my_package my/resource.xml | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virtualenv_mod.py#L381-L423 | [
"def _verify_virtualenv(venv_path):\n bin_path = os.path.join(venv_path, 'bin/python')\n if not os.path.exists(bin_path):\n raise CommandExecutionError(\n 'Path \\'{0}\\' does not appear to be a virtualenv: bin/python not found.'.format(venv_path)\n )\n return bin_path\n",
"def _verify_safe_py_code(*args):\n for arg in args:\n if not salt.utils.verify.safe_py_code(arg):\n raise SaltInvocationError(\n 'Unsafe python code detected in \\'{0}\\''.format(arg)\n )\n"
] | # -*- coding: utf-8 -*-
'''
Create virtualenv environments.
.. versionadded:: 0.17.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import glob
import shutil
import logging
import os
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.verify
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.ext.six import string_types
KNOWN_BINARY_NAMES = frozenset([
'pyvenv-{0}.{1}'.format(*sys.version_info[:2]),
'virtualenv-{0}.{1}'.format(*sys.version_info[:2]),
'pyvenv{0}'.format(sys.version_info[0]),
'virtualenv{0}'.format(sys.version_info[0]),
'pyvenv',
'virtualenv',
])
log = logging.getLogger(__name__)
__opts__ = {
'venv_bin': salt.utils.path.which_bin(KNOWN_BINARY_NAMES) or 'virtualenv'
}
__pillar__ = {}
# Define the module's virtual name
__virtualname__ = 'virtualenv'
def __virtual__():
return __virtualname__
def create(path,
venv_bin=None,
system_site_packages=False,
distribute=False,
clear=False,
python=None,
extra_search_dir=None,
never_download=None,
prompt=None,
pip=False,
symlinks=None,
upgrade=None,
user=None,
use_vt=False,
saltenv='base',
**kwargs):
'''
Create a virtualenv
path
The path to the virtualenv to be created
venv_bin
The name (and optionally path) of the virtualenv command. This can also
be set globally in the pillar data as ``venv_bin``.
Defaults to ``pyvenv`` or ``virtualenv``, depending on what is installed.
system_site_packages : False
Passthrough argument given to virtualenv or pyvenv
distribute : False
Passthrough argument given to virtualenv
pip : False
Install pip after creating a virtual environment. Implies
``distribute=True``
clear : False
Passthrough argument given to virtualenv or pyvenv
python : None (default)
Passthrough argument given to virtualenv
extra_search_dir : None (default)
Passthrough argument given to virtualenv
never_download : None (default)
Passthrough argument given to virtualenv if True
prompt : None (default)
Passthrough argument given to virtualenv if not None
symlinks : None
Passthrough argument given to pyvenv if True
upgrade : None
Passthrough argument given to pyvenv if True
user : None
Set ownership for the virtualenv
.. note::
On Windows you must also pass a ``password`` parameter. Additionally,
the user must have permissions to the location where the virtual
environment is being created
runas : None
Set ownership for the virtualenv
.. deprecated:: 2014.1.0
``user`` should be used instead
use_vt : False
Use VT terminal emulation (see output while installing)
.. versionadded:: 2015.5.0
saltenv : 'base'
Specify a different environment. The default environment is ``base``.
.. versionadded:: 2014.1.0
.. note::
The ``runas`` argument is deprecated as of 2014.1.0. ``user`` should be
used instead.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.create /path/to/new/virtualenv
'''
if venv_bin is None:
# Beginning in 3.6, pyvenv has been deprecated
# in favor of "python3 -m venv"
if sys.version_info >= (3, 6):
venv_bin = ['python3', '-m', 'venv']
else:
venv_bin = __pillar__.get('venv_bin') or __opts__.get('venv_bin')
if not isinstance(venv_bin, list):
cmd = [venv_bin]
else:
cmd = venv_bin
if 'pyvenv' not in venv_bin:
# ----- Stop the user if pyvenv only options are used --------------->
# If any of the following values are not None, it means that the user
# is actually passing a True or False value. Stop Him!
if upgrade is not None:
raise CommandExecutionError(
'The `upgrade`(`--upgrade`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
elif symlinks is not None:
raise CommandExecutionError(
'The `symlinks`(`--symlinks`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
# <---- Stop the user if pyvenv only options are used ----------------
# Virtualenv package
try:
import virtualenv
version = getattr(virtualenv, '__version__',
virtualenv.virtualenv_version)
virtualenv_version_info = tuple(
[int(i) for i in version.split('rc')[0].split('.')]
)
except ImportError:
# Unable to import?? Let's parse the version from the console
version_cmd = [venv_bin, '--version']
ret = __salt__['cmd.run_all'](
version_cmd, runas=user, python_shell=False, **kwargs
)
if ret['retcode'] > 0 or not ret['stdout'].strip():
raise CommandExecutionError(
'Unable to get the virtualenv version output using \'{0}\'. '
'Returned data: {1}'.format(version_cmd, ret)
)
virtualenv_version_info = tuple(
[int(i) for i in
ret['stdout'].strip().split('rc')[0].split('.')]
)
if distribute:
if virtualenv_version_info >= (1, 10):
log.info(
'The virtualenv \'--distribute\' option has been '
'deprecated in virtualenv(>=1.10), as such, the '
'\'distribute\' option to `virtualenv.create()` has '
'also been deprecated and it\'s not necessary anymore.'
)
else:
cmd.append('--distribute')
if python is not None and python.strip() != '':
if not salt.utils.path.which(python):
raise CommandExecutionError(
'Cannot find requested python ({0}).'.format(python)
)
cmd.append('--python={0}'.format(python))
if extra_search_dir is not None:
if isinstance(extra_search_dir, string_types) and \
extra_search_dir.strip() != '':
extra_search_dir = [
e.strip() for e in extra_search_dir.split(',')
]
for entry in extra_search_dir:
cmd.append('--extra-search-dir={0}'.format(entry))
if never_download is True:
if (1, 10) <= virtualenv_version_info < (14, 0, 0):
log.info(
'--never-download was deprecated in 1.10.0, but reimplemented in 14.0.0. '
'If this feature is needed, please install a supported virtualenv version.'
)
else:
cmd.append('--never-download')
if prompt is not None and prompt.strip() != '':
cmd.append('--prompt=\'{0}\''.format(prompt))
else:
# venv module from the Python >= 3.3 standard library
# ----- Stop the user if virtualenv only options are being used ----->
# If any of the following values are not None, it means that the user
# is actually passing a True or False value. Stop Him!
if python is not None and python.strip() != '':
raise CommandExecutionError(
'The `python`(`--python`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
elif extra_search_dir is not None and extra_search_dir.strip() != '':
raise CommandExecutionError(
'The `extra_search_dir`(`--extra-search-dir`) option is not '
'supported by \'{0}\''.format(venv_bin)
)
elif never_download is not None:
raise CommandExecutionError(
'The `never_download`(`--never-download`) option is not '
'supported by \'{0}\''.format(venv_bin)
)
elif prompt is not None and prompt.strip() != '':
raise CommandExecutionError(
'The `prompt`(`--prompt`) option is not supported '
'by \'{0}\''.format(venv_bin)
)
# <---- Stop the user if virtualenv only options are being used ------
if upgrade is True:
cmd.append('--upgrade')
if symlinks is True:
cmd.append('--symlinks')
# Common options to virtualenv and pyvenv
if clear is True:
cmd.append('--clear')
if system_site_packages is True:
cmd.append('--system-site-packages')
# Finally the virtualenv path
cmd.append(path)
# Let's create the virtualenv
ret = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False, **kwargs)
if ret['retcode'] != 0:
# Something went wrong. Let's bail out now!
return ret
# Check if distribute and pip are already installed
if salt.utils.platform.is_windows():
venv_python = os.path.join(path, 'Scripts', 'python.exe')
venv_pip = os.path.join(path, 'Scripts', 'pip.exe')
venv_setuptools = os.path.join(path, 'Scripts', 'easy_install.exe')
else:
venv_python = os.path.join(path, 'bin', 'python')
venv_pip = os.path.join(path, 'bin', 'pip')
venv_setuptools = os.path.join(path, 'bin', 'easy_install')
# Install setuptools
if (pip or distribute) and not os.path.exists(venv_setuptools):
_install_script(
'https://bitbucket.org/pypa/setuptools/raw/default/ez_setup.py',
path, venv_python, user, saltenv=saltenv, use_vt=use_vt
)
# clear up the distribute archive which gets downloaded
for fpath in glob.glob(os.path.join(path, 'distribute-*.tar.gz*')):
os.unlink(fpath)
if ret['retcode'] != 0:
# Something went wrong. Let's bail out now!
return ret
# Install pip
if pip and not os.path.exists(venv_pip):
_ret = _install_script(
'https://bootstrap.pypa.io/get-pip.py',
path, venv_python, user, saltenv=saltenv, use_vt=use_vt
)
# Let's update the return dictionary with the details from the pip
# installation
ret.update(
retcode=_ret['retcode'],
stdout='{0}\n{1}'.format(ret['stdout'], _ret['stdout']).strip(),
stderr='{0}\n{1}'.format(ret['stderr'], _ret['stderr']).strip(),
)
return ret
def get_site_packages(venv):
'''
Return the path to the site-packages directory of a virtualenv
venv
Path to the virtualenv.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_site_packages /path/to/my/venv
'''
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'from distutils import sysconfig; '
'print(sysconfig.get_python_lib())'
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def get_distribution_path(venv, distribution):
'''
Return the path to a distribution installed inside a virtualenv
.. versionadded:: 2016.3.0
venv
Path to the virtualenv.
distribution
Name of the distribution. Note, all non-alphanumeric characters
will be converted to dashes.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_distribution_path /path/to/my/venv my_distribution
'''
_verify_safe_py_code(distribution)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.get_distribution('{0}').location)".format(
distribution
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def get_resource_content(venv,
package=None,
resource=None):
'''
Return the content of a package resource installed inside a virtualenv
.. versionadded:: 2015.5.0
venv
Path to the virtualenv
package
Name of the package in which the resource resides
.. versionadded:: 2016.3.0
resource
Name of the resource of which the content is to be returned
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_resource_content /path/to/my/venv my_package my/resource.xml
'''
_verify_safe_py_code(package, resource)
bin_path = _verify_virtualenv(venv)
ret = __salt__['cmd.exec_code_all'](
bin_path,
'import pkg_resources; '
"print(pkg_resources.resource_string('{0}', '{1}'))".format(
package,
resource
)
)
if ret['retcode'] != 0:
raise CommandExecutionError('{stdout}\n{stderr}'.format(**ret))
return ret['stdout']
def _install_script(source, cwd, python, user, saltenv='base', use_vt=False):
if not salt.utils.platform.is_windows():
tmppath = salt.utils.files.mkstemp(dir=cwd)
else:
tmppath = __salt__['cp.cache_file'](source, saltenv)
if not salt.utils.platform.is_windows():
fn_ = __salt__['cp.cache_file'](source, saltenv)
shutil.copyfile(fn_, tmppath)
os.chmod(tmppath, 0o500)
os.chown(tmppath, __salt__['file.user_to_uid'](user), -1)
try:
return __salt__['cmd.run_all'](
[python, tmppath],
runas=user,
cwd=cwd,
env={'VIRTUAL_ENV': cwd},
use_vt=use_vt,
python_shell=False,
)
finally:
os.remove(tmppath)
def _verify_safe_py_code(*args):
for arg in args:
if not salt.utils.verify.safe_py_code(arg):
raise SaltInvocationError(
'Unsafe python code detected in \'{0}\''.format(arg)
)
def _verify_virtualenv(venv_path):
bin_path = os.path.join(venv_path, 'bin/python')
if not os.path.exists(bin_path):
raise CommandExecutionError(
'Path \'{0}\' does not appear to be a virtualenv: bin/python not found.'.format(venv_path)
)
return bin_path
|
saltstack/salt | salt/cloud/clouds/libvirt.py | list_nodes | python | def list_nodes(call=None):
'''
Return a list of the VMs
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
providers = __opts__.get('providers', {})
ret = {}
providers_to_check = [_f for _f in [cfg.get('libvirt') for cfg in six.itervalues(providers)] if _f]
for provider in providers_to_check:
conn = __get_conn(provider['url'])
domains = conn.listAllDomains()
for domain in domains:
data = {
'id': domain.UUIDString(),
'image': '',
'size': '',
'state': VIRT_STATE_NAME_MAP[domain.state()[0]],
'private_ips': [],
'public_ips': get_domain_ips(domain, libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE)}
# TODO: Annoyingly name is not guaranteed to be unique, but the id will not work in other places
ret[domain.name()] = data
return ret | Return a list of the VMs
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list) | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/libvirt.py#L162-L198 | [
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n",
"def __get_conn(url):\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n try:\n conn = libvirt.open(url)\n except Exception:\n raise SaltCloudExecutionFailure(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'], url\n )\n )\n return conn\n",
"def get_domain_ips(domain, ip_source):\n ips = []\n state = domain.state(0)\n if state[0] != libvirt.VIR_DOMAIN_RUNNING:\n return ips\n try:\n addresses = domain.interfaceAddresses(ip_source, 0)\n except libvirt.libvirtError as error:\n log.info(\"Exception polling address %s\", error)\n return ips\n\n for (name, val) in six.iteritems(addresses):\n if val['addrs']:\n for addr in val['addrs']:\n tp = to_ip_addr_type(addr['type'])\n log.info(\"Found address %s\", addr)\n if tp == \"ipv4\":\n ips.append(addr['addr'])\n return ips\n"
] | # -*- coding: utf-8 -*-
'''
Libvirt Cloud Module
====================
Example provider:
.. code-block:: yaml
# A provider maps to a libvirt instance
my-libvirt-config:
driver: libvirt
# url: "qemu+ssh://user@remotekvm/system?socket=/var/run/libvirt/libvirt-sock"
url: qemu:///system
Example profile:
.. code-block:: yaml
base-itest:
# points back at provider configuration e.g. the libvirt daemon to talk to
provider: my-libvirt-config
base_domain: base-image
# ip_source = [ ip-learning | qemu-agent ]
ip_source: ip-learning
# clone_strategy = [ quick | full ]
clone_strategy: quick
ssh_username: vagrant
# has_ssh_agent: True
password: vagrant
# if /tmp is mounted noexec do workaround
deploy_command: sh /tmp/.saltcloud/deploy.sh
# -F makes the bootstrap script overwrite existing config
# which make reprovisioning a box work
script_args: -F
grains:
sushi: more tasty
# point at the another master at another port
minion:
master: 192.168.16.1
master_port: 5506
Tested on:
- Fedora 26 (libvirt 3.2.1, qemu 2.9.1)
- Fedora 25 (libvirt 1.3.3.2, qemu 2.6.1)
- Fedora 23 (libvirt 1.2.18, qemu 2.4.1)
- Centos 7 (libvirt 1.2.17, qemu 1.5.3)
'''
# TODO: look at event descriptions here:
# https://docs.saltstack.com/en/latest/topics/cloud/reactor.html
# TODO: support reboot? salt-cloud -a reboot vm1 vm2 vm2
# TODO: by using metadata tags in the libvirt XML we could make provider only
# manage domains that we actually created
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import uuid
import os
from xml.etree import ElementTree
# Import 3rd-party libs
from salt.ext import six
try:
import libvirt # pylint: disable=import-error
from libvirt import libvirtError
HAS_LIBVIRT = True
except ImportError:
HAS_LIBVIRT = False
# Import salt libs
import salt.config as config
import salt.utils.cloud
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudExecutionFailure,
SaltCloudNotFound,
SaltCloudSystemExit
)
VIRT_STATE_NAME_MAP = {0: 'running',
1: 'running',
2: 'running',
3: 'paused',
4: 'shutdown',
5: 'shutdown',
6: 'crashed'}
IP_LEARNING_XML = """<filterref filter='clean-traffic'>
<parameter name='CTRL_IP_LEARNING' value='any'/>
</filterref>"""
__virtualname__ = 'libvirt'
# Set up logging
log = logging.getLogger(__name__)
def libvirt_error_handler(ctx, error): # pylint: disable=unused-argument
'''
Redirect stderr prints from libvirt to salt logging.
'''
log.debug("libvirt error %s", error)
if HAS_LIBVIRT:
libvirt.registerErrorHandler(f=libvirt_error_handler, ctx=None)
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_LIBVIRT:
return False, 'Unable to locate or import python libvirt library.'
if get_configured_provider() is False:
return False, 'The \'libvirt\' provider is not configured.'
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('url',)
)
def __get_conn(url):
# This has only been tested on kvm and xen, it needs to be expanded to
# support all vm layers supported by libvirt
try:
conn = libvirt.open(url)
except Exception:
raise SaltCloudExecutionFailure(
'Sorry, {0} failed to open a connection to the hypervisor '
'software at {1}'.format(
__grains__['fqdn'], url
)
)
return conn
def list_nodes_full(call=None):
'''
Because this module is not specific to any cloud providers, there will be
no nodes to list.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
return list_nodes(call)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called '
'with -f or --function.'
)
selection = __opts__.get('query.selection')
if not selection:
raise SaltCloudSystemExit(
'query.selection not found in /etc/salt/cloud'
)
# TODO: somewhat doubt the implementation of cloud.list_nodes_select
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), selection, call,
)
def to_ip_addr_type(addr_type):
if addr_type == libvirt.VIR_IP_ADDR_TYPE_IPV4:
return "ipv4"
elif addr_type == libvirt.VIR_IP_ADDR_TYPE_IPV6:
return "ipv6"
def get_domain_ips(domain, ip_source):
ips = []
state = domain.state(0)
if state[0] != libvirt.VIR_DOMAIN_RUNNING:
return ips
try:
addresses = domain.interfaceAddresses(ip_source, 0)
except libvirt.libvirtError as error:
log.info("Exception polling address %s", error)
return ips
for (name, val) in six.iteritems(addresses):
if val['addrs']:
for addr in val['addrs']:
tp = to_ip_addr_type(addr['type'])
log.info("Found address %s", addr)
if tp == "ipv4":
ips.append(addr['addr'])
return ips
def get_domain_ip(domain, idx, ip_source, skip_loopback=True):
ips = get_domain_ips(domain, ip_source)
if skip_loopback:
ips = [ip for ip in ips if not ip.startswith('127.')]
if not ips or len(ips) <= idx:
return None
return ips[idx]
def create(vm_):
'''
Provision a single machine
'''
clone_strategy = vm_.get('clone_strategy') or 'full'
if clone_strategy not in ('quick', 'full'):
raise SaltCloudSystemExit("'clone_strategy' must be one of quick or full. Got '{0}'".format(clone_strategy))
ip_source = vm_.get('ip_source') or 'ip-learning'
if ip_source not in ('ip-learning', 'qemu-agent'):
raise SaltCloudSystemExit("'ip_source' must be one of qemu-agent or ip-learning. Got '{0}'".format(ip_source))
validate_xml = vm_.get('validate_xml') if vm_.get('validate_xml') is not None else True
log.info("Cloning '%s' with strategy '%s' validate_xml='%s'", vm_['name'], clone_strategy, validate_xml)
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'libvirt',
vm_['profile']) is False:
return False
except AttributeError:
pass
# TODO: check name qemu/libvirt will choke on some characters (like '/')?
name = vm_['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']
)
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
# wait_for_instance requires private_key
vm_['private_key'] = key_filename
cleanup = []
try:
# clone the vm
base = vm_['base_domain']
conn = __get_conn(vm_['url'])
try:
# for idempotency the salt-bootstrap needs -F argument
# script_args: -F
clone_domain = conn.lookupByName(name)
except libvirtError as e:
domain = conn.lookupByName(base)
# TODO: ensure base is shut down before cloning
xml = domain.XMLDesc(0)
kwargs = {
'name': name,
'base_domain': base,
}
__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']
)
log.debug("Source machine XML '%s'", xml)
domain_xml = ElementTree.fromstring(xml)
domain_xml.find('./name').text = name
if domain_xml.find('./description') is None:
description_elem = ElementTree.Element('description')
domain_xml.insert(0, description_elem)
description = domain_xml.find('./description')
description.text = "Cloned from {0}".format(base)
domain_xml.remove(domain_xml.find('./uuid'))
for iface_xml in domain_xml.findall('./devices/interface'):
iface_xml.remove(iface_xml.find('./mac'))
# enable IP learning, this might be a default behaviour...
# Don't always enable since it can cause problems through libvirt-4.5
if ip_source == 'ip-learning' and iface_xml.find("./filterref/parameter[@name='CTRL_IP_LEARNING']") is None:
iface_xml.append(ElementTree.fromstring(IP_LEARNING_XML))
# If a qemu agent is defined we need to fix the path to its socket
# <channel type='unix'>
# <source mode='bind' path='/var/lib/libvirt/qemu/channel/target/domain-<dom-name>/org.qemu.guest_agent.0'/>
# <target type='virtio' name='org.qemu.guest_agent.0'/>
# <address type='virtio-serial' controller='0' bus='0' port='2'/>
# </channel>
for agent_xml in domain_xml.findall("""./devices/channel[@type='unix']"""):
# is org.qemu.guest_agent.0 an option?
if agent_xml.find("""./target[@type='virtio'][@name='org.qemu.guest_agent.0']""") is not None:
source_element = agent_xml.find("""./source[@mode='bind']""")
# see if there is a path element that needs rewriting
if source_element and 'path' in source_element.attrib:
path = source_element.attrib['path']
new_path = path.replace('/domain-{0}/'.format(base), '/domain-{0}/'.format(name))
log.debug("Rewriting agent socket path to %s", new_path)
source_element.attrib['path'] = new_path
for disk in domain_xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
# print "Disk: ", ElementTree.tostring(disk)
# check if we can clone
driver = disk.find("./driver[@name='qemu']")
if driver is None:
# Err on the safe side
raise SaltCloudExecutionFailure("Non qemu driver disk encountered bailing out.")
disk_type = driver.attrib.get('type')
log.info("disk attributes %s", disk.attrib)
if disk_type == 'qcow2':
source = disk.find("./source").attrib['file']
pool, volume = find_pool_and_volume(conn, source)
if clone_strategy == 'quick':
new_volume = pool.createXML(create_volume_with_backing_store_xml(volume), 0)
else:
new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
cleanup.append({'what': 'volume', 'item': new_volume})
disk.find("./source").attrib['file'] = new_volume.path()
elif disk_type == 'raw':
source = disk.find("./source").attrib['file']
pool, volume = find_pool_and_volume(conn, source)
# TODO: more control on the cloned disk type
new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
cleanup.append({'what': 'volume', 'item': new_volume})
disk.find("./source").attrib['file'] = new_volume.path()
else:
raise SaltCloudExecutionFailure("Disk type '{0}' not supported".format(disk_type))
clone_xml = salt.utils.stringutils.to_str(ElementTree.tostring(domain_xml))
log.debug("Clone XML '%s'", clone_xml)
validate_flags = libvirt.VIR_DOMAIN_DEFINE_VALIDATE if validate_xml else 0
clone_domain = conn.defineXMLFlags(clone_xml, validate_flags)
cleanup.append({'what': 'domain', 'item': clone_domain})
clone_domain.createWithFlags(libvirt.VIR_DOMAIN_START_FORCE_BOOT)
log.debug("VM '%s'", vm_)
if ip_source == 'qemu-agent':
ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT
elif ip_source == 'ip-learning':
ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE
address = salt.utils.cloud.wait_for_ip(
get_domain_ip,
update_args=(clone_domain, 0, ip_source),
timeout=config.get_cloud_config_value('wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value('wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value('wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
log.info('Address = %s', address)
vm_['ssh_host'] = address
# the bootstrap script needs to be installed first in /etc/salt/cloud.deploy.d/
# salt-cloud -u is your friend
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
__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
except Exception as e: # pylint: disable=broad-except
do_cleanup(cleanup)
# throw the root cause after cleanup
raise e
def do_cleanup(cleanup):
'''
Clean up clone domain leftovers as much as possible.
Extra robust clean up in order to deal with some small changes in libvirt
behavior over time. Passed in volumes and domains are deleted, any errors
are ignored. Used when cloning/provisioning a domain fails.
:param cleanup: list containing dictonaries with two keys: 'what' and 'item'.
If 'what' is domain the 'item' is a libvirt domain object.
If 'what' is volume then the item is a libvirt volume object.
Returns:
none
.. versionadded: 2017.7.3
'''
log.info('Cleaning up after exception')
for leftover in cleanup:
what = leftover['what']
item = leftover['item']
if what == 'domain':
log.info('Cleaning up %s %s', what, item.name())
try:
item.destroy()
log.debug('%s %s forced off', what, item.name())
except libvirtError:
pass
try:
item.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+
libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+
libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)
log.debug('%s %s undefined', what, item.name())
except libvirtError:
pass
if what == 'volume':
try:
item.delete()
log.debug('%s %s cleaned up', what, item.name())
except libvirtError:
pass
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
"""
log.info("Attempting to delete instance %s", name)
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
found = []
providers = __opts__.get('providers', {})
providers_to_check = [_f for _f in [cfg.get('libvirt') for cfg in six.itervalues(providers)] if _f]
for provider in providers_to_check:
conn = __get_conn(provider['url'])
log.info("looking at %s", provider['url'])
try:
domain = conn.lookupByName(name)
found.append({'domain': domain, 'conn': conn})
except libvirtError:
pass
if not found:
return "{0} doesn't exist and can't be deleted".format(name)
if len(found) > 1:
return "{0} doesn't identify a unique machine leaving things".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
destroy_domain(found[0]['conn'], found[0]['domain'])
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def destroy_domain(conn, domain):
log.info('Destroying domain %s', domain.name())
try:
domain.destroy()
except libvirtError:
pass
volumes = get_domain_volumes(conn, domain)
for volume in volumes:
log.debug('Removing volume %s', volume.name())
volume.delete()
log.debug('Undefining domain %s', domain.name())
domain.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+
libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+
libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)
def create_volume_xml(volume):
template = """<volume>
<name>n</name>
<capacity>c</capacity>
<allocation>0</allocation>
<target>
<path>p</path>
<format type='qcow2'/>
<compat>1.1</compat>
</target>
</volume>
"""
volume_xml = ElementTree.fromstring(template)
# TODO: generate name
volume_xml.find('name').text = generate_new_name(volume.name())
log.debug("Volume: %s", dir(volume))
volume_xml.find('capacity').text = six.text_type(volume.info()[1])
volume_xml.find('./target/path').text = volume.path()
xml_string = salt.utils.stringutils.to_str(ElementTree.tostring(volume_xml))
log.debug("Creating %s", xml_string)
return xml_string
def create_volume_with_backing_store_xml(volume):
template = """<volume>
<name>n</name>
<capacity>c</capacity>
<allocation>0</allocation>
<target>
<format type='qcow2'/>
<compat>1.1</compat>
</target>
<backingStore>
<format type='qcow2'/>
<path>p</path>
</backingStore>
</volume>
"""
volume_xml = ElementTree.fromstring(template)
# TODO: generate name
volume_xml.find('name').text = generate_new_name(volume.name())
log.debug("volume: %s", dir(volume))
volume_xml.find('capacity').text = six.text_type(volume.info()[1])
volume_xml.find('./backingStore/path').text = volume.path()
xml_string = salt.utils.stringutils.to_str(ElementTree.tostring(volume_xml))
log.debug("Creating %s", xml_string)
return xml_string
def find_pool_and_volume(conn, path):
# active and persistent storage pools
# TODO: should we filter on type?
for sp in conn.listAllStoragePools(2+4):
for v in sp.listAllVolumes():
if v.path() == path:
return sp, v
raise SaltCloudNotFound('Could not find volume for path {0}'.format(path))
def generate_new_name(orig_name):
if '.' not in orig_name:
return '{0}-{1}'.format(orig_name, uuid.uuid1())
name, ext = orig_name.rsplit('.', 1)
return '{0}-{1}.{2}'.format(name, uuid.uuid1(), ext)
def get_domain_volumes(conn, domain):
volumes = []
xml = ElementTree.fromstring(domain.XMLDesc(0))
for disk in xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
if disk.find("./driver[@name='qemu'][@type='qcow2']") is not None:
source = disk.find("./source").attrib['file']
try:
pool, volume = find_pool_and_volume(conn, source)
volumes.append(volume)
except libvirtError:
log.warning("Disk not found '%s'", source)
return volumes
|
saltstack/salt | salt/cloud/clouds/libvirt.py | list_nodes_select | python | def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called '
'with -f or --function.'
)
selection = __opts__.get('query.selection')
if not selection:
raise SaltCloudSystemExit(
'query.selection not found in /etc/salt/cloud'
)
# TODO: somewhat doubt the implementation of cloud.list_nodes_select
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), selection, call,
) | Return a list of the VMs that are on the provider, with select fields | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/libvirt.py#L215-L235 | [
"def list_nodes_full(call=None):\n '''\n Because this module is not specific to any cloud providers, there will be\n no nodes to list.\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes_full function must be called '\n 'with -f or --function.'\n )\n\n return list_nodes(call)\n",
"def list_nodes_select(nodes, selection, call=None):\n '''\n Return a list of the VMs that are on the provider, with select fields\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes_select function must be called '\n 'with -f or --function.'\n )\n\n if 'error' in nodes:\n raise SaltCloudSystemExit(\n 'An error occurred while listing nodes: {0}'.format(\n nodes['error']['Errors']['Error']['Message']\n )\n )\n\n ret = {}\n for node in nodes:\n pairs = {}\n data = nodes[node]\n for key in data:\n if six.text_type(key) in selection:\n value = data[key]\n pairs[key] = value\n ret[node] = pairs\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
Libvirt Cloud Module
====================
Example provider:
.. code-block:: yaml
# A provider maps to a libvirt instance
my-libvirt-config:
driver: libvirt
# url: "qemu+ssh://user@remotekvm/system?socket=/var/run/libvirt/libvirt-sock"
url: qemu:///system
Example profile:
.. code-block:: yaml
base-itest:
# points back at provider configuration e.g. the libvirt daemon to talk to
provider: my-libvirt-config
base_domain: base-image
# ip_source = [ ip-learning | qemu-agent ]
ip_source: ip-learning
# clone_strategy = [ quick | full ]
clone_strategy: quick
ssh_username: vagrant
# has_ssh_agent: True
password: vagrant
# if /tmp is mounted noexec do workaround
deploy_command: sh /tmp/.saltcloud/deploy.sh
# -F makes the bootstrap script overwrite existing config
# which make reprovisioning a box work
script_args: -F
grains:
sushi: more tasty
# point at the another master at another port
minion:
master: 192.168.16.1
master_port: 5506
Tested on:
- Fedora 26 (libvirt 3.2.1, qemu 2.9.1)
- Fedora 25 (libvirt 1.3.3.2, qemu 2.6.1)
- Fedora 23 (libvirt 1.2.18, qemu 2.4.1)
- Centos 7 (libvirt 1.2.17, qemu 1.5.3)
'''
# TODO: look at event descriptions here:
# https://docs.saltstack.com/en/latest/topics/cloud/reactor.html
# TODO: support reboot? salt-cloud -a reboot vm1 vm2 vm2
# TODO: by using metadata tags in the libvirt XML we could make provider only
# manage domains that we actually created
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import uuid
import os
from xml.etree import ElementTree
# Import 3rd-party libs
from salt.ext import six
try:
import libvirt # pylint: disable=import-error
from libvirt import libvirtError
HAS_LIBVIRT = True
except ImportError:
HAS_LIBVIRT = False
# Import salt libs
import salt.config as config
import salt.utils.cloud
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudExecutionFailure,
SaltCloudNotFound,
SaltCloudSystemExit
)
VIRT_STATE_NAME_MAP = {0: 'running',
1: 'running',
2: 'running',
3: 'paused',
4: 'shutdown',
5: 'shutdown',
6: 'crashed'}
IP_LEARNING_XML = """<filterref filter='clean-traffic'>
<parameter name='CTRL_IP_LEARNING' value='any'/>
</filterref>"""
__virtualname__ = 'libvirt'
# Set up logging
log = logging.getLogger(__name__)
def libvirt_error_handler(ctx, error): # pylint: disable=unused-argument
'''
Redirect stderr prints from libvirt to salt logging.
'''
log.debug("libvirt error %s", error)
if HAS_LIBVIRT:
libvirt.registerErrorHandler(f=libvirt_error_handler, ctx=None)
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_LIBVIRT:
return False, 'Unable to locate or import python libvirt library.'
if get_configured_provider() is False:
return False, 'The \'libvirt\' provider is not configured.'
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('url',)
)
def __get_conn(url):
# This has only been tested on kvm and xen, it needs to be expanded to
# support all vm layers supported by libvirt
try:
conn = libvirt.open(url)
except Exception:
raise SaltCloudExecutionFailure(
'Sorry, {0} failed to open a connection to the hypervisor '
'software at {1}'.format(
__grains__['fqdn'], url
)
)
return conn
def list_nodes(call=None):
'''
Return a list of the VMs
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
providers = __opts__.get('providers', {})
ret = {}
providers_to_check = [_f for _f in [cfg.get('libvirt') for cfg in six.itervalues(providers)] if _f]
for provider in providers_to_check:
conn = __get_conn(provider['url'])
domains = conn.listAllDomains()
for domain in domains:
data = {
'id': domain.UUIDString(),
'image': '',
'size': '',
'state': VIRT_STATE_NAME_MAP[domain.state()[0]],
'private_ips': [],
'public_ips': get_domain_ips(domain, libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE)}
# TODO: Annoyingly name is not guaranteed to be unique, but the id will not work in other places
ret[domain.name()] = data
return ret
def list_nodes_full(call=None):
'''
Because this module is not specific to any cloud providers, there will be
no nodes to list.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
return list_nodes(call)
def to_ip_addr_type(addr_type):
if addr_type == libvirt.VIR_IP_ADDR_TYPE_IPV4:
return "ipv4"
elif addr_type == libvirt.VIR_IP_ADDR_TYPE_IPV6:
return "ipv6"
def get_domain_ips(domain, ip_source):
ips = []
state = domain.state(0)
if state[0] != libvirt.VIR_DOMAIN_RUNNING:
return ips
try:
addresses = domain.interfaceAddresses(ip_source, 0)
except libvirt.libvirtError as error:
log.info("Exception polling address %s", error)
return ips
for (name, val) in six.iteritems(addresses):
if val['addrs']:
for addr in val['addrs']:
tp = to_ip_addr_type(addr['type'])
log.info("Found address %s", addr)
if tp == "ipv4":
ips.append(addr['addr'])
return ips
def get_domain_ip(domain, idx, ip_source, skip_loopback=True):
ips = get_domain_ips(domain, ip_source)
if skip_loopback:
ips = [ip for ip in ips if not ip.startswith('127.')]
if not ips or len(ips) <= idx:
return None
return ips[idx]
def create(vm_):
'''
Provision a single machine
'''
clone_strategy = vm_.get('clone_strategy') or 'full'
if clone_strategy not in ('quick', 'full'):
raise SaltCloudSystemExit("'clone_strategy' must be one of quick or full. Got '{0}'".format(clone_strategy))
ip_source = vm_.get('ip_source') or 'ip-learning'
if ip_source not in ('ip-learning', 'qemu-agent'):
raise SaltCloudSystemExit("'ip_source' must be one of qemu-agent or ip-learning. Got '{0}'".format(ip_source))
validate_xml = vm_.get('validate_xml') if vm_.get('validate_xml') is not None else True
log.info("Cloning '%s' with strategy '%s' validate_xml='%s'", vm_['name'], clone_strategy, validate_xml)
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'libvirt',
vm_['profile']) is False:
return False
except AttributeError:
pass
# TODO: check name qemu/libvirt will choke on some characters (like '/')?
name = vm_['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']
)
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
# wait_for_instance requires private_key
vm_['private_key'] = key_filename
cleanup = []
try:
# clone the vm
base = vm_['base_domain']
conn = __get_conn(vm_['url'])
try:
# for idempotency the salt-bootstrap needs -F argument
# script_args: -F
clone_domain = conn.lookupByName(name)
except libvirtError as e:
domain = conn.lookupByName(base)
# TODO: ensure base is shut down before cloning
xml = domain.XMLDesc(0)
kwargs = {
'name': name,
'base_domain': base,
}
__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']
)
log.debug("Source machine XML '%s'", xml)
domain_xml = ElementTree.fromstring(xml)
domain_xml.find('./name').text = name
if domain_xml.find('./description') is None:
description_elem = ElementTree.Element('description')
domain_xml.insert(0, description_elem)
description = domain_xml.find('./description')
description.text = "Cloned from {0}".format(base)
domain_xml.remove(domain_xml.find('./uuid'))
for iface_xml in domain_xml.findall('./devices/interface'):
iface_xml.remove(iface_xml.find('./mac'))
# enable IP learning, this might be a default behaviour...
# Don't always enable since it can cause problems through libvirt-4.5
if ip_source == 'ip-learning' and iface_xml.find("./filterref/parameter[@name='CTRL_IP_LEARNING']") is None:
iface_xml.append(ElementTree.fromstring(IP_LEARNING_XML))
# If a qemu agent is defined we need to fix the path to its socket
# <channel type='unix'>
# <source mode='bind' path='/var/lib/libvirt/qemu/channel/target/domain-<dom-name>/org.qemu.guest_agent.0'/>
# <target type='virtio' name='org.qemu.guest_agent.0'/>
# <address type='virtio-serial' controller='0' bus='0' port='2'/>
# </channel>
for agent_xml in domain_xml.findall("""./devices/channel[@type='unix']"""):
# is org.qemu.guest_agent.0 an option?
if agent_xml.find("""./target[@type='virtio'][@name='org.qemu.guest_agent.0']""") is not None:
source_element = agent_xml.find("""./source[@mode='bind']""")
# see if there is a path element that needs rewriting
if source_element and 'path' in source_element.attrib:
path = source_element.attrib['path']
new_path = path.replace('/domain-{0}/'.format(base), '/domain-{0}/'.format(name))
log.debug("Rewriting agent socket path to %s", new_path)
source_element.attrib['path'] = new_path
for disk in domain_xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
# print "Disk: ", ElementTree.tostring(disk)
# check if we can clone
driver = disk.find("./driver[@name='qemu']")
if driver is None:
# Err on the safe side
raise SaltCloudExecutionFailure("Non qemu driver disk encountered bailing out.")
disk_type = driver.attrib.get('type')
log.info("disk attributes %s", disk.attrib)
if disk_type == 'qcow2':
source = disk.find("./source").attrib['file']
pool, volume = find_pool_and_volume(conn, source)
if clone_strategy == 'quick':
new_volume = pool.createXML(create_volume_with_backing_store_xml(volume), 0)
else:
new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
cleanup.append({'what': 'volume', 'item': new_volume})
disk.find("./source").attrib['file'] = new_volume.path()
elif disk_type == 'raw':
source = disk.find("./source").attrib['file']
pool, volume = find_pool_and_volume(conn, source)
# TODO: more control on the cloned disk type
new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
cleanup.append({'what': 'volume', 'item': new_volume})
disk.find("./source").attrib['file'] = new_volume.path()
else:
raise SaltCloudExecutionFailure("Disk type '{0}' not supported".format(disk_type))
clone_xml = salt.utils.stringutils.to_str(ElementTree.tostring(domain_xml))
log.debug("Clone XML '%s'", clone_xml)
validate_flags = libvirt.VIR_DOMAIN_DEFINE_VALIDATE if validate_xml else 0
clone_domain = conn.defineXMLFlags(clone_xml, validate_flags)
cleanup.append({'what': 'domain', 'item': clone_domain})
clone_domain.createWithFlags(libvirt.VIR_DOMAIN_START_FORCE_BOOT)
log.debug("VM '%s'", vm_)
if ip_source == 'qemu-agent':
ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT
elif ip_source == 'ip-learning':
ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE
address = salt.utils.cloud.wait_for_ip(
get_domain_ip,
update_args=(clone_domain, 0, ip_source),
timeout=config.get_cloud_config_value('wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value('wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value('wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
log.info('Address = %s', address)
vm_['ssh_host'] = address
# the bootstrap script needs to be installed first in /etc/salt/cloud.deploy.d/
# salt-cloud -u is your friend
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
__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
except Exception as e: # pylint: disable=broad-except
do_cleanup(cleanup)
# throw the root cause after cleanup
raise e
def do_cleanup(cleanup):
'''
Clean up clone domain leftovers as much as possible.
Extra robust clean up in order to deal with some small changes in libvirt
behavior over time. Passed in volumes and domains are deleted, any errors
are ignored. Used when cloning/provisioning a domain fails.
:param cleanup: list containing dictonaries with two keys: 'what' and 'item'.
If 'what' is domain the 'item' is a libvirt domain object.
If 'what' is volume then the item is a libvirt volume object.
Returns:
none
.. versionadded: 2017.7.3
'''
log.info('Cleaning up after exception')
for leftover in cleanup:
what = leftover['what']
item = leftover['item']
if what == 'domain':
log.info('Cleaning up %s %s', what, item.name())
try:
item.destroy()
log.debug('%s %s forced off', what, item.name())
except libvirtError:
pass
try:
item.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+
libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+
libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)
log.debug('%s %s undefined', what, item.name())
except libvirtError:
pass
if what == 'volume':
try:
item.delete()
log.debug('%s %s cleaned up', what, item.name())
except libvirtError:
pass
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
"""
log.info("Attempting to delete instance %s", name)
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
found = []
providers = __opts__.get('providers', {})
providers_to_check = [_f for _f in [cfg.get('libvirt') for cfg in six.itervalues(providers)] if _f]
for provider in providers_to_check:
conn = __get_conn(provider['url'])
log.info("looking at %s", provider['url'])
try:
domain = conn.lookupByName(name)
found.append({'domain': domain, 'conn': conn})
except libvirtError:
pass
if not found:
return "{0} doesn't exist and can't be deleted".format(name)
if len(found) > 1:
return "{0} doesn't identify a unique machine leaving things".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
destroy_domain(found[0]['conn'], found[0]['domain'])
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def destroy_domain(conn, domain):
log.info('Destroying domain %s', domain.name())
try:
domain.destroy()
except libvirtError:
pass
volumes = get_domain_volumes(conn, domain)
for volume in volumes:
log.debug('Removing volume %s', volume.name())
volume.delete()
log.debug('Undefining domain %s', domain.name())
domain.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+
libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+
libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)
def create_volume_xml(volume):
template = """<volume>
<name>n</name>
<capacity>c</capacity>
<allocation>0</allocation>
<target>
<path>p</path>
<format type='qcow2'/>
<compat>1.1</compat>
</target>
</volume>
"""
volume_xml = ElementTree.fromstring(template)
# TODO: generate name
volume_xml.find('name').text = generate_new_name(volume.name())
log.debug("Volume: %s", dir(volume))
volume_xml.find('capacity').text = six.text_type(volume.info()[1])
volume_xml.find('./target/path').text = volume.path()
xml_string = salt.utils.stringutils.to_str(ElementTree.tostring(volume_xml))
log.debug("Creating %s", xml_string)
return xml_string
def create_volume_with_backing_store_xml(volume):
template = """<volume>
<name>n</name>
<capacity>c</capacity>
<allocation>0</allocation>
<target>
<format type='qcow2'/>
<compat>1.1</compat>
</target>
<backingStore>
<format type='qcow2'/>
<path>p</path>
</backingStore>
</volume>
"""
volume_xml = ElementTree.fromstring(template)
# TODO: generate name
volume_xml.find('name').text = generate_new_name(volume.name())
log.debug("volume: %s", dir(volume))
volume_xml.find('capacity').text = six.text_type(volume.info()[1])
volume_xml.find('./backingStore/path').text = volume.path()
xml_string = salt.utils.stringutils.to_str(ElementTree.tostring(volume_xml))
log.debug("Creating %s", xml_string)
return xml_string
def find_pool_and_volume(conn, path):
# active and persistent storage pools
# TODO: should we filter on type?
for sp in conn.listAllStoragePools(2+4):
for v in sp.listAllVolumes():
if v.path() == path:
return sp, v
raise SaltCloudNotFound('Could not find volume for path {0}'.format(path))
def generate_new_name(orig_name):
if '.' not in orig_name:
return '{0}-{1}'.format(orig_name, uuid.uuid1())
name, ext = orig_name.rsplit('.', 1)
return '{0}-{1}.{2}'.format(name, uuid.uuid1(), ext)
def get_domain_volumes(conn, domain):
volumes = []
xml = ElementTree.fromstring(domain.XMLDesc(0))
for disk in xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
if disk.find("./driver[@name='qemu'][@type='qcow2']") is not None:
source = disk.find("./source").attrib['file']
try:
pool, volume = find_pool_and_volume(conn, source)
volumes.append(volume)
except libvirtError:
log.warning("Disk not found '%s'", source)
return volumes
|
saltstack/salt | salt/cloud/clouds/libvirt.py | create | python | def create(vm_):
'''
Provision a single machine
'''
clone_strategy = vm_.get('clone_strategy') or 'full'
if clone_strategy not in ('quick', 'full'):
raise SaltCloudSystemExit("'clone_strategy' must be one of quick or full. Got '{0}'".format(clone_strategy))
ip_source = vm_.get('ip_source') or 'ip-learning'
if ip_source not in ('ip-learning', 'qemu-agent'):
raise SaltCloudSystemExit("'ip_source' must be one of qemu-agent or ip-learning. Got '{0}'".format(ip_source))
validate_xml = vm_.get('validate_xml') if vm_.get('validate_xml') is not None else True
log.info("Cloning '%s' with strategy '%s' validate_xml='%s'", vm_['name'], clone_strategy, validate_xml)
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'libvirt',
vm_['profile']) is False:
return False
except AttributeError:
pass
# TODO: check name qemu/libvirt will choke on some characters (like '/')?
name = vm_['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']
)
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
# wait_for_instance requires private_key
vm_['private_key'] = key_filename
cleanup = []
try:
# clone the vm
base = vm_['base_domain']
conn = __get_conn(vm_['url'])
try:
# for idempotency the salt-bootstrap needs -F argument
# script_args: -F
clone_domain = conn.lookupByName(name)
except libvirtError as e:
domain = conn.lookupByName(base)
# TODO: ensure base is shut down before cloning
xml = domain.XMLDesc(0)
kwargs = {
'name': name,
'base_domain': base,
}
__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']
)
log.debug("Source machine XML '%s'", xml)
domain_xml = ElementTree.fromstring(xml)
domain_xml.find('./name').text = name
if domain_xml.find('./description') is None:
description_elem = ElementTree.Element('description')
domain_xml.insert(0, description_elem)
description = domain_xml.find('./description')
description.text = "Cloned from {0}".format(base)
domain_xml.remove(domain_xml.find('./uuid'))
for iface_xml in domain_xml.findall('./devices/interface'):
iface_xml.remove(iface_xml.find('./mac'))
# enable IP learning, this might be a default behaviour...
# Don't always enable since it can cause problems through libvirt-4.5
if ip_source == 'ip-learning' and iface_xml.find("./filterref/parameter[@name='CTRL_IP_LEARNING']") is None:
iface_xml.append(ElementTree.fromstring(IP_LEARNING_XML))
# If a qemu agent is defined we need to fix the path to its socket
# <channel type='unix'>
# <source mode='bind' path='/var/lib/libvirt/qemu/channel/target/domain-<dom-name>/org.qemu.guest_agent.0'/>
# <target type='virtio' name='org.qemu.guest_agent.0'/>
# <address type='virtio-serial' controller='0' bus='0' port='2'/>
# </channel>
for agent_xml in domain_xml.findall("""./devices/channel[@type='unix']"""):
# is org.qemu.guest_agent.0 an option?
if agent_xml.find("""./target[@type='virtio'][@name='org.qemu.guest_agent.0']""") is not None:
source_element = agent_xml.find("""./source[@mode='bind']""")
# see if there is a path element that needs rewriting
if source_element and 'path' in source_element.attrib:
path = source_element.attrib['path']
new_path = path.replace('/domain-{0}/'.format(base), '/domain-{0}/'.format(name))
log.debug("Rewriting agent socket path to %s", new_path)
source_element.attrib['path'] = new_path
for disk in domain_xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
# print "Disk: ", ElementTree.tostring(disk)
# check if we can clone
driver = disk.find("./driver[@name='qemu']")
if driver is None:
# Err on the safe side
raise SaltCloudExecutionFailure("Non qemu driver disk encountered bailing out.")
disk_type = driver.attrib.get('type')
log.info("disk attributes %s", disk.attrib)
if disk_type == 'qcow2':
source = disk.find("./source").attrib['file']
pool, volume = find_pool_and_volume(conn, source)
if clone_strategy == 'quick':
new_volume = pool.createXML(create_volume_with_backing_store_xml(volume), 0)
else:
new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
cleanup.append({'what': 'volume', 'item': new_volume})
disk.find("./source").attrib['file'] = new_volume.path()
elif disk_type == 'raw':
source = disk.find("./source").attrib['file']
pool, volume = find_pool_and_volume(conn, source)
# TODO: more control on the cloned disk type
new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
cleanup.append({'what': 'volume', 'item': new_volume})
disk.find("./source").attrib['file'] = new_volume.path()
else:
raise SaltCloudExecutionFailure("Disk type '{0}' not supported".format(disk_type))
clone_xml = salt.utils.stringutils.to_str(ElementTree.tostring(domain_xml))
log.debug("Clone XML '%s'", clone_xml)
validate_flags = libvirt.VIR_DOMAIN_DEFINE_VALIDATE if validate_xml else 0
clone_domain = conn.defineXMLFlags(clone_xml, validate_flags)
cleanup.append({'what': 'domain', 'item': clone_domain})
clone_domain.createWithFlags(libvirt.VIR_DOMAIN_START_FORCE_BOOT)
log.debug("VM '%s'", vm_)
if ip_source == 'qemu-agent':
ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT
elif ip_source == 'ip-learning':
ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE
address = salt.utils.cloud.wait_for_ip(
get_domain_ip,
update_args=(clone_domain, 0, ip_source),
timeout=config.get_cloud_config_value('wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value('wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value('wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
log.info('Address = %s', address)
vm_['ssh_host'] = address
# the bootstrap script needs to be installed first in /etc/salt/cloud.deploy.d/
# salt-cloud -u is your friend
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
__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
except Exception as e: # pylint: disable=broad-except
do_cleanup(cleanup)
# throw the root cause after cleanup
raise e | Provision a single machine | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/libvirt.py#L278-L471 | [
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def __get_conn(url):\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n try:\n conn = libvirt.open(url)\n except Exception:\n raise SaltCloudExecutionFailure(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'], url\n )\n )\n return conn\n",
"def do_cleanup(cleanup):\n '''\n Clean up clone domain leftovers as much as possible.\n\n Extra robust clean up in order to deal with some small changes in libvirt\n behavior over time. Passed in volumes and domains are deleted, any errors\n are ignored. Used when cloning/provisioning a domain fails.\n\n :param cleanup: list containing dictonaries with two keys: 'what' and 'item'.\n If 'what' is domain the 'item' is a libvirt domain object.\n If 'what' is volume then the item is a libvirt volume object.\n\n Returns:\n none\n\n .. versionadded: 2017.7.3\n '''\n log.info('Cleaning up after exception')\n for leftover in cleanup:\n what = leftover['what']\n item = leftover['item']\n if what == 'domain':\n log.info('Cleaning up %s %s', what, item.name())\n try:\n item.destroy()\n log.debug('%s %s forced off', what, item.name())\n except libvirtError:\n pass\n try:\n item.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+\n libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+\n libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)\n log.debug('%s %s undefined', what, item.name())\n except libvirtError:\n pass\n if what == 'volume':\n try:\n item.delete()\n log.debug('%s %s cleaned up', what, item.name())\n except libvirtError:\n pass\n"
] | # -*- coding: utf-8 -*-
'''
Libvirt Cloud Module
====================
Example provider:
.. code-block:: yaml
# A provider maps to a libvirt instance
my-libvirt-config:
driver: libvirt
# url: "qemu+ssh://user@remotekvm/system?socket=/var/run/libvirt/libvirt-sock"
url: qemu:///system
Example profile:
.. code-block:: yaml
base-itest:
# points back at provider configuration e.g. the libvirt daemon to talk to
provider: my-libvirt-config
base_domain: base-image
# ip_source = [ ip-learning | qemu-agent ]
ip_source: ip-learning
# clone_strategy = [ quick | full ]
clone_strategy: quick
ssh_username: vagrant
# has_ssh_agent: True
password: vagrant
# if /tmp is mounted noexec do workaround
deploy_command: sh /tmp/.saltcloud/deploy.sh
# -F makes the bootstrap script overwrite existing config
# which make reprovisioning a box work
script_args: -F
grains:
sushi: more tasty
# point at the another master at another port
minion:
master: 192.168.16.1
master_port: 5506
Tested on:
- Fedora 26 (libvirt 3.2.1, qemu 2.9.1)
- Fedora 25 (libvirt 1.3.3.2, qemu 2.6.1)
- Fedora 23 (libvirt 1.2.18, qemu 2.4.1)
- Centos 7 (libvirt 1.2.17, qemu 1.5.3)
'''
# TODO: look at event descriptions here:
# https://docs.saltstack.com/en/latest/topics/cloud/reactor.html
# TODO: support reboot? salt-cloud -a reboot vm1 vm2 vm2
# TODO: by using metadata tags in the libvirt XML we could make provider only
# manage domains that we actually created
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import uuid
import os
from xml.etree import ElementTree
# Import 3rd-party libs
from salt.ext import six
try:
import libvirt # pylint: disable=import-error
from libvirt import libvirtError
HAS_LIBVIRT = True
except ImportError:
HAS_LIBVIRT = False
# Import salt libs
import salt.config as config
import salt.utils.cloud
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudExecutionFailure,
SaltCloudNotFound,
SaltCloudSystemExit
)
VIRT_STATE_NAME_MAP = {0: 'running',
1: 'running',
2: 'running',
3: 'paused',
4: 'shutdown',
5: 'shutdown',
6: 'crashed'}
IP_LEARNING_XML = """<filterref filter='clean-traffic'>
<parameter name='CTRL_IP_LEARNING' value='any'/>
</filterref>"""
__virtualname__ = 'libvirt'
# Set up logging
log = logging.getLogger(__name__)
def libvirt_error_handler(ctx, error): # pylint: disable=unused-argument
'''
Redirect stderr prints from libvirt to salt logging.
'''
log.debug("libvirt error %s", error)
if HAS_LIBVIRT:
libvirt.registerErrorHandler(f=libvirt_error_handler, ctx=None)
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_LIBVIRT:
return False, 'Unable to locate or import python libvirt library.'
if get_configured_provider() is False:
return False, 'The \'libvirt\' provider is not configured.'
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('url',)
)
def __get_conn(url):
# This has only been tested on kvm and xen, it needs to be expanded to
# support all vm layers supported by libvirt
try:
conn = libvirt.open(url)
except Exception:
raise SaltCloudExecutionFailure(
'Sorry, {0} failed to open a connection to the hypervisor '
'software at {1}'.format(
__grains__['fqdn'], url
)
)
return conn
def list_nodes(call=None):
'''
Return a list of the VMs
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
providers = __opts__.get('providers', {})
ret = {}
providers_to_check = [_f for _f in [cfg.get('libvirt') for cfg in six.itervalues(providers)] if _f]
for provider in providers_to_check:
conn = __get_conn(provider['url'])
domains = conn.listAllDomains()
for domain in domains:
data = {
'id': domain.UUIDString(),
'image': '',
'size': '',
'state': VIRT_STATE_NAME_MAP[domain.state()[0]],
'private_ips': [],
'public_ips': get_domain_ips(domain, libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE)}
# TODO: Annoyingly name is not guaranteed to be unique, but the id will not work in other places
ret[domain.name()] = data
return ret
def list_nodes_full(call=None):
'''
Because this module is not specific to any cloud providers, there will be
no nodes to list.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
return list_nodes(call)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called '
'with -f or --function.'
)
selection = __opts__.get('query.selection')
if not selection:
raise SaltCloudSystemExit(
'query.selection not found in /etc/salt/cloud'
)
# TODO: somewhat doubt the implementation of cloud.list_nodes_select
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), selection, call,
)
def to_ip_addr_type(addr_type):
if addr_type == libvirt.VIR_IP_ADDR_TYPE_IPV4:
return "ipv4"
elif addr_type == libvirt.VIR_IP_ADDR_TYPE_IPV6:
return "ipv6"
def get_domain_ips(domain, ip_source):
ips = []
state = domain.state(0)
if state[0] != libvirt.VIR_DOMAIN_RUNNING:
return ips
try:
addresses = domain.interfaceAddresses(ip_source, 0)
except libvirt.libvirtError as error:
log.info("Exception polling address %s", error)
return ips
for (name, val) in six.iteritems(addresses):
if val['addrs']:
for addr in val['addrs']:
tp = to_ip_addr_type(addr['type'])
log.info("Found address %s", addr)
if tp == "ipv4":
ips.append(addr['addr'])
return ips
def get_domain_ip(domain, idx, ip_source, skip_loopback=True):
ips = get_domain_ips(domain, ip_source)
if skip_loopback:
ips = [ip for ip in ips if not ip.startswith('127.')]
if not ips or len(ips) <= idx:
return None
return ips[idx]
def do_cleanup(cleanup):
'''
Clean up clone domain leftovers as much as possible.
Extra robust clean up in order to deal with some small changes in libvirt
behavior over time. Passed in volumes and domains are deleted, any errors
are ignored. Used when cloning/provisioning a domain fails.
:param cleanup: list containing dictonaries with two keys: 'what' and 'item'.
If 'what' is domain the 'item' is a libvirt domain object.
If 'what' is volume then the item is a libvirt volume object.
Returns:
none
.. versionadded: 2017.7.3
'''
log.info('Cleaning up after exception')
for leftover in cleanup:
what = leftover['what']
item = leftover['item']
if what == 'domain':
log.info('Cleaning up %s %s', what, item.name())
try:
item.destroy()
log.debug('%s %s forced off', what, item.name())
except libvirtError:
pass
try:
item.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+
libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+
libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)
log.debug('%s %s undefined', what, item.name())
except libvirtError:
pass
if what == 'volume':
try:
item.delete()
log.debug('%s %s cleaned up', what, item.name())
except libvirtError:
pass
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
"""
log.info("Attempting to delete instance %s", name)
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
found = []
providers = __opts__.get('providers', {})
providers_to_check = [_f for _f in [cfg.get('libvirt') for cfg in six.itervalues(providers)] if _f]
for provider in providers_to_check:
conn = __get_conn(provider['url'])
log.info("looking at %s", provider['url'])
try:
domain = conn.lookupByName(name)
found.append({'domain': domain, 'conn': conn})
except libvirtError:
pass
if not found:
return "{0} doesn't exist and can't be deleted".format(name)
if len(found) > 1:
return "{0} doesn't identify a unique machine leaving things".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
destroy_domain(found[0]['conn'], found[0]['domain'])
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def destroy_domain(conn, domain):
log.info('Destroying domain %s', domain.name())
try:
domain.destroy()
except libvirtError:
pass
volumes = get_domain_volumes(conn, domain)
for volume in volumes:
log.debug('Removing volume %s', volume.name())
volume.delete()
log.debug('Undefining domain %s', domain.name())
domain.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+
libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+
libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)
def create_volume_xml(volume):
template = """<volume>
<name>n</name>
<capacity>c</capacity>
<allocation>0</allocation>
<target>
<path>p</path>
<format type='qcow2'/>
<compat>1.1</compat>
</target>
</volume>
"""
volume_xml = ElementTree.fromstring(template)
# TODO: generate name
volume_xml.find('name').text = generate_new_name(volume.name())
log.debug("Volume: %s", dir(volume))
volume_xml.find('capacity').text = six.text_type(volume.info()[1])
volume_xml.find('./target/path').text = volume.path()
xml_string = salt.utils.stringutils.to_str(ElementTree.tostring(volume_xml))
log.debug("Creating %s", xml_string)
return xml_string
def create_volume_with_backing_store_xml(volume):
template = """<volume>
<name>n</name>
<capacity>c</capacity>
<allocation>0</allocation>
<target>
<format type='qcow2'/>
<compat>1.1</compat>
</target>
<backingStore>
<format type='qcow2'/>
<path>p</path>
</backingStore>
</volume>
"""
volume_xml = ElementTree.fromstring(template)
# TODO: generate name
volume_xml.find('name').text = generate_new_name(volume.name())
log.debug("volume: %s", dir(volume))
volume_xml.find('capacity').text = six.text_type(volume.info()[1])
volume_xml.find('./backingStore/path').text = volume.path()
xml_string = salt.utils.stringutils.to_str(ElementTree.tostring(volume_xml))
log.debug("Creating %s", xml_string)
return xml_string
def find_pool_and_volume(conn, path):
# active and persistent storage pools
# TODO: should we filter on type?
for sp in conn.listAllStoragePools(2+4):
for v in sp.listAllVolumes():
if v.path() == path:
return sp, v
raise SaltCloudNotFound('Could not find volume for path {0}'.format(path))
def generate_new_name(orig_name):
if '.' not in orig_name:
return '{0}-{1}'.format(orig_name, uuid.uuid1())
name, ext = orig_name.rsplit('.', 1)
return '{0}-{1}.{2}'.format(name, uuid.uuid1(), ext)
def get_domain_volumes(conn, domain):
volumes = []
xml = ElementTree.fromstring(domain.XMLDesc(0))
for disk in xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
if disk.find("./driver[@name='qemu'][@type='qcow2']") is not None:
source = disk.find("./source").attrib['file']
try:
pool, volume = find_pool_and_volume(conn, source)
volumes.append(volume)
except libvirtError:
log.warning("Disk not found '%s'", source)
return volumes
|
saltstack/salt | salt/cloud/clouds/libvirt.py | do_cleanup | python | def do_cleanup(cleanup):
'''
Clean up clone domain leftovers as much as possible.
Extra robust clean up in order to deal with some small changes in libvirt
behavior over time. Passed in volumes and domains are deleted, any errors
are ignored. Used when cloning/provisioning a domain fails.
:param cleanup: list containing dictonaries with two keys: 'what' and 'item'.
If 'what' is domain the 'item' is a libvirt domain object.
If 'what' is volume then the item is a libvirt volume object.
Returns:
none
.. versionadded: 2017.7.3
'''
log.info('Cleaning up after exception')
for leftover in cleanup:
what = leftover['what']
item = leftover['item']
if what == 'domain':
log.info('Cleaning up %s %s', what, item.name())
try:
item.destroy()
log.debug('%s %s forced off', what, item.name())
except libvirtError:
pass
try:
item.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+
libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+
libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)
log.debug('%s %s undefined', what, item.name())
except libvirtError:
pass
if what == 'volume':
try:
item.delete()
log.debug('%s %s cleaned up', what, item.name())
except libvirtError:
pass | Clean up clone domain leftovers as much as possible.
Extra robust clean up in order to deal with some small changes in libvirt
behavior over time. Passed in volumes and domains are deleted, any errors
are ignored. Used when cloning/provisioning a domain fails.
:param cleanup: list containing dictonaries with two keys: 'what' and 'item'.
If 'what' is domain the 'item' is a libvirt domain object.
If 'what' is volume then the item is a libvirt volume object.
Returns:
none
.. versionadded: 2017.7.3 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/libvirt.py#L474-L514 | null | # -*- coding: utf-8 -*-
'''
Libvirt Cloud Module
====================
Example provider:
.. code-block:: yaml
# A provider maps to a libvirt instance
my-libvirt-config:
driver: libvirt
# url: "qemu+ssh://user@remotekvm/system?socket=/var/run/libvirt/libvirt-sock"
url: qemu:///system
Example profile:
.. code-block:: yaml
base-itest:
# points back at provider configuration e.g. the libvirt daemon to talk to
provider: my-libvirt-config
base_domain: base-image
# ip_source = [ ip-learning | qemu-agent ]
ip_source: ip-learning
# clone_strategy = [ quick | full ]
clone_strategy: quick
ssh_username: vagrant
# has_ssh_agent: True
password: vagrant
# if /tmp is mounted noexec do workaround
deploy_command: sh /tmp/.saltcloud/deploy.sh
# -F makes the bootstrap script overwrite existing config
# which make reprovisioning a box work
script_args: -F
grains:
sushi: more tasty
# point at the another master at another port
minion:
master: 192.168.16.1
master_port: 5506
Tested on:
- Fedora 26 (libvirt 3.2.1, qemu 2.9.1)
- Fedora 25 (libvirt 1.3.3.2, qemu 2.6.1)
- Fedora 23 (libvirt 1.2.18, qemu 2.4.1)
- Centos 7 (libvirt 1.2.17, qemu 1.5.3)
'''
# TODO: look at event descriptions here:
# https://docs.saltstack.com/en/latest/topics/cloud/reactor.html
# TODO: support reboot? salt-cloud -a reboot vm1 vm2 vm2
# TODO: by using metadata tags in the libvirt XML we could make provider only
# manage domains that we actually created
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import uuid
import os
from xml.etree import ElementTree
# Import 3rd-party libs
from salt.ext import six
try:
import libvirt # pylint: disable=import-error
from libvirt import libvirtError
HAS_LIBVIRT = True
except ImportError:
HAS_LIBVIRT = False
# Import salt libs
import salt.config as config
import salt.utils.cloud
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudExecutionFailure,
SaltCloudNotFound,
SaltCloudSystemExit
)
VIRT_STATE_NAME_MAP = {0: 'running',
1: 'running',
2: 'running',
3: 'paused',
4: 'shutdown',
5: 'shutdown',
6: 'crashed'}
IP_LEARNING_XML = """<filterref filter='clean-traffic'>
<parameter name='CTRL_IP_LEARNING' value='any'/>
</filterref>"""
__virtualname__ = 'libvirt'
# Set up logging
log = logging.getLogger(__name__)
def libvirt_error_handler(ctx, error): # pylint: disable=unused-argument
'''
Redirect stderr prints from libvirt to salt logging.
'''
log.debug("libvirt error %s", error)
if HAS_LIBVIRT:
libvirt.registerErrorHandler(f=libvirt_error_handler, ctx=None)
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_LIBVIRT:
return False, 'Unable to locate or import python libvirt library.'
if get_configured_provider() is False:
return False, 'The \'libvirt\' provider is not configured.'
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('url',)
)
def __get_conn(url):
# This has only been tested on kvm and xen, it needs to be expanded to
# support all vm layers supported by libvirt
try:
conn = libvirt.open(url)
except Exception:
raise SaltCloudExecutionFailure(
'Sorry, {0} failed to open a connection to the hypervisor '
'software at {1}'.format(
__grains__['fqdn'], url
)
)
return conn
def list_nodes(call=None):
'''
Return a list of the VMs
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
providers = __opts__.get('providers', {})
ret = {}
providers_to_check = [_f for _f in [cfg.get('libvirt') for cfg in six.itervalues(providers)] if _f]
for provider in providers_to_check:
conn = __get_conn(provider['url'])
domains = conn.listAllDomains()
for domain in domains:
data = {
'id': domain.UUIDString(),
'image': '',
'size': '',
'state': VIRT_STATE_NAME_MAP[domain.state()[0]],
'private_ips': [],
'public_ips': get_domain_ips(domain, libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE)}
# TODO: Annoyingly name is not guaranteed to be unique, but the id will not work in other places
ret[domain.name()] = data
return ret
def list_nodes_full(call=None):
'''
Because this module is not specific to any cloud providers, there will be
no nodes to list.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
return list_nodes(call)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called '
'with -f or --function.'
)
selection = __opts__.get('query.selection')
if not selection:
raise SaltCloudSystemExit(
'query.selection not found in /etc/salt/cloud'
)
# TODO: somewhat doubt the implementation of cloud.list_nodes_select
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), selection, call,
)
def to_ip_addr_type(addr_type):
if addr_type == libvirt.VIR_IP_ADDR_TYPE_IPV4:
return "ipv4"
elif addr_type == libvirt.VIR_IP_ADDR_TYPE_IPV6:
return "ipv6"
def get_domain_ips(domain, ip_source):
ips = []
state = domain.state(0)
if state[0] != libvirt.VIR_DOMAIN_RUNNING:
return ips
try:
addresses = domain.interfaceAddresses(ip_source, 0)
except libvirt.libvirtError as error:
log.info("Exception polling address %s", error)
return ips
for (name, val) in six.iteritems(addresses):
if val['addrs']:
for addr in val['addrs']:
tp = to_ip_addr_type(addr['type'])
log.info("Found address %s", addr)
if tp == "ipv4":
ips.append(addr['addr'])
return ips
def get_domain_ip(domain, idx, ip_source, skip_loopback=True):
ips = get_domain_ips(domain, ip_source)
if skip_loopback:
ips = [ip for ip in ips if not ip.startswith('127.')]
if not ips or len(ips) <= idx:
return None
return ips[idx]
def create(vm_):
'''
Provision a single machine
'''
clone_strategy = vm_.get('clone_strategy') or 'full'
if clone_strategy not in ('quick', 'full'):
raise SaltCloudSystemExit("'clone_strategy' must be one of quick or full. Got '{0}'".format(clone_strategy))
ip_source = vm_.get('ip_source') or 'ip-learning'
if ip_source not in ('ip-learning', 'qemu-agent'):
raise SaltCloudSystemExit("'ip_source' must be one of qemu-agent or ip-learning. Got '{0}'".format(ip_source))
validate_xml = vm_.get('validate_xml') if vm_.get('validate_xml') is not None else True
log.info("Cloning '%s' with strategy '%s' validate_xml='%s'", vm_['name'], clone_strategy, validate_xml)
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'libvirt',
vm_['profile']) is False:
return False
except AttributeError:
pass
# TODO: check name qemu/libvirt will choke on some characters (like '/')?
name = vm_['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']
)
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
# wait_for_instance requires private_key
vm_['private_key'] = key_filename
cleanup = []
try:
# clone the vm
base = vm_['base_domain']
conn = __get_conn(vm_['url'])
try:
# for idempotency the salt-bootstrap needs -F argument
# script_args: -F
clone_domain = conn.lookupByName(name)
except libvirtError as e:
domain = conn.lookupByName(base)
# TODO: ensure base is shut down before cloning
xml = domain.XMLDesc(0)
kwargs = {
'name': name,
'base_domain': base,
}
__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']
)
log.debug("Source machine XML '%s'", xml)
domain_xml = ElementTree.fromstring(xml)
domain_xml.find('./name').text = name
if domain_xml.find('./description') is None:
description_elem = ElementTree.Element('description')
domain_xml.insert(0, description_elem)
description = domain_xml.find('./description')
description.text = "Cloned from {0}".format(base)
domain_xml.remove(domain_xml.find('./uuid'))
for iface_xml in domain_xml.findall('./devices/interface'):
iface_xml.remove(iface_xml.find('./mac'))
# enable IP learning, this might be a default behaviour...
# Don't always enable since it can cause problems through libvirt-4.5
if ip_source == 'ip-learning' and iface_xml.find("./filterref/parameter[@name='CTRL_IP_LEARNING']") is None:
iface_xml.append(ElementTree.fromstring(IP_LEARNING_XML))
# If a qemu agent is defined we need to fix the path to its socket
# <channel type='unix'>
# <source mode='bind' path='/var/lib/libvirt/qemu/channel/target/domain-<dom-name>/org.qemu.guest_agent.0'/>
# <target type='virtio' name='org.qemu.guest_agent.0'/>
# <address type='virtio-serial' controller='0' bus='0' port='2'/>
# </channel>
for agent_xml in domain_xml.findall("""./devices/channel[@type='unix']"""):
# is org.qemu.guest_agent.0 an option?
if agent_xml.find("""./target[@type='virtio'][@name='org.qemu.guest_agent.0']""") is not None:
source_element = agent_xml.find("""./source[@mode='bind']""")
# see if there is a path element that needs rewriting
if source_element and 'path' in source_element.attrib:
path = source_element.attrib['path']
new_path = path.replace('/domain-{0}/'.format(base), '/domain-{0}/'.format(name))
log.debug("Rewriting agent socket path to %s", new_path)
source_element.attrib['path'] = new_path
for disk in domain_xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
# print "Disk: ", ElementTree.tostring(disk)
# check if we can clone
driver = disk.find("./driver[@name='qemu']")
if driver is None:
# Err on the safe side
raise SaltCloudExecutionFailure("Non qemu driver disk encountered bailing out.")
disk_type = driver.attrib.get('type')
log.info("disk attributes %s", disk.attrib)
if disk_type == 'qcow2':
source = disk.find("./source").attrib['file']
pool, volume = find_pool_and_volume(conn, source)
if clone_strategy == 'quick':
new_volume = pool.createXML(create_volume_with_backing_store_xml(volume), 0)
else:
new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
cleanup.append({'what': 'volume', 'item': new_volume})
disk.find("./source").attrib['file'] = new_volume.path()
elif disk_type == 'raw':
source = disk.find("./source").attrib['file']
pool, volume = find_pool_and_volume(conn, source)
# TODO: more control on the cloned disk type
new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
cleanup.append({'what': 'volume', 'item': new_volume})
disk.find("./source").attrib['file'] = new_volume.path()
else:
raise SaltCloudExecutionFailure("Disk type '{0}' not supported".format(disk_type))
clone_xml = salt.utils.stringutils.to_str(ElementTree.tostring(domain_xml))
log.debug("Clone XML '%s'", clone_xml)
validate_flags = libvirt.VIR_DOMAIN_DEFINE_VALIDATE if validate_xml else 0
clone_domain = conn.defineXMLFlags(clone_xml, validate_flags)
cleanup.append({'what': 'domain', 'item': clone_domain})
clone_domain.createWithFlags(libvirt.VIR_DOMAIN_START_FORCE_BOOT)
log.debug("VM '%s'", vm_)
if ip_source == 'qemu-agent':
ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT
elif ip_source == 'ip-learning':
ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE
address = salt.utils.cloud.wait_for_ip(
get_domain_ip,
update_args=(clone_domain, 0, ip_source),
timeout=config.get_cloud_config_value('wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value('wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value('wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
log.info('Address = %s', address)
vm_['ssh_host'] = address
# the bootstrap script needs to be installed first in /etc/salt/cloud.deploy.d/
# salt-cloud -u is your friend
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
__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
except Exception as e: # pylint: disable=broad-except
do_cleanup(cleanup)
# throw the root cause after cleanup
raise e
def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str
"""
log.info("Attempting to delete instance %s", name)
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
found = []
providers = __opts__.get('providers', {})
providers_to_check = [_f for _f in [cfg.get('libvirt') for cfg in six.itervalues(providers)] if _f]
for provider in providers_to_check:
conn = __get_conn(provider['url'])
log.info("looking at %s", provider['url'])
try:
domain = conn.lookupByName(name)
found.append({'domain': domain, 'conn': conn})
except libvirtError:
pass
if not found:
return "{0} doesn't exist and can't be deleted".format(name)
if len(found) > 1:
return "{0} doesn't identify a unique machine leaving things".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
destroy_domain(found[0]['conn'], found[0]['domain'])
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def destroy_domain(conn, domain):
log.info('Destroying domain %s', domain.name())
try:
domain.destroy()
except libvirtError:
pass
volumes = get_domain_volumes(conn, domain)
for volume in volumes:
log.debug('Removing volume %s', volume.name())
volume.delete()
log.debug('Undefining domain %s', domain.name())
domain.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+
libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+
libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)
def create_volume_xml(volume):
template = """<volume>
<name>n</name>
<capacity>c</capacity>
<allocation>0</allocation>
<target>
<path>p</path>
<format type='qcow2'/>
<compat>1.1</compat>
</target>
</volume>
"""
volume_xml = ElementTree.fromstring(template)
# TODO: generate name
volume_xml.find('name').text = generate_new_name(volume.name())
log.debug("Volume: %s", dir(volume))
volume_xml.find('capacity').text = six.text_type(volume.info()[1])
volume_xml.find('./target/path').text = volume.path()
xml_string = salt.utils.stringutils.to_str(ElementTree.tostring(volume_xml))
log.debug("Creating %s", xml_string)
return xml_string
def create_volume_with_backing_store_xml(volume):
template = """<volume>
<name>n</name>
<capacity>c</capacity>
<allocation>0</allocation>
<target>
<format type='qcow2'/>
<compat>1.1</compat>
</target>
<backingStore>
<format type='qcow2'/>
<path>p</path>
</backingStore>
</volume>
"""
volume_xml = ElementTree.fromstring(template)
# TODO: generate name
volume_xml.find('name').text = generate_new_name(volume.name())
log.debug("volume: %s", dir(volume))
volume_xml.find('capacity').text = six.text_type(volume.info()[1])
volume_xml.find('./backingStore/path').text = volume.path()
xml_string = salt.utils.stringutils.to_str(ElementTree.tostring(volume_xml))
log.debug("Creating %s", xml_string)
return xml_string
def find_pool_and_volume(conn, path):
# active and persistent storage pools
# TODO: should we filter on type?
for sp in conn.listAllStoragePools(2+4):
for v in sp.listAllVolumes():
if v.path() == path:
return sp, v
raise SaltCloudNotFound('Could not find volume for path {0}'.format(path))
def generate_new_name(orig_name):
if '.' not in orig_name:
return '{0}-{1}'.format(orig_name, uuid.uuid1())
name, ext = orig_name.rsplit('.', 1)
return '{0}-{1}.{2}'.format(name, uuid.uuid1(), ext)
def get_domain_volumes(conn, domain):
volumes = []
xml = ElementTree.fromstring(domain.XMLDesc(0))
for disk in xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
if disk.find("./driver[@name='qemu'][@type='qcow2']") is not None:
source = disk.find("./source").attrib['file']
try:
pool, volume = find_pool_and_volume(conn, source)
volumes.append(volume)
except libvirtError:
log.warning("Disk not found '%s'", source)
return volumes
|
saltstack/salt | salt/cloud/clouds/libvirt.py | destroy | python | def destroy(name, call=None):
log.info("Attempting to delete instance %s", name)
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
found = []
providers = __opts__.get('providers', {})
providers_to_check = [_f for _f in [cfg.get('libvirt') for cfg in six.itervalues(providers)] if _f]
for provider in providers_to_check:
conn = __get_conn(provider['url'])
log.info("looking at %s", provider['url'])
try:
domain = conn.lookupByName(name)
found.append({'domain': domain, 'conn': conn})
except libvirtError:
pass
if not found:
return "{0} doesn't exist and can't be deleted".format(name)
if len(found) > 1:
return "{0} doesn't identify a unique machine leaving things".format(name)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
destroy_domain(found[0]['conn'], found[0]['domain'])
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
) | This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is fired.
The tag for that event is `salt/cloud/<vm name>/destroyed`.
Dependencies:
list_nodes
@param name:
@type name: str
@param call:
@type call:
@return: True if all went well, otherwise an error message
@rtype: bool|str | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/libvirt.py#L517-L581 | [
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n",
"def __get_conn(url):\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n try:\n conn = libvirt.open(url)\n except Exception:\n raise SaltCloudExecutionFailure(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'], url\n )\n )\n return conn\n",
"def destroy_domain(conn, domain):\n log.info('Destroying domain %s', domain.name())\n try:\n domain.destroy()\n except libvirtError:\n pass\n volumes = get_domain_volumes(conn, domain)\n for volume in volumes:\n log.debug('Removing volume %s', volume.name())\n volume.delete()\n\n log.debug('Undefining domain %s', domain.name())\n domain.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+\n libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+\n libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)\n"
] | # -*- coding: utf-8 -*-
'''
Libvirt Cloud Module
====================
Example provider:
.. code-block:: yaml
# A provider maps to a libvirt instance
my-libvirt-config:
driver: libvirt
# url: "qemu+ssh://user@remotekvm/system?socket=/var/run/libvirt/libvirt-sock"
url: qemu:///system
Example profile:
.. code-block:: yaml
base-itest:
# points back at provider configuration e.g. the libvirt daemon to talk to
provider: my-libvirt-config
base_domain: base-image
# ip_source = [ ip-learning | qemu-agent ]
ip_source: ip-learning
# clone_strategy = [ quick | full ]
clone_strategy: quick
ssh_username: vagrant
# has_ssh_agent: True
password: vagrant
# if /tmp is mounted noexec do workaround
deploy_command: sh /tmp/.saltcloud/deploy.sh
# -F makes the bootstrap script overwrite existing config
# which make reprovisioning a box work
script_args: -F
grains:
sushi: more tasty
# point at the another master at another port
minion:
master: 192.168.16.1
master_port: 5506
Tested on:
- Fedora 26 (libvirt 3.2.1, qemu 2.9.1)
- Fedora 25 (libvirt 1.3.3.2, qemu 2.6.1)
- Fedora 23 (libvirt 1.2.18, qemu 2.4.1)
- Centos 7 (libvirt 1.2.17, qemu 1.5.3)
'''
# TODO: look at event descriptions here:
# https://docs.saltstack.com/en/latest/topics/cloud/reactor.html
# TODO: support reboot? salt-cloud -a reboot vm1 vm2 vm2
# TODO: by using metadata tags in the libvirt XML we could make provider only
# manage domains that we actually created
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import uuid
import os
from xml.etree import ElementTree
# Import 3rd-party libs
from salt.ext import six
try:
import libvirt # pylint: disable=import-error
from libvirt import libvirtError
HAS_LIBVIRT = True
except ImportError:
HAS_LIBVIRT = False
# Import salt libs
import salt.config as config
import salt.utils.cloud
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudExecutionFailure,
SaltCloudNotFound,
SaltCloudSystemExit
)
VIRT_STATE_NAME_MAP = {0: 'running',
1: 'running',
2: 'running',
3: 'paused',
4: 'shutdown',
5: 'shutdown',
6: 'crashed'}
IP_LEARNING_XML = """<filterref filter='clean-traffic'>
<parameter name='CTRL_IP_LEARNING' value='any'/>
</filterref>"""
__virtualname__ = 'libvirt'
# Set up logging
log = logging.getLogger(__name__)
def libvirt_error_handler(ctx, error): # pylint: disable=unused-argument
'''
Redirect stderr prints from libvirt to salt logging.
'''
log.debug("libvirt error %s", error)
if HAS_LIBVIRT:
libvirt.registerErrorHandler(f=libvirt_error_handler, ctx=None)
def __virtual__():
'''
This function determines whether or not
to make this cloud module available upon execution.
Most often, it uses get_configured_provider() to determine
if the necessary configuration has been set up.
It may also check for necessary imports decide whether to load the module.
In most cases, it will return a True or False value.
If the name of the driver used does not match the filename,
then that name should be returned instead of True.
@return True|False|str
'''
if not HAS_LIBVIRT:
return False, 'Unable to locate or import python libvirt library.'
if get_configured_provider() is False:
return False, 'The \'libvirt\' provider is not configured.'
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('url',)
)
def __get_conn(url):
# This has only been tested on kvm and xen, it needs to be expanded to
# support all vm layers supported by libvirt
try:
conn = libvirt.open(url)
except Exception:
raise SaltCloudExecutionFailure(
'Sorry, {0} failed to open a connection to the hypervisor '
'software at {1}'.format(
__grains__['fqdn'], url
)
)
return conn
def list_nodes(call=None):
'''
Return a list of the VMs
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called '
'with -f or --function.'
)
providers = __opts__.get('providers', {})
ret = {}
providers_to_check = [_f for _f in [cfg.get('libvirt') for cfg in six.itervalues(providers)] if _f]
for provider in providers_to_check:
conn = __get_conn(provider['url'])
domains = conn.listAllDomains()
for domain in domains:
data = {
'id': domain.UUIDString(),
'image': '',
'size': '',
'state': VIRT_STATE_NAME_MAP[domain.state()[0]],
'private_ips': [],
'public_ips': get_domain_ips(domain, libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE)}
# TODO: Annoyingly name is not guaranteed to be unique, but the id will not work in other places
ret[domain.name()] = data
return ret
def list_nodes_full(call=None):
'''
Because this module is not specific to any cloud providers, there will be
no nodes to list.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called '
'with -f or --function.'
)
return list_nodes(call)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called '
'with -f or --function.'
)
selection = __opts__.get('query.selection')
if not selection:
raise SaltCloudSystemExit(
'query.selection not found in /etc/salt/cloud'
)
# TODO: somewhat doubt the implementation of cloud.list_nodes_select
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), selection, call,
)
def to_ip_addr_type(addr_type):
if addr_type == libvirt.VIR_IP_ADDR_TYPE_IPV4:
return "ipv4"
elif addr_type == libvirt.VIR_IP_ADDR_TYPE_IPV6:
return "ipv6"
def get_domain_ips(domain, ip_source):
ips = []
state = domain.state(0)
if state[0] != libvirt.VIR_DOMAIN_RUNNING:
return ips
try:
addresses = domain.interfaceAddresses(ip_source, 0)
except libvirt.libvirtError as error:
log.info("Exception polling address %s", error)
return ips
for (name, val) in six.iteritems(addresses):
if val['addrs']:
for addr in val['addrs']:
tp = to_ip_addr_type(addr['type'])
log.info("Found address %s", addr)
if tp == "ipv4":
ips.append(addr['addr'])
return ips
def get_domain_ip(domain, idx, ip_source, skip_loopback=True):
ips = get_domain_ips(domain, ip_source)
if skip_loopback:
ips = [ip for ip in ips if not ip.startswith('127.')]
if not ips or len(ips) <= idx:
return None
return ips[idx]
def create(vm_):
'''
Provision a single machine
'''
clone_strategy = vm_.get('clone_strategy') or 'full'
if clone_strategy not in ('quick', 'full'):
raise SaltCloudSystemExit("'clone_strategy' must be one of quick or full. Got '{0}'".format(clone_strategy))
ip_source = vm_.get('ip_source') or 'ip-learning'
if ip_source not in ('ip-learning', 'qemu-agent'):
raise SaltCloudSystemExit("'ip_source' must be one of qemu-agent or ip-learning. Got '{0}'".format(ip_source))
validate_xml = vm_.get('validate_xml') if vm_.get('validate_xml') is not None else True
log.info("Cloning '%s' with strategy '%s' validate_xml='%s'", vm_['name'], clone_strategy, validate_xml)
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'libvirt',
vm_['profile']) is False:
return False
except AttributeError:
pass
# TODO: check name qemu/libvirt will choke on some characters (like '/')?
name = vm_['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']
)
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
# wait_for_instance requires private_key
vm_['private_key'] = key_filename
cleanup = []
try:
# clone the vm
base = vm_['base_domain']
conn = __get_conn(vm_['url'])
try:
# for idempotency the salt-bootstrap needs -F argument
# script_args: -F
clone_domain = conn.lookupByName(name)
except libvirtError as e:
domain = conn.lookupByName(base)
# TODO: ensure base is shut down before cloning
xml = domain.XMLDesc(0)
kwargs = {
'name': name,
'base_domain': base,
}
__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']
)
log.debug("Source machine XML '%s'", xml)
domain_xml = ElementTree.fromstring(xml)
domain_xml.find('./name').text = name
if domain_xml.find('./description') is None:
description_elem = ElementTree.Element('description')
domain_xml.insert(0, description_elem)
description = domain_xml.find('./description')
description.text = "Cloned from {0}".format(base)
domain_xml.remove(domain_xml.find('./uuid'))
for iface_xml in domain_xml.findall('./devices/interface'):
iface_xml.remove(iface_xml.find('./mac'))
# enable IP learning, this might be a default behaviour...
# Don't always enable since it can cause problems through libvirt-4.5
if ip_source == 'ip-learning' and iface_xml.find("./filterref/parameter[@name='CTRL_IP_LEARNING']") is None:
iface_xml.append(ElementTree.fromstring(IP_LEARNING_XML))
# If a qemu agent is defined we need to fix the path to its socket
# <channel type='unix'>
# <source mode='bind' path='/var/lib/libvirt/qemu/channel/target/domain-<dom-name>/org.qemu.guest_agent.0'/>
# <target type='virtio' name='org.qemu.guest_agent.0'/>
# <address type='virtio-serial' controller='0' bus='0' port='2'/>
# </channel>
for agent_xml in domain_xml.findall("""./devices/channel[@type='unix']"""):
# is org.qemu.guest_agent.0 an option?
if agent_xml.find("""./target[@type='virtio'][@name='org.qemu.guest_agent.0']""") is not None:
source_element = agent_xml.find("""./source[@mode='bind']""")
# see if there is a path element that needs rewriting
if source_element and 'path' in source_element.attrib:
path = source_element.attrib['path']
new_path = path.replace('/domain-{0}/'.format(base), '/domain-{0}/'.format(name))
log.debug("Rewriting agent socket path to %s", new_path)
source_element.attrib['path'] = new_path
for disk in domain_xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
# print "Disk: ", ElementTree.tostring(disk)
# check if we can clone
driver = disk.find("./driver[@name='qemu']")
if driver is None:
# Err on the safe side
raise SaltCloudExecutionFailure("Non qemu driver disk encountered bailing out.")
disk_type = driver.attrib.get('type')
log.info("disk attributes %s", disk.attrib)
if disk_type == 'qcow2':
source = disk.find("./source").attrib['file']
pool, volume = find_pool_and_volume(conn, source)
if clone_strategy == 'quick':
new_volume = pool.createXML(create_volume_with_backing_store_xml(volume), 0)
else:
new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
cleanup.append({'what': 'volume', 'item': new_volume})
disk.find("./source").attrib['file'] = new_volume.path()
elif disk_type == 'raw':
source = disk.find("./source").attrib['file']
pool, volume = find_pool_and_volume(conn, source)
# TODO: more control on the cloned disk type
new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
cleanup.append({'what': 'volume', 'item': new_volume})
disk.find("./source").attrib['file'] = new_volume.path()
else:
raise SaltCloudExecutionFailure("Disk type '{0}' not supported".format(disk_type))
clone_xml = salt.utils.stringutils.to_str(ElementTree.tostring(domain_xml))
log.debug("Clone XML '%s'", clone_xml)
validate_flags = libvirt.VIR_DOMAIN_DEFINE_VALIDATE if validate_xml else 0
clone_domain = conn.defineXMLFlags(clone_xml, validate_flags)
cleanup.append({'what': 'domain', 'item': clone_domain})
clone_domain.createWithFlags(libvirt.VIR_DOMAIN_START_FORCE_BOOT)
log.debug("VM '%s'", vm_)
if ip_source == 'qemu-agent':
ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT
elif ip_source == 'ip-learning':
ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE
address = salt.utils.cloud.wait_for_ip(
get_domain_ip,
update_args=(clone_domain, 0, ip_source),
timeout=config.get_cloud_config_value('wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value('wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value('wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
log.info('Address = %s', address)
vm_['ssh_host'] = address
# the bootstrap script needs to be installed first in /etc/salt/cloud.deploy.d/
# salt-cloud -u is your friend
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
__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
except Exception as e: # pylint: disable=broad-except
do_cleanup(cleanup)
# throw the root cause after cleanup
raise e
def do_cleanup(cleanup):
'''
Clean up clone domain leftovers as much as possible.
Extra robust clean up in order to deal with some small changes in libvirt
behavior over time. Passed in volumes and domains are deleted, any errors
are ignored. Used when cloning/provisioning a domain fails.
:param cleanup: list containing dictonaries with two keys: 'what' and 'item'.
If 'what' is domain the 'item' is a libvirt domain object.
If 'what' is volume then the item is a libvirt volume object.
Returns:
none
.. versionadded: 2017.7.3
'''
log.info('Cleaning up after exception')
for leftover in cleanup:
what = leftover['what']
item = leftover['item']
if what == 'domain':
log.info('Cleaning up %s %s', what, item.name())
try:
item.destroy()
log.debug('%s %s forced off', what, item.name())
except libvirtError:
pass
try:
item.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+
libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+
libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)
log.debug('%s %s undefined', what, item.name())
except libvirtError:
pass
if what == 'volume':
try:
item.delete()
log.debug('%s %s cleaned up', what, item.name())
except libvirtError:
pass
def destroy_domain(conn, domain):
log.info('Destroying domain %s', domain.name())
try:
domain.destroy()
except libvirtError:
pass
volumes = get_domain_volumes(conn, domain)
for volume in volumes:
log.debug('Removing volume %s', volume.name())
volume.delete()
log.debug('Undefining domain %s', domain.name())
domain.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE+
libvirt.VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA+
libvirt.VIR_DOMAIN_UNDEFINE_NVRAM)
def create_volume_xml(volume):
template = """<volume>
<name>n</name>
<capacity>c</capacity>
<allocation>0</allocation>
<target>
<path>p</path>
<format type='qcow2'/>
<compat>1.1</compat>
</target>
</volume>
"""
volume_xml = ElementTree.fromstring(template)
# TODO: generate name
volume_xml.find('name').text = generate_new_name(volume.name())
log.debug("Volume: %s", dir(volume))
volume_xml.find('capacity').text = six.text_type(volume.info()[1])
volume_xml.find('./target/path').text = volume.path()
xml_string = salt.utils.stringutils.to_str(ElementTree.tostring(volume_xml))
log.debug("Creating %s", xml_string)
return xml_string
def create_volume_with_backing_store_xml(volume):
template = """<volume>
<name>n</name>
<capacity>c</capacity>
<allocation>0</allocation>
<target>
<format type='qcow2'/>
<compat>1.1</compat>
</target>
<backingStore>
<format type='qcow2'/>
<path>p</path>
</backingStore>
</volume>
"""
volume_xml = ElementTree.fromstring(template)
# TODO: generate name
volume_xml.find('name').text = generate_new_name(volume.name())
log.debug("volume: %s", dir(volume))
volume_xml.find('capacity').text = six.text_type(volume.info()[1])
volume_xml.find('./backingStore/path').text = volume.path()
xml_string = salt.utils.stringutils.to_str(ElementTree.tostring(volume_xml))
log.debug("Creating %s", xml_string)
return xml_string
def find_pool_and_volume(conn, path):
# active and persistent storage pools
# TODO: should we filter on type?
for sp in conn.listAllStoragePools(2+4):
for v in sp.listAllVolumes():
if v.path() == path:
return sp, v
raise SaltCloudNotFound('Could not find volume for path {0}'.format(path))
def generate_new_name(orig_name):
if '.' not in orig_name:
return '{0}-{1}'.format(orig_name, uuid.uuid1())
name, ext = orig_name.rsplit('.', 1)
return '{0}-{1}.{2}'.format(name, uuid.uuid1(), ext)
def get_domain_volumes(conn, domain):
volumes = []
xml = ElementTree.fromstring(domain.XMLDesc(0))
for disk in xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
if disk.find("./driver[@name='qemu'][@type='qcow2']") is not None:
source = disk.find("./source").attrib['file']
try:
pool, volume = find_pool_and_volume(conn, source)
volumes.append(volume)
except libvirtError:
log.warning("Disk not found '%s'", source)
return volumes
|
saltstack/salt | salt/output/pprint_out.py | output | python | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Print out via pretty print
'''
if isinstance(data, Exception):
data = six.text_type(data)
if 'output_indent' in __opts__ and __opts__['output_indent'] >= 0:
return pprint.pformat(data, indent=__opts__['output_indent'])
return pprint.pformat(data) | Print out via pretty print | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/pprint_out.py#L34-L42 | null | # -*- coding: utf-8 -*-
'''
Python pretty-print (pprint)
============================
The python pretty-print system was once the default outputter. It simply
passes the return data through to ``pprint.pformat`` and prints the results.
Example output::
{'saltmine': {'foo': {'bar': 'baz',
'dictionary': {'abc': 123, 'def': 456},
'list': ['Hello', 'World']}}}
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import pprint
# Import 3rd-party libs
from salt.ext import six
# Define the module's virtual name
__virtualname__ = 'pprint'
def __virtual__():
'''
Change the name to pprint
'''
return __virtualname__
|
saltstack/salt | salt/cloud/clouds/oneandone.py | get_size | python | def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
) | Return the VM's size object | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L204-L224 | [
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def avail_sizes(call=None):\n '''\n Return a dict of all available VM sizes on the cloud provider with\n relevant data.\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_sizes function must be called with '\n '-f or --function, or with the --list-sizes option'\n )\n\n conn = get_conn()\n\n sizes = conn.fixed_server_flavors()\n\n return sizes\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | get_image | python | def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
) | Return the image object to use | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L227-L242 | [
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def avail_images(conn=None, call=None):\n '''\n Return a list of the server appliances that are on the provider\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_images function must be called with '\n '-f or --function, or with the --list-images option'\n )\n\n if not conn:\n conn = get_conn()\n\n ret = {}\n\n for appliance in conn.list_appliances():\n ret[appliance['name']] = appliance\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | avail_locations | python | def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters} | List available locations/datacenters for 1&1 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L245-L263 | [
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | create_block_storage | python | def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data} | Create a block storage | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L266-L283 | [
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n",
"def _get_block_storage(kwargs):\n '''\n Construct a block storage instance from passed arguments\n '''\n if kwargs is None:\n kwargs = {}\n\n block_storage_name = kwargs.get('name', None)\n block_storage_size = kwargs.get('size', None)\n block_storage_description = kwargs.get('description', None)\n datacenter_id = kwargs.get('datacenter_id', None)\n server_id = kwargs.get('server_id', None)\n\n block_storage = BlockStorage(\n name=block_storage_name,\n size=block_storage_size)\n\n if block_storage_description:\n block_storage.description = block_storage_description\n\n if datacenter_id:\n block_storage.datacenter_id = datacenter_id\n\n if server_id:\n block_storage.server_id = server_id\n\n return block_storage\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | _get_block_storage | python | def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage | Construct a block storage instance from passed arguments | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L286-L312 | null | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | _get_ssh_key | python | def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
) | Construct an SshKey instance from passed arguments | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L315-L327 | null | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | create_ssh_key | python | def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data} | Create an ssh key | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L330-L347 | [
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n",
"def _get_ssh_key(kwargs):\n '''\n Construct an SshKey instance from passed arguments\n '''\n ssh_key_name = kwargs.get('name', None)\n ssh_key_description = kwargs.get('description', None)\n public_key = kwargs.get('public_key', None)\n\n return SshKey(\n name=ssh_key_name,\n description=ssh_key_description,\n public_key=public_key\n )\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | _get_firewall_policy | python | def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules} | Construct FirewallPolicy and FirewallPolicy instances from passed arguments | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L350-L382 | null | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | create_firewall_policy | python | def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data} | Create a firewall policy | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L385-L405 | [
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n",
"def _get_firewall_policy(kwargs):\n '''\n Construct FirewallPolicy and FirewallPolicy instances from passed arguments\n '''\n fp_name = kwargs.get('name', None)\n fp_description = kwargs.get('description', None)\n firewallPolicy = FirewallPolicy(\n name=fp_name,\n description=fp_description\n )\n\n fpr_json = kwargs.get('rules', None)\n jdata = json.loads(fpr_json)\n rules = []\n for fwpr in jdata:\n firewallPolicyRule = FirewallPolicyRule()\n if 'protocol' in fwpr:\n firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']\n if 'port_from' in fwpr:\n firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']\n if 'port_to' in fwpr:\n firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']\n if 'source' in fwpr:\n firewallPolicyRule.rule_set['source'] = fwpr['source']\n if 'action' in fwpr:\n firewallPolicyRule.rule_set['action'] = fwpr['action']\n if 'description' in fwpr:\n firewallPolicyRule.rule_set['description'] = fwpr['description']\n if 'port' in fwpr:\n firewallPolicyRule.rule_set['port'] = fwpr['port']\n rules.append(firewallPolicyRule)\n\n return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | avail_images | python | def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret | Return a list of the server appliances that are on the provider | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L408-L426 | [
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | avail_baremetal_images | python | def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret | Return a list of the baremetal server appliances that are on the provider | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L429-L447 | [
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | avail_sizes | python | def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes | Return a dict of all available VM sizes on the cloud provider with
relevant data. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L450-L465 | [
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | baremetal_models | python | def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels | Return a dict of all available baremetal models with relevant data. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L468-L482 | [
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | list_nodes | python | def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret | Return a list of VMs that are on the provider | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L499-L539 | [
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | list_nodes_full | python | def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret | Return a list of the VMs that are on the provider, with all fields | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L542-L561 | [
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | _get_server | python | def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
) | Construct server instance from cloud profile config | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L596-L716 | null | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | _get_hdds | python | def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds | Construct VM hdds from cloud profile config | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L719-L738 | null | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | create | 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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.') | Create a single VM from a data dict | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L741-L870 | [
"def destroy(name, call=None):\n '''\n destroy a server by name\n\n :param name: name given to the server\n :param call: call value in this case is 'action'\n :return: array of booleans , true if successfully stopped and true if\n successfully removed\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud -d vm_name\n\n '''\n if call == 'function':\n raise SaltCloudSystemExit(\n 'The destroy action must be called with -d, --destroy, '\n '-a or --action.'\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroying instance',\n 'salt/cloud/{0}/destroying'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n conn = get_conn()\n node = get_node(conn, name)\n\n conn.delete_server(server_id=node['id'])\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroyed instance',\n 'salt/cloud/{0}/destroyed'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n if __opts__.get('update_cachedir', False) is True:\n __utils__['cloud.delete_minion_cachedir'](\n name,\n __active_provider_name__.split(':')[0],\n __opts__\n )\n\n return True\n",
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def is_profile_configured(opts, provider, profile_name, vm_=None):\n '''\n Check if the requested profile contains the minimum required parameters for\n a profile.\n\n Required parameters include image and provider for all drivers, while some\n drivers also require size keys.\n\n .. versionadded:: 2015.8.0\n '''\n # Standard dict keys required by all drivers.\n required_keys = ['provider']\n alias, driver = provider.split(':')\n\n # Most drivers need an image to be specified, but some do not.\n non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']\n\n # Most drivers need a size, but some do not.\n non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',\n 'softlayer', 'softlayer_hw', 'vmware', 'vsphere',\n 'virtualbox', 'libvirt', 'oneandone', 'profitbricks']\n\n provider_key = opts['providers'][alias][driver]\n profile_key = opts['providers'][alias][driver]['profiles'][profile_name]\n\n # If cloning on Linode, size and image are not necessary.\n # They are obtained from the to-be-cloned VM.\n if driver == 'linode' and profile_key.get('clonefrom', False):\n non_image_drivers.append('linode')\n non_size_drivers.append('linode')\n elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):\n non_image_drivers.append('gce')\n\n # If cloning on VMware, specifying image is not necessary.\n if driver == 'vmware' and 'image' not in list(profile_key.keys()):\n non_image_drivers.append('vmware')\n\n if driver not in non_image_drivers:\n required_keys.append('image')\n if driver == 'vmware':\n required_keys.append('datastore')\n elif driver in ['linode', 'virtualbox']:\n required_keys.append('clonefrom')\n elif driver == 'nova':\n nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']\n if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):\n required_keys.extend(nova_image_keys)\n\n if driver not in non_size_drivers:\n required_keys.append('size')\n\n # Check if required fields are supplied in the provider config. If they\n # are present, remove it from the required_keys list.\n for item in list(required_keys):\n if item in provider_key:\n required_keys.remove(item)\n\n # If a vm_ dict was passed in, use that information to get any other configs\n # that we might have missed thus far, such as a option provided in a map file.\n if vm_:\n for item in list(required_keys):\n if item in vm_:\n required_keys.remove(item)\n\n # Check for remaining required parameters in the profile config.\n for item in required_keys:\n if profile_key.get(item, None) is None:\n # There's at least one required configuration item which is not set.\n log.error(\n \"The required '%s' configuration setting is missing from \"\n \"the '%s' profile, which is configured under the '%s' alias.\",\n item, profile_name, alias\n )\n return False\n\n return True\n",
"def wait_for_ip(update_callback,\n update_args=None,\n update_kwargs=None,\n timeout=5 * 60,\n interval=5,\n interval_multiplier=1,\n max_failures=10):\n '''\n Helper function that waits for an IP address for a specific maximum amount\n of time.\n\n :param update_callback: callback function which queries the cloud provider\n for the VM ip address. It must return None if the\n required data, IP included, is not available yet.\n :param update_args: Arguments to pass to update_callback\n :param update_kwargs: Keyword arguments to pass to update_callback\n :param timeout: The maximum amount of time(in seconds) to wait for the IP\n address.\n :param interval: The looping interval, i.e., the amount of time to sleep\n before the next iteration.\n :param interval_multiplier: Increase the interval by this multiplier after\n each request; helps with throttling\n :param max_failures: If update_callback returns ``False`` it's considered\n query failure. This value is the amount of failures\n accepted before giving up.\n :returns: The update_callback returned data\n :raises: SaltCloudExecutionTimeout\n\n '''\n if update_args is None:\n update_args = ()\n if update_kwargs is None:\n update_kwargs = {}\n\n duration = timeout\n while True:\n log.debug(\n 'Waiting for VM IP. Giving up in 00:%02d:%02d.',\n int(timeout // 60), int(timeout % 60)\n )\n data = update_callback(*update_args, **update_kwargs)\n if data is False:\n log.debug(\n '\\'update_callback\\' has returned \\'False\\', which is '\n 'considered a failure. Remaining Failures: %s.', max_failures\n )\n max_failures -= 1\n if max_failures <= 0:\n raise SaltCloudExecutionFailure(\n 'Too many failures occurred while waiting for '\n 'the IP address.'\n )\n elif data is not None:\n return data\n\n if timeout < 0:\n raise SaltCloudExecutionTimeout(\n 'Unable to get IP for 00:{0:02d}:{1:02d}.'.format(\n int(duration // 60),\n int(duration % 60)\n )\n )\n time.sleep(interval)\n timeout -= interval\n\n if interval_multiplier > 1:\n interval *= interval_multiplier\n if interval > timeout:\n interval = timeout + 1\n log.info('Interval multiplier in effect; interval is '\n 'now %ss.', interval)\n",
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n",
"def _get_server(vm_):\n '''\n Construct server instance from cloud profile config\n '''\n description = config.get_cloud_config_value(\n 'description', vm_, __opts__, default=None,\n search_global=False\n )\n\n ssh_key = load_public_key(vm_)\n\n server_type = config.get_cloud_config_value(\n 'server_type', vm_, __opts__, default='cloud',\n search_global=False\n )\n vcore = None\n cores_per_processor = None\n ram = None\n fixed_instance_size_id = None\n baremetal_model_id = None\n\n if 'fixed_instance_size' in vm_:\n fixed_instance_size = get_size(vm_)\n fixed_instance_size_id = fixed_instance_size['id']\n elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:\n vcore = config.get_cloud_config_value(\n 'vcore', vm_, __opts__, default=None,\n search_global=False\n )\n cores_per_processor = config.get_cloud_config_value(\n 'cores_per_processor', vm_, __opts__, default=None,\n search_global=False\n )\n ram = config.get_cloud_config_value(\n 'ram', vm_, __opts__, default=None,\n search_global=False\n )\n elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':\n baremetal_model_id = config.get_cloud_config_value(\n 'baremetal_model_id', vm_, __opts__, default=None,\n search_global=False\n )\n else:\n raise SaltCloudConfigError(\"'fixed_instance_size' or 'vcore', \"\n \"'cores_per_processor', 'ram', and 'hdds' \"\n \"must be provided for 'cloud' server. \"\n \"For 'baremetal' server, 'baremetal_model_id'\"\n \"must be provided.\")\n\n appliance_id = config.get_cloud_config_value(\n 'appliance_id', vm_, __opts__, default=None,\n search_global=False\n )\n\n password = config.get_cloud_config_value(\n 'password', vm_, __opts__, default=None,\n search_global=False\n )\n\n firewall_policy_id = config.get_cloud_config_value(\n 'firewall_policy_id', vm_, __opts__, default=None,\n search_global=False\n )\n\n ip_id = config.get_cloud_config_value(\n 'ip_id', vm_, __opts__, default=None,\n search_global=False\n )\n\n load_balancer_id = config.get_cloud_config_value(\n 'load_balancer_id', vm_, __opts__, default=None,\n search_global=False\n )\n\n monitoring_policy_id = config.get_cloud_config_value(\n 'monitoring_policy_id', vm_, __opts__, default=None,\n search_global=False\n )\n\n datacenter_id = config.get_cloud_config_value(\n 'datacenter_id', vm_, __opts__, default=None,\n search_global=False\n )\n\n private_network_id = config.get_cloud_config_value(\n 'private_network_id', vm_, __opts__, default=None,\n search_global=False\n )\n\n power_on = config.get_cloud_config_value(\n 'power_on', vm_, __opts__, default=True,\n search_global=False\n )\n\n public_key = config.get_cloud_config_value(\n 'public_key_ids', vm_, __opts__, default=None,\n search_global=False\n )\n\n # Contruct server object\n return Server(\n name=vm_['name'],\n description=description,\n fixed_instance_size_id=fixed_instance_size_id,\n vcore=vcore,\n cores_per_processor=cores_per_processor,\n ram=ram,\n appliance_id=appliance_id,\n password=password,\n power_on=power_on,\n firewall_policy_id=firewall_policy_id,\n ip_id=ip_id,\n load_balancer_id=load_balancer_id,\n monitoring_policy_id=monitoring_policy_id,\n datacenter_id=datacenter_id,\n rsa_key=ssh_key,\n private_network_id=private_network_id,\n public_key=public_key,\n server_type=server_type,\n baremetal_model_id=baremetal_model_id\n )\n",
"def _wait_for_completion(conn, wait_timeout, server_id):\n '''\n Poll request status until resource is provisioned.\n '''\n wait_timeout = time.time() + wait_timeout\n while wait_timeout > time.time():\n time.sleep(5)\n\n server = conn.get_server(server_id)\n server_state = server['status']['state'].lower()\n\n if server_state == \"powered_on\":\n return\n elif server_state == 'failed':\n raise Exception('Server creation failed for {0}'.format(server_id))\n elif server_state in ('active',\n 'enabled',\n 'deploying',\n 'configuring'):\n continue\n else:\n raise Exception(\n 'Unknown server state {0}'.format(server_state))\n raise Exception(\n 'Timed out waiting for server create completion for {0}'.format(server_id)\n )\n",
"def get_wait_timeout(vm_):\n '''\n Return the wait_for_timeout for resource provisioning.\n '''\n return config.get_cloud_config_value(\n 'wait_for_timeout', vm_, __opts__, default=15 * 60,\n search_global=False\n )\n",
"def get_key_filename(vm_):\n '''\n Check SSH private key file and return absolute path if exists.\n '''\n key_filename = config.get_cloud_config_value(\n 'ssh_private_key', vm_, __opts__, search_global=False, default=None\n )\n if key_filename is not None:\n key_filename = os.path.expanduser(key_filename)\n if not os.path.isfile(key_filename):\n raise SaltCloudConfigError(\n 'The defined ssh_private_key \\'{0}\\' does not exist'.format(\n key_filename\n )\n )\n\n return key_filename\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | destroy | python | def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True | destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L873-L925 | [
"def get_node(conn, name):\n '''\n Return a node for the named VM\n '''\n for node in conn.list_servers(per_page=1000):\n if node['name'] == name:\n return node\n",
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | reboot | python | def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True | reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L928-L946 | [
"def get_node(conn, name):\n '''\n Return a node for the named VM\n '''\n for node in conn.list_servers(per_page=1000):\n if node['name'] == name:\n return node\n",
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n return OneAndOneService(\n api_token=config.get_cloud_config_value(\n 'api_token',\n get_configured_provider(),\n __opts__,\n search_global=False\n )\n )\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | get_node | python | def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node | Return a node for the named VM | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L992-L998 | null | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | load_public_key | python | def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key | Load the public key file if exists. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L1020-L1039 | [
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n"
] | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
)
|
saltstack/salt | salt/cloud/clouds/oneandone.py | _wait_for_completion | python | def _wait_for_completion(conn, wait_timeout, server_id):
'''
Poll request status until resource is provisioned.
'''
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
server = conn.get_server(server_id)
server_state = server['status']['state'].lower()
if server_state == "powered_on":
return
elif server_state == 'failed':
raise Exception('Server creation failed for {0}'.format(server_id))
elif server_state in ('active',
'enabled',
'deploying',
'configuring'):
continue
else:
raise Exception(
'Unknown server state {0}'.format(server_state))
raise Exception(
'Timed out waiting for server create completion for {0}'.format(server_id)
) | Poll request status until resource is provisioned. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L1052-L1077 | null | # -*- coding: utf-8 -*-
'''
1&1 Cloud Server Module
=======================
The 1&1 SaltStack cloud module allows a 1&1 server to be automatically deployed
and bootstrapped with Salt. It also has functions to create block storages and
ssh keys.
:depends: 1and1 >= 1.2.0
The module requires the 1&1 api_token to be provided. The server should also
be assigned a public LAN, a private LAN, or both along with SSH key pairs.
Set up the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/oneandone.conf``:
.. code-block:: yaml
my-oneandone-config:
driver: oneandone
# The 1&1 api token
api_token: <your-token>
# SSH private key filename
ssh_private_key: /path/to/private_key
# SSH public key filename
ssh_public_key: /path/to/public_key
.. code-block:: yaml
my-oneandone-profile:
provider: my-oneandone-config
# Either provide fixed_instance_size_id or vcore, cores_per_processor, ram, and hdds.
# Size of the ID desired for the server
fixed_instance_size: S
# Total amount of processors
vcore: 2
# Number of cores per processor
cores_per_processor: 2
# RAM memory size in GB
ram: 4
# Hard disks
hdds:
-
is_main: true
size: 20
-
is_main: false
size: 20
# ID of the appliance image that will be installed on server
appliance_id: <ID>
# ID of the datacenter where the server will be created
datacenter_id: <ID>
# Description of the server
description: My server description
# Password of the server. Password must contain more than 8 characters
# using uppercase letters, numbers and other special symbols.
password: P4$$w0rD
# Power on server after creation - default True
power_on: true
# Firewall policy ID. If it is not provided, the server will assign
# the best firewall policy, creating a new one if necessary.
# If the parameter is sent with a 0 value, the server will be created with all ports blocked.
firewall_policy_id: <ID>
# IP address ID
ip_id: <ID>
# Load balancer ID
load_balancer_id: <ID>
# Monitoring policy ID
monitoring_policy_id: <ID>
# Baremetal model ID
baremetal_model_id: <ID>
# Server type
server_type: <cloud or baremetal> - default cloud
Set ``deploy`` to False if Salt should not be installed on the node.
.. code-block:: yaml
my-oneandone-profile:
deploy: False
Create an SSH key
.. code-block:: bash
sudo salt-cloud -f create_ssh_key my-oneandone-config name='SaltTest' description='SaltTestDescription'
Create a block storage
.. code-block:: bash
sudo salt-cloud -f create_block_storage my-oneandone-config name='SaltTest2'
description='SaltTestDescription' size=50 datacenter_id='5091F6D8CBFEF9C26ACE957C652D5D49'
Create a firewall policy
.. code-block:: bash
sudo salt-cloud -f create_firewall_policy oneandone name='1salttest'
description='salt_test_desc' rules='[{"protocol":"TCP", "port":"80", "description":"salt_fw_rule_desc"}]'
List baremetal models
.. code-block:: bash
sudo salt-cloud -f baremetal_models oneandone
List baremetal images
.. code-block:: bash
sudo salt-cloud -f avail_baremetal_images oneandone
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import pprint
import time
import json
# Import salt libs
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
SaltCloudSystemExit
)
import salt.utils.files
# Import salt.cloud libs
import salt.utils.cloud
import salt.utils.stringutils
from salt.ext import six
try:
from oneandone.client import (
OneAndOneService, FirewallPolicy, FirewallPolicyRule, Server, Hdd, SshKey, BlockStorage
)
HAS_ONEANDONE = True
except ImportError:
HAS_ONEANDONE = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'oneandone'
# Only load in this module if the 1&1 configurations are in place
def __virtual__():
'''
Check for 1&1 configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('api_token',)
)
def get_dependencies():
'''
Warn if dependencies are not met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'oneandone': HAS_ONEANDONE}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
return OneAndOneService(
api_token=config.get_cloud_config_value(
'api_token',
get_configured_provider(),
__opts__,
search_global=False
)
)
def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value(
'fixed_instance_size', vm_, __opts__, default=None,
search_global=False
)
sizes = avail_sizes()
if not vm_size:
size = next((item for item in sizes if item['name'] == 'S'), None)
return size
size = next((item for item in sizes if item['name'] == vm_size or item['id'] == vm_size), None)
if size:
return size
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['id'], images[key]['name']):
return images[key]
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def avail_locations(conn=None, call=None):
'''
List available locations/datacenters for 1&1
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
datacenters = []
if not conn:
conn = get_conn()
for datacenter in conn.list_datacenters():
datacenters.append({datacenter['country_code']: datacenter})
return {'Locations': datacenters}
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite block storage object.
block_storage = _get_block_storage(kwargs)
data = conn.create_block_storage(block_storage=block_storage)
return {'BlockStorage': data}
def _get_block_storage(kwargs):
'''
Construct a block storage instance from passed arguments
'''
if kwargs is None:
kwargs = {}
block_storage_name = kwargs.get('name', None)
block_storage_size = kwargs.get('size', None)
block_storage_description = kwargs.get('description', None)
datacenter_id = kwargs.get('datacenter_id', None)
server_id = kwargs.get('server_id', None)
block_storage = BlockStorage(
name=block_storage_name,
size=block_storage_size)
if block_storage_description:
block_storage.description = block_storage_description
if datacenter_id:
block_storage.datacenter_id = datacenter_id
if server_id:
block_storage.server_id = server_id
return block_storage
def _get_ssh_key(kwargs):
'''
Construct an SshKey instance from passed arguments
'''
ssh_key_name = kwargs.get('name', None)
ssh_key_description = kwargs.get('description', None)
public_key = kwargs.get('public_key', None)
return SshKey(
name=ssh_key_name,
description=ssh_key_description,
public_key=public_key
)
def create_ssh_key(kwargs=None, call=None):
'''
Create an ssh key
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_ssh_key function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite SshKey object.
ssh_key = _get_ssh_key(kwargs)
data = conn.create_ssh_key(ssh_key=ssh_key)
return {'SshKey': data}
def _get_firewall_policy(kwargs):
'''
Construct FirewallPolicy and FirewallPolicy instances from passed arguments
'''
fp_name = kwargs.get('name', None)
fp_description = kwargs.get('description', None)
firewallPolicy = FirewallPolicy(
name=fp_name,
description=fp_description
)
fpr_json = kwargs.get('rules', None)
jdata = json.loads(fpr_json)
rules = []
for fwpr in jdata:
firewallPolicyRule = FirewallPolicyRule()
if 'protocol' in fwpr:
firewallPolicyRule.rule_set['protocol'] = fwpr['protocol']
if 'port_from' in fwpr:
firewallPolicyRule.rule_set['port_from'] = fwpr['port_from']
if 'port_to' in fwpr:
firewallPolicyRule.rule_set['port_to'] = fwpr['port_to']
if 'source' in fwpr:
firewallPolicyRule.rule_set['source'] = fwpr['source']
if 'action' in fwpr:
firewallPolicyRule.rule_set['action'] = fwpr['action']
if 'description' in fwpr:
firewallPolicyRule.rule_set['description'] = fwpr['description']
if 'port' in fwpr:
firewallPolicyRule.rule_set['port'] = fwpr['port']
rules.append(firewallPolicyRule)
return {'firewall_policy': firewallPolicy, 'firewall_policy_rules': rules}
def create_firewall_policy(kwargs=None, call=None):
'''
Create a firewall policy
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_firewall_policy function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite FirewallPolicy and FirewallPolicyRule[] objects.
getFwpResult = _get_firewall_policy(kwargs)
data = conn.create_firewall_policy(
firewall_policy=getFwpResult['firewall_policy'],
firewall_policy_rules=getFwpResult['firewall_policy_rules']
)
return {'FirewallPolicy': data}
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret
def avail_baremetal_images(conn=None, call=None):
'''
Return a list of the baremetal server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_baremetal_images function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances(q='BAREMETAL'):
ret[appliance['name']] = appliance
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes
def baremetal_models(call=None):
'''
Return a dict of all available baremetal models with relevant data.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The baremetal_models function must be called with '
'-f or --function'
)
conn = get_conn()
bmodels = conn.list_baremetal_models()
return bmodels
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
public_ips = []
private_ips = []
ret = {}
size = node.get('hardware').get('fixed_instance_size_id', 'Custom size')
if node.get('private_networks'):
for private_ip in node['private_networks']:
private_ips.append(private_ip)
if node.get('ips'):
for public_ip in node['ips']:
public_ips.append(public_ip['ip'])
server = {
'id': node['id'],
'image': node['image']['id'],
'size': size,
'state': node['status']['state'],
'private_ips': private_ips,
'public_ips': public_ips
}
ret[node['name']] = server
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn()
ret = {}
nodes = conn.list_servers()
for node in nodes:
ret[node['name']] = node
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'),
__opts__['query.selection'],
call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](
nodes[name],
__active_provider_name__,
__opts__
)
return nodes[name]
def _get_server(vm_):
'''
Construct server instance from cloud profile config
'''
description = config.get_cloud_config_value(
'description', vm_, __opts__, default=None,
search_global=False
)
ssh_key = load_public_key(vm_)
server_type = config.get_cloud_config_value(
'server_type', vm_, __opts__, default='cloud',
search_global=False
)
vcore = None
cores_per_processor = None
ram = None
fixed_instance_size_id = None
baremetal_model_id = None
if 'fixed_instance_size' in vm_:
fixed_instance_size = get_size(vm_)
fixed_instance_size_id = fixed_instance_size['id']
elif 'vm_core' in vm_ and 'cores_per_processor' in vm_ and 'ram' in vm_ and 'hdds' in vm_:
vcore = config.get_cloud_config_value(
'vcore', vm_, __opts__, default=None,
search_global=False
)
cores_per_processor = config.get_cloud_config_value(
'cores_per_processor', vm_, __opts__, default=None,
search_global=False
)
ram = config.get_cloud_config_value(
'ram', vm_, __opts__, default=None,
search_global=False
)
elif 'baremetal_model_id' in vm_ and server_type == 'baremetal':
baremetal_model_id = config.get_cloud_config_value(
'baremetal_model_id', vm_, __opts__, default=None,
search_global=False
)
else:
raise SaltCloudConfigError("'fixed_instance_size' or 'vcore', "
"'cores_per_processor', 'ram', and 'hdds' "
"must be provided for 'cloud' server. "
"For 'baremetal' server, 'baremetal_model_id'"
"must be provided.")
appliance_id = config.get_cloud_config_value(
'appliance_id', vm_, __opts__, default=None,
search_global=False
)
password = config.get_cloud_config_value(
'password', vm_, __opts__, default=None,
search_global=False
)
firewall_policy_id = config.get_cloud_config_value(
'firewall_policy_id', vm_, __opts__, default=None,
search_global=False
)
ip_id = config.get_cloud_config_value(
'ip_id', vm_, __opts__, default=None,
search_global=False
)
load_balancer_id = config.get_cloud_config_value(
'load_balancer_id', vm_, __opts__, default=None,
search_global=False
)
monitoring_policy_id = config.get_cloud_config_value(
'monitoring_policy_id', vm_, __opts__, default=None,
search_global=False
)
datacenter_id = config.get_cloud_config_value(
'datacenter_id', vm_, __opts__, default=None,
search_global=False
)
private_network_id = config.get_cloud_config_value(
'private_network_id', vm_, __opts__, default=None,
search_global=False
)
power_on = config.get_cloud_config_value(
'power_on', vm_, __opts__, default=True,
search_global=False
)
public_key = config.get_cloud_config_value(
'public_key_ids', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
password=password,
power_on=power_on,
firewall_policy_id=firewall_policy_id,
ip_id=ip_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
public_key=public_key,
server_type=server_type,
baremetal_model_id=baremetal_model_id
)
def _get_hdds(vm_):
'''
Construct VM hdds from cloud profile config
'''
_hdds = config.get_cloud_config_value(
'hdds', vm_, __opts__, default=None,
search_global=False
)
hdds = []
for hdd in _hdds:
hdds.append(
Hdd(
size=hdd['size'],
is_main=hdd['is_main']
)
)
return hdds
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
'oneandone'),
vm_['profile']) is False):
return False
except AttributeError:
pass
data = None
conn = get_conn()
hdds = []
# Assemble the composite server object.
server = _get_server(vm_)
if not bool(server.specs['hardware']['fixed_instance_size_id'])\
and not bool(server.specs['server_type'] == 'baremetal'):
# Assemble the hdds object.
hdds = _get_hdds(vm_)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={'name': vm_['name']},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = conn.create_server(server=server, hdds=hdds)
_wait_for_completion(conn,
get_wait_timeout(vm_),
data['id'])
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s on 1and1\n\n'
'The following exception was thrown by the 1and1 library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
password = data['first_password']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'],
pprint.pformat(data['name']),
data['status']['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['status']['state'].lower() == 'powered_on'
if not running:
# Still not running, trigger another iteration
return
vm_['ssh_host'] = data['ips'][0]['ip']
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args={
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if 'ssh_host' in vm_:
vm_['password'] = password
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.')
def destroy(name, call=None):
'''
destroy a server by name
:param name: name given to the server
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
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']
)
conn = get_conn()
node = get_node(conn, name)
conn.delete_server(server_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 True
def reboot(name, call=None):
'''
reboot a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.modify_server_status(server_id=node['id'], action='REBOOT')
return True
def stop(name, call=None):
'''
stop a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(server_id=node['id'])
return True
def start(name, call=None):
'''
start a server by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
conn = get_conn()
node = get_node(conn, name)
conn.start_server(server_id=node['id'])
return True
def get_node(conn, name):
'''
Return a node for the named VM
'''
for node in conn.list_servers(per_page=1000):
if node['name'] == name:
return node
def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_filename)
if not os.path.isfile(public_key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
public_key_filename
)
)
with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))
return key
def get_wait_timeout(vm_):
'''
Return the wait_for_timeout for resource provisioning.
'''
return config.get_cloud_config_value(
'wait_for_timeout', vm_, __opts__, default=15 * 60,
search_global=False
)
|
saltstack/salt | salt/states/bigip.py | _load_result | python | def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret | format the results of listing functions | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L26-L50 | null | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | _strip_key | python | def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary | look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L53-L70 | [
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _strip_key(dictionary, keyword):\n '''\n look for a certain key within a dictionary and nullify ti's contents, check within nested\n dictionaries and lists as well. Certain attributes such as \"generation\" will change even\n when there were no changes made to the entity.\n '''\n\n for key, value in six.iteritems(dictionary):\n if key == keyword:\n dictionary[key] = None\n elif isinstance(value, dict):\n _strip_key(value, keyword)\n elif isinstance(value, list):\n for item in value:\n if isinstance(item, dict):\n _strip_key(item, keyword)\n\n return dictionary\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | _check_for_changes | python | def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret | take an existing entity and a modified entity and check for changes. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L73-L106 | null | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | create_node | python | def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret | Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L165-L215 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | manage_node | python | def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret | Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ] | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L218-L369 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _check_for_changes(entity_type, ret, existing, modified):\n '''\n take an existing entity and a modified entity and check for changes.\n '''\n\n ret['result'] = True\n\n #were there any changes? generation always changes, remove it.\n\n if isinstance(existing, dict) and isinstance(modified, dict):\n if 'generation' in modified['content'].keys():\n del modified['content']['generation']\n\n if 'generation' in existing['content'].keys():\n del existing['content']['generation']\n\n if modified['content'] == existing['content']:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing['content']\n ret['changes']['new'] = modified['content']\n\n else:\n if modified == existing:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing\n ret['changes']['new'] = modified\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | modify_node | python | def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret | Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ] | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L372-L467 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _check_for_changes(entity_type, ret, existing, modified):\n '''\n take an existing entity and a modified entity and check for changes.\n '''\n\n ret['result'] = True\n\n #were there any changes? generation always changes, remove it.\n\n if isinstance(existing, dict) and isinstance(modified, dict):\n if 'generation' in modified['content'].keys():\n del modified['content']['generation']\n\n if 'generation' in existing['content'].keys():\n del existing['content']['generation']\n\n if modified['content'] == existing['content']:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing['content']\n ret['changes']['new'] = modified['content']\n\n else:\n if modified == existing:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing\n ret['changes']['new'] = modified\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | create_pool | python | def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret | Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer] | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L554-L731 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | manage_pool | python | def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret | Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer] | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L734-L951 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _check_for_changes(entity_type, ret, existing, modified):\n '''\n take an existing entity and a modified entity and check for changes.\n '''\n\n ret['result'] = True\n\n #were there any changes? generation always changes, remove it.\n\n if isinstance(existing, dict) and isinstance(modified, dict):\n if 'generation' in modified['content'].keys():\n del modified['content']['generation']\n\n if 'generation' in existing['content'].keys():\n del existing['content']['generation']\n\n if modified['content'] == existing['content']:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing['content']\n ret['changes']['new'] = modified['content']\n\n else:\n if modified == existing:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing\n ret['changes']['new'] = modified\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | delete_pool | python | def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret | Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L1135-L1187 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | manage_pool_members | python | def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret | Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L1190-L1266 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _check_for_changes(entity_type, ret, existing, modified):\n '''\n take an existing entity and a modified entity and check for changes.\n '''\n\n ret['result'] = True\n\n #were there any changes? generation always changes, remove it.\n\n if isinstance(existing, dict) and isinstance(modified, dict):\n if 'generation' in modified['content'].keys():\n del modified['content']['generation']\n\n if 'generation' in existing['content'].keys():\n del existing['content']['generation']\n\n if modified['content'] == existing['content']:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing['content']\n ret['changes']['new'] = modified['content']\n\n else:\n if modified == existing:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing\n ret['changes']['new'] = modified\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | add_pool_member | python | def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret | A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L1269-L1355 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | modify_pool_member | python | def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret | A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ] | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L1358-L1494 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _check_for_changes(entity_type, ret, existing, modified):\n '''\n take an existing entity and a modified entity and check for changes.\n '''\n\n ret['result'] = True\n\n #were there any changes? generation always changes, remove it.\n\n if isinstance(existing, dict) and isinstance(modified, dict):\n if 'generation' in modified['content'].keys():\n del modified['content']['generation']\n\n if 'generation' in existing['content'].keys():\n del existing['content']['generation']\n\n if modified['content'] == existing['content']:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing['content']\n ret['changes']['new'] = modified['content']\n\n else:\n if modified == existing:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing\n ret['changes']['new'] = modified\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | delete_pool_member | python | def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret | Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L1497-L1561 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | list_virtual | python | def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret) | A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L1564-L1590 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | manage_virtual | python | def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret | Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ] | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L1851-L2169 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _strip_key(dictionary, keyword):\n '''\n look for a certain key within a dictionary and nullify ti's contents, check within nested\n dictionaries and lists as well. Certain attributes such as \"generation\" will change even\n when there were no changes made to the entity.\n '''\n\n for key, value in six.iteritems(dictionary):\n if key == keyword:\n dictionary[key] = None\n elif isinstance(value, dict):\n _strip_key(value, keyword)\n elif isinstance(value, list):\n for item in value:\n if isinstance(item, dict):\n _strip_key(item, keyword)\n\n return dictionary\n",
"def _check_for_changes(entity_type, ret, existing, modified):\n '''\n take an existing entity and a modified entity and check for changes.\n '''\n\n ret['result'] = True\n\n #were there any changes? generation always changes, remove it.\n\n if isinstance(existing, dict) and isinstance(modified, dict):\n if 'generation' in modified['content'].keys():\n del modified['content']['generation']\n\n if 'generation' in existing['content'].keys():\n del existing['content']['generation']\n\n if modified['content'] == existing['content']:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing['content']\n ret['changes']['new'] = modified['content']\n\n else:\n if modified == existing:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing\n ret['changes']['new'] = modified\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | modify_virtual | python | def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret | Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ] | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L2172-L2436 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _strip_key(dictionary, keyword):\n '''\n look for a certain key within a dictionary and nullify ti's contents, check within nested\n dictionaries and lists as well. Certain attributes such as \"generation\" will change even\n when there were no changes made to the entity.\n '''\n\n for key, value in six.iteritems(dictionary):\n if key == keyword:\n dictionary[key] = None\n elif isinstance(value, dict):\n _strip_key(value, keyword)\n elif isinstance(value, list):\n for item in value:\n if isinstance(item, dict):\n _strip_key(item, keyword)\n\n return dictionary\n",
"def _check_for_changes(entity_type, ret, existing, modified):\n '''\n take an existing entity and a modified entity and check for changes.\n '''\n\n ret['result'] = True\n\n #were there any changes? generation always changes, remove it.\n\n if isinstance(existing, dict) and isinstance(modified, dict):\n if 'generation' in modified['content'].keys():\n del modified['content']['generation']\n\n if 'generation' in existing['content'].keys():\n del existing['content']['generation']\n\n if modified['content'] == existing['content']:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing['content']\n ret['changes']['new'] = modified['content']\n\n else:\n if modified == existing:\n ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)\n else:\n ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \\\n 'were enforced. See changes for details.'.format(entity_type=entity_type)\n ret['changes']['old'] = existing\n ret['changes']['new'] = modified\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | create_monitor | python | def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret | A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L2524-L2587 | [
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/states/bigip.py | create_profile | python | def create_profile(hostname, username, password, profile_type, name, **kwargs):
r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A profile by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret | r'''
A function to connect to a bigip device and create a profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
Special Characters ``|``, ``,`` and ``:`` must be escaped using ``\`` when
used within strings. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L2823-L2885 | [
"def _load_result(response, ret):\n '''\n format the results of listing functions\n '''\n\n #were we able to connect?\n if response['code'] is None:\n ret['comment'] = response['content']\n #forbidden?\n elif response['code'] == 401:\n ret['comment'] = '401 Forbidden: Authentication required!'\n #Not found?\n elif response['code'] == 404:\n ret['comment'] = response['content']['message']\n #200?\n elif response['code'] == 200:\n ret['result'] = True\n ret['comment'] = 'Listing Current Configuration Only. ' \\\n 'Not action or changes occurred during the execution of this state.'\n ret['changes'] = response['content']\n #something bad\n else:\n ret['comment'] = response['content']['message']\n\n return ret\n",
"def _test_output(ret, action, params):\n '''\n For testing just output what the state will attempt to do without actually doing it.\n '''\n\n if action == 'list':\n ret['comment'] += 'The list action will just list an entity and will make no changes.\\n'\n elif action == 'create' or action == 'add':\n ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\\n'\n elif action == 'delete':\n ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\\n'\n elif action == 'manage':\n ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \\\n 'to the desired state.\\n'\n elif action == 'modify':\n ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\\n'\n\n ret['comment'] += 'An iControl REST Request will be made using the parameters:\\n'\n ret['comment'] += salt.utils.json.dumps(params, indent=4)\n\n ret['changes'] = {}\n # Return ``None`` when running with ``test=true``.\n ret['result'] = None\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
A state module designed to enforce load-balancing configurations for F5 Big-IP entities.
:maturity: develop
:platform: f5_bigip_11.6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.json
# Import 3rd-party libs
from salt.ext import six
#set up virtual function
def __virtual__():
'''
Only load if the bigip exec module is available in __salt__
'''
return 'bigip' if 'bigip.list_transaction' in __salt__ else False
def _load_result(response, ret):
'''
format the results of listing functions
'''
#were we able to connect?
if response['code'] is None:
ret['comment'] = response['content']
#forbidden?
elif response['code'] == 401:
ret['comment'] = '401 Forbidden: Authentication required!'
#Not found?
elif response['code'] == 404:
ret['comment'] = response['content']['message']
#200?
elif response['code'] == 200:
ret['result'] = True
ret['comment'] = 'Listing Current Configuration Only. ' \
'Not action or changes occurred during the execution of this state.'
ret['changes'] = response['content']
#something bad
else:
ret['comment'] = response['content']['message']
return ret
def _strip_key(dictionary, keyword):
'''
look for a certain key within a dictionary and nullify ti's contents, check within nested
dictionaries and lists as well. Certain attributes such as "generation" will change even
when there were no changes made to the entity.
'''
for key, value in six.iteritems(dictionary):
if key == keyword:
dictionary[key] = None
elif isinstance(value, dict):
_strip_key(value, keyword)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_strip_key(item, keyword)
return dictionary
def _check_for_changes(entity_type, ret, existing, modified):
'''
take an existing entity and a modified entity and check for changes.
'''
ret['result'] = True
#were there any changes? generation always changes, remove it.
if isinstance(existing, dict) and isinstance(modified, dict):
if 'generation' in modified['content'].keys():
del modified['content']['generation']
if 'generation' in existing['content'].keys():
del existing['content']['generation']
if modified['content'] == existing['content']:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing['content']
ret['changes']['new'] = modified['content']
else:
if modified == existing:
ret['comment'] = '{entity_type} is currently enforced to the desired state. No changes made.'.format(entity_type=entity_type)
else:
ret['comment'] = '{entity_type} was enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'.format(entity_type=entity_type)
ret['changes']['old'] = existing
ret['changes']['new'] = modified
return ret
def _test_output(ret, action, params):
'''
For testing just output what the state will attempt to do without actually doing it.
'''
if action == 'list':
ret['comment'] += 'The list action will just list an entity and will make no changes.\n'
elif action == 'create' or action == 'add':
ret['comment'] += 'The create action will attempt to create an entity if it does not already exist.\n'
elif action == 'delete':
ret['comment'] += 'The delete action will attempt to delete an existing entity if it exists.\n'
elif action == 'manage':
ret['comment'] += 'The manage action will create a new entity if it does not exist. If it does exist, it will be enforced' \
'to the desired state.\n'
elif action == 'modify':
ret['comment'] += 'The modify action will attempt to modify an existing entity only if it exists.\n'
ret['comment'] += 'An iControl REST Request will be made using the parameters:\n'
ret['comment'] += salt.utils.json.dumps(params, indent=4)
ret['changes'] = {}
# Return ``None`` when running with ``test=true``.
ret['result'] = None
return ret
def list_node(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_node'](hostname, username, password, name)
return _load_result(response, ret)
def create_node(hostname, username, password, name, address):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A node by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_node'](hostname, username, password, name, address)
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Node was successfully created.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_node(hostname, username, password, name, address,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Manages a node of a given bigip device. If the node does not exist it will be created, otherwise,
only the properties which are different than the existing will be updated.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to manage.
address
The address of the node
connection_limit
[integer]
description
[string]
dynam
c_ratio: [integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'address': address,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
# ensure the address is the same, we don't want to modify a different node than what
# we think we are managing
if existing['content']['address'] != address:
ret['result'] = False
ret['comment'] = 'A node with this name exists but the address does not match.'
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
new = __salt__['bigip.create_node'](hostname, username, password, name, address)
# were we able to create it?
if new['code'] == 200:
# try modification
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = modified['content']
# roll it back
else:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node has been rolled back. Message is as follows:\n' \
'{message}'.format(message=modified['content']['message'])
# something bad happened
else:
ret['comment'] = 'Node was successfully created but an error occurred during modification. ' \
'The creation of the node was not able to be rolled back. Message is as follows:' \
'\n {message}\n{message_two}'.format(message=modified['content']['message'],
message_two=deleted['content']['message'])
# unable to create it
else:
ret = _load_result(new, ret)
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
node_state=None):
'''
Modify an existing node. Only a node which already exists will be modified and
only the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
logging
[enabled | disabled]
monitor
[[name] | none | default]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
node_state (state)
[user-down | user-up ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'connection_limit': connection_limit,
'description': description,
'dynamic_ratio': dynamic_ratio,
'logging': logging,
'monitor': monitor,
'rate_limit': rate_limit,
'ratio': ratio,
'session': session,
'state:': node_state
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
modified = __salt__['bigip.modify_node'](hostname=hostname,
username=username,
password=password,
name=name,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
logging=logging,
monitor=monitor,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=node_state)
#was the modification successful?
if modified['code'] == 200:
ret = _check_for_changes('Node', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# not found, attempt to create it
elif existing['code'] == 404:
ret['comment'] = 'A node with this name was not found.'
# an error occurred
else:
ret = _load_result(existing, ret)
return ret
def delete_node(hostname, username, password, name):
'''
Delete an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node which will be deleted.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this node currently configured?
existing = __salt__['bigip.list_node'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_node'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Node was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(existing, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This node already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_pool(hostname, username, password, name):
'''
A function to connect to a bigip device and list a specific pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to list.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
response = __salt__['bigip.list_pool'](hostname, username, password, name)
return _load_result(response, ret)
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
members
List of members to be added to the pool
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A pool by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
members=members,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Pool was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Create a new pool if it does not already exist. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
new = __salt__['bigip.create_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
# were we able to create it?
if new['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was created and enforced to the desired state. Note: Only parameters specified ' \
'were enforced. See changes for details.'
ret['changes']['old'] = {}
ret['changes']['new'] = new['content']
# unable to create it
else:
ret = _load_result(new, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_pool(hostname, username, password, name,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_to_server=None,
link_qos_to_client=None,
link_qos_to_server=None,
load_balancing_mode=None,
min_active_members=None,
min_up_members=None,
min_up_members_action=None,
min_up_members_checking=None,
monitor=None,
profiles=None,
queue_depth_limit=None,
queue_on_connection_limit=None,
queue_time_limit=None,
reselect_tries=None,
service_down_action=None,
slow_ramp_time=None):
'''
Modify an existing pool. Pool members are managed separately. Only the
parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create
allow_nat
[yes | no]
allow_snat
[yes | no]
description
[string]
gateway_failsafe_device
[string]
ignore_persisted_weight
[enabled | disabled]
ip_tos_to_client
[pass-through | [integer]]
ip_tos_to_server
[pass-through | [integer]]
link_qos_to_client
[pass-through | [integer]]
link_qos_to_server
[pass-through | [integer]]
load_balancing_mode
[dynamic-ratio-member | dynamic-ratio-node |
fastest-app-response | fastest-node |
least-connections-members |
least-connections-node |
least-sessions |
observed-member | observed-node |
predictive-member | predictive-node |
ratio-least-connections-member |
ratio-least-connections-node |
ratio-member | ratio-node | ratio-session |
round-robin | weighted-least-connections-member |
weighted-least-connections-node]
min_active_members
[integer]
min_up_members
[integer]
min_up_members_action
[failover | reboot | restart-all]
min_up_members_checking
[enabled | disabled]
monitor
[name]
profiles
[none | profile_name]
queue_depth_limit
[integer]
queue_on_connection_limit
[enabled | disabled]
queue_time_limit
[integer]
reselect_tries
[integer]
service_down_action
[drop | none | reselect | reset]
slow_ramp_time
[integer]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'allow_nat': allow_nat,
'allow_snat': allow_snat,
'description': description,
'gateway_failsafe_device': gateway_failsafe_device,
'ignore_persisted_weight': ignore_persisted_weight,
'ip_tos_client:': ip_tos_to_client,
'ip_tos_server': ip_tos_to_server,
'link_qos_to_client': link_qos_to_client,
'link_qos_to_server': link_qos_to_server,
'load_balancing_mode': load_balancing_mode,
'min_active_members': min_active_members,
'min_up_members': min_up_members,
'min_up_members_checking': min_up_members_checking,
'monitor': monitor,
'profiles': profiles,
'queue_depth_limit': queue_depth_limit,
'queue_on_connection_limit': queue_on_connection_limit,
'queue_time_limit': queue_time_limit,
'reselect_tries': reselect_tries,
'service_down_action': service_down_action,
'slow_ramp_time': slow_ramp_time
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
modified = __salt__['bigip.modify_pool'](hostname=hostname,
username=username,
password=password,
name=name,
allow_nat=allow_nat,
allow_snat=allow_snat,
description=description,
gateway_failsafe_device=gateway_failsafe_device,
ignore_persisted_weight=ignore_persisted_weight,
ip_tos_to_client=ip_tos_to_client,
ip_tos_to_server=ip_tos_to_server,
link_qos_to_client=link_qos_to_client,
link_qos_to_server=link_qos_to_server,
load_balancing_mode=load_balancing_mode,
min_active_members=min_active_members,
min_up_members=min_up_members,
min_up_members_action=min_up_members_action,
min_up_members_checking=min_up_members_checking,
monitor=monitor,
profiles=profiles,
queue_depth_limit=queue_depth_limit,
queue_on_connection_limit=queue_on_connection_limit,
queue_time_limit=queue_time_limit,
reselect_tries=reselect_tries,
service_down_action=service_down_action,
slow_ramp_time=slow_ramp_time)
#was the modification successful?
if modified['code'] == 200:
#remove member listings and self-links
del existing['content']['membersReference']
del modified['content']['membersReference']
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Pool', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_pool'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This pool already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def manage_pool_members(hostname, username, password, name, members):
'''
Manage the members of an existing pool. This function replaces all current pool members.
Only the parameters specified are enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
members
list of pool members to manage.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': members
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
modified = __salt__['bigip.replace_pool_members'](hostname, username, password, name, members)
#was the modification successful?
if modified['code'] == 200:
#re-list the pool with new membership
new_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
#just in case something happened...
if new_listing['code'] != 200:
ret = _load_result(new_listing, ret)
ret['comment'] = 'modification of the pool was successful but an error occurred upon retrieving new' \
' listing.'
return ret
new_members = new_listing['content']['membersReference']['items']
#remove generation keys and create new lists indexed by integers
for current_member in current_members:
del current_member['generation']
for new_member in new_members:
del new_member['generation']
#anything changed?
ret = _check_for_changes('Pool Membership', ret, current_members, new_members)
else:
ret = _load_result(modified, ret)
#pool does not exists
elif existing['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing, ret)
return ret
def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member to add to the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'add', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member['name']:
exists = True
break
if exists:
ret['result'] = True
ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name'])
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member)
if new_member['code'] == 200:
ret['result'] = True
ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name'])
ret['changes']['old'] = {}
#look up the member again...
pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name)
if pool_listing['code'] != 200:
ret = _load_result(new_member, ret)
return ret
members = pool_listing['content']['membersReference']['items']
#loop through them
for current_member in members:
if current_member['name'] == member['name']:
added_member = current_member
break
ret['changes']['new'] = added_member
# member wasn't added
else:
ret = _load_result(new_member, ret)
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def modify_pool_member(hostname, username, password, name, member,
connection_limit=None,
description=None,
dynamic_ratio=None,
inherit_profile=None,
logging=None,
monitor=None,
priority_group=None,
profiles=None,
rate_limit=None,
ratio=None,
session=None,
member_state=None):
'''
A function to connect to a bigip device and modify a member of an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to modify
member
The member modify
connection_limit
[integer]
description
[string]
dynamic_ratio
[integer]
inherit_profile
[enabled | disabled]
logging
[enabled | disabled]
monitor
[name]
priority_group
[integer]
profiles
[none | profile_name]
rate_limit
[integer]
ratio
[integer]
session
[user-enabled | user-disabled]
member_state (state)
[ user-up | user-down ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool member currently configured?
existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if existing_pool['code'] == 200:
# for some reason iControl REST doesn't support listing a single pool member.
# the response from GET for listing a member will return 200 even if it doesn't exists.
# because of this we have to do some rather "unnecessary" searching within a pool.
#what are the current members?
current_members = existing_pool['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
#modify the pool member
modified = __salt__['bigip.modify_pool_member'](hostname=hostname,
username=username,
password=password,
name=name,
member=member,
connection_limit=connection_limit,
description=description,
dynamic_ratio=dynamic_ratio,
inherit_profile=inherit_profile,
logging=logging,
monitor=monitor,
priority_group=priority_group,
profiles=profiles,
rate_limit=rate_limit,
ratio=ratio,
session=session,
state=member_state)
#re-list the pool
new_pool = __salt__['bigip.list_pool'](hostname, username, password, name)
if modified['code'] == 200 and modified['code'] == 200:
#what are the new members?
new_members = new_pool['content']['membersReference']['items']
#loop through them
for new_member in new_members:
if new_member['name'] == member:
modified_member = new_member
break
#check for changes
old = {'content': existing_member}
new = {'content': modified_member}
ret = _check_for_changes('Pool Member: {member}'.format(member=member), ret, old, new)
else:
ret = _load_result(modified, ret)
else:
ret['comment'] = 'Member: {name} does not exists within this pool. No changes made.'.format(name=member['name'])
#pool does not exists
elif existing_pool['code'] == 404:
ret['comment'] = 'A pool with this name was not found.'
else:
ret = _load_result(existing_pool, ret)
return ret
def delete_pool_member(hostname, username, password, name, member):
'''
Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'members': member
}
)
#is this pool currently configured?
existing = __salt__['bigip.list_pool'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
#what are the current members?
current_members = existing['content']['membersReference']['items']
#loop through them
exists = False
for current_member in current_members:
if current_member['name'] == member:
exists = True
existing_member = current_member
break
if exists:
deleted = __salt__['bigip.delete_pool_member'](hostname, username, password, name, member)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Pool Member: {member} was successfully deleted.'.format(member=member)
ret['changes']['old'] = existing_member
ret['changes']['new'] = {}
# something bad happened
else:
ret['result'] = True
ret['comment'] = 'This pool member already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_virtual(hostname, username, password, name):
'''
A function to list a specific virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
response = __salt__['bigip.list_virtual'](hostname, username, password, name)
return _load_result(response, ret)
def create_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
A function to connect to a bigip device and create a virtual server if it does not already exists.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'create', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A virtual by this name currently exists. No change made.'
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Manage a virtual server. If a virtual does not exists it will be created, otherwise only the
parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit-dst
[integer]
rate_limit-src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'manage', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
#create it
virtual = __salt__['bigip.create_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#were we able to create it?
if virtual['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = virtual['content']
ret['comment'] = 'Virtual was successfully created and enforced to the desired state.'
else:
ret = _load_result(virtual, ret)
else:
ret = _load_result(existing, ret)
return ret
def modify_virtual(hostname, username, password, name, destination,
pool=None,
address_status=None,
auto_lasthop=None,
bwc_policy=None,
cmp_enabled=None,
connection_limit=None,
dhcp_relay=None,
description=None,
fallback_persistence=None,
flow_eviction_policy=None,
gtm_score=None,
ip_forward=None,
ip_protocol=None,
internal=None,
twelve_forward=None,
last_hop_pool=None,
mask=None,
mirror=None,
nat64=None,
persist=None,
profiles=None,
policies=None,
rate_class=None,
rate_limit=None,
rate_limit_mode=None,
rate_limit_dst=None,
rate_limit_src=None,
rules=None,
related_rules=None,
reject=None,
source=None,
source_address_translation=None,
source_port=None,
virtual_state=None,
traffic_classes=None,
translate_address=None,
translate_port=None,
vlans=None):
'''
Modify an virtual server. modify an existing virtual. Only parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual to create
destination
[ [virtual_address_name:port] | [ipv4:port] | [ipv6.port] ]
pool
[ [pool_name] | none]
address_status
[yes | no]
auto_lasthop
[default | enabled | disabled ]
bwc_policy
[none] | string]
cmp_enabled
[yes | no]
dhcp_relay
[yes | no}
connection_limit
[integer]
description
[string]
state
[disabled | enabled]
fallback_persistence
[none | [profile name] ]
flow_eviction_policy
[none | [eviction policy name] ]
gtm_score
[integer]
ip_forward
[yes | no]
ip_protocol
[any | protocol]
internal
[yes | no]
twelve_forward(12-forward)
[yes | no]
last_hop-pool
[ [pool_name] | none]
mask
{ [ipv4] | [ipv6] }
mirror
{ [disabled | enabled | none] }
nat64
[enabled | disabled]
persist
[list]
profiles
[none | default | list ]
policies
[none | default | list ]
rate_class
[name]
rate_limit
[integer]
rate_limit-mode
[destination | object | object-destination |
object-source | object-source-destination |
source | source-destination]
rate_limit_dst
[integer]
rate_limit_src
[integer]
rules
[none | list ]
related_rules
[none | list ]
reject
[yes | no]
source
{ [ipv4[/prefixlen]] | [ipv6[/prefixlen]] }
source_address_translation
[none | snat:pool_name | lsn | automap | dictionary ]
source_port
[change | preserve | preserve-strict]
state
[enabled | disabled]
traffic_classes
[none | default | list ]
translate_address
[enabled | disabled]
translate_port
[enabled | disabled]
vlans
[none | default | dictionary ]
vlan_ids
[ list]
enabled
[ true | false ]
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'modify', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name,
'destination': destination,
'pool': pool,
'address_status': address_status,
'auto_lasthop': auto_lasthop,
'bwc_policy': bwc_policy,
'cmp_enabled': cmp_enabled,
'connection_limit': connection_limit,
'dhcp_relay': dhcp_relay,
'description': description,
'fallback_persistence': fallback_persistence,
'flow_eviction_policy': flow_eviction_policy,
'gtm_score': gtm_score,
'ip_forward': ip_forward,
'ip_protocol': ip_protocol,
'internal': internal,
'twelve_forward': twelve_forward,
'last_hop_pool': last_hop_pool,
'mask': mask,
'mirror': mirror,
'nat64': nat64,
'persist': persist,
'profiles': profiles,
'policies': policies,
'rate_class': rate_class,
'rate_limit': rate_limit,
'rate_limit_mode': rate_limit_mode,
'rate_limit_dst': rate_limit_dst,
'rate_limit_src': rate_limit_src,
'rules': rules,
'related_rules': related_rules,
'reject': reject,
'source': source,
'source_address_translation': source_address_translation,
'source_port': source_port,
'virtual_state': virtual_state,
'traffic_classes': traffic_classes,
'translate_address': translate_address,
'translate_port': translate_port,
'vlans': vlans
}
)
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# does this virtual exist?
if existing['code'] == 200:
# modify
modified = __salt__['bigip.modify_virtual'](hostname=hostname,
username=username,
password=password,
name=name,
destination=destination,
description=description,
pool=pool,
address_status=address_status,
auto_lasthop=auto_lasthop,
bwc_policy=bwc_policy,
cmp_enabled=cmp_enabled,
connection_limit=connection_limit,
dhcp_relay=dhcp_relay,
fallback_persistence=fallback_persistence,
flow_eviction_policy=flow_eviction_policy,
gtm_score=gtm_score,
ip_forward=ip_forward,
ip_protocol=ip_protocol,
internal=internal,
twelve_forward=twelve_forward,
last_hop_pool=last_hop_pool,
mask=mask,
mirror=mirror,
nat64=nat64,
persist=persist,
profiles=profiles,
policies=policies,
rate_class=rate_class,
rate_limit=rate_limit,
rate_limit_mode=rate_limit_mode,
rate_limit_dst=rate_limit_dst,
rate_limit_src=rate_limit_src,
rules=rules,
related_rules=related_rules,
reject=reject,
source=source,
source_address_translation=source_address_translation,
source_port=source_port,
state=virtual_state,
traffic_classes=traffic_classes,
translate_address=translate_address,
translate_port=translate_port,
vlans=vlans)
#was the modification successful?
if modified['code'] == 200:
#relist it to compare
relisting = __salt__['bigip.list_virtual'](hostname, username, password, name)
if relisting['code'] == 200:
relisting = _strip_key(relisting, 'generation')
existing = _strip_key(existing, 'generation')
ret = _check_for_changes('Virtual', ret, existing, relisting)
else:
ret = _load_result(relisting, ret)
else:
ret = _load_result(modified, ret)
elif existing['code'] == 404:
ret['comment'] = 'A Virtual with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_virtual(hostname, username, password, name):
'''
Delete an existing virtual.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the virtual which will be deleted
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'name': name
}
)
#is this virtual currently configured?
existing = __salt__['bigip.list_virtual'](hostname, username, password, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_virtual'](hostname, username, password, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Virtual was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This virtual already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_monitor(hostname, username, password, monitor_type, name):
'''
A function to list an existing monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to list
name
The name of the monitor to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
)
response = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
return _load_result(response, ret)
def create_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
A function to connect to a bigip device and create a monitor.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'create', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
ret['result'] = True
ret['comment'] = 'A monitor by this name currently exists. No change made.'
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def manage_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Create a new monitor if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_monitor'](hostname, username, password, monitor_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Monitor was successfully created.'
else:
ret = _load_result(response, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_monitor(hostname, username, password, monitor_type, name, **kwargs):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this monitor currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists
if existing['code'] == 200:
#modify the monitor
modified = __salt__['bigip.modify_monitor'](hostname, username, password, monitor_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Monitor', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Monitor with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_monitor(hostname, username, password, monitor_type, name):
'''
Modify an existing monitor. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
monitor_type
The type of monitor to create
name
The name of the monitor to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'monitor_type': monitor_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_monitor'](hostname, username, password, monitor_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_monitor'](hostname, username, password, monitor_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Monitor was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Monitor already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
def list_profile(hostname, username, password, profile_type, name):
'''
A function to list an existing profile.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to list
name
The name of the profile to list
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'list', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
response = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
return _load_result(response, ret)
def manage_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Create a new profile if a monitor of this type and name does not already exists. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'manage', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
response = __salt__['bigip.create_profile'](hostname, username, password, profile_type, name, **kwargs)
if response['code'] == 200:
ret['result'] = True
ret['changes']['old'] = {}
ret['changes']['new'] = response['content']
ret['comment'] = 'Profile was successfully created.'
else:
ret = _load_result(existing, ret)
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def modify_profile(hostname, username, password, profile_type, name, **kwargs):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each monitor type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
params = {
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
}
for key, value in six.iteritems(kwargs):
params[key] = value
return _test_output(ret, 'modify', params)
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists
if existing['code'] == 200:
#modify the profile
modified = __salt__['bigip.modify_profile'](hostname, username, password, profile_type, name, **kwargs)
#was the modification successful?
if modified['code'] == 200:
del existing['content']['selfLink']
del modified['content']['selfLink']
ret = _check_for_changes('Profile', ret, existing, modified)
else:
ret = _load_result(modified, ret)
# if it doesn't exist
elif existing['code'] == 404:
ret['comment'] = 'A Profile with this name was not found.'
# else something else was returned
else:
ret = _load_result(existing, ret)
return ret
def delete_profile(hostname, username, password, profile_type, name):
'''
Modify an existing profile. If it does exists, only
the parameters specified will be enforced.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
profile_type
The type of profile to create
name
The name of the profile to create
kwargs
[ arg=val ] ...
Consult F5 BIGIP user guide for specific options for each profile type.
Typically, tmsh arg names are used.
'''
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
if __opts__['test']:
return _test_output(ret, 'delete', params={
'hostname': hostname,
'username': username,
'password': password,
'profile_type': profile_type,
'name': name
})
#is this profile currently configured?
existing = __salt__['bigip.list_profile'](hostname, username, password, profile_type, name)
# if it exists by name
if existing['code'] == 200:
deleted = __salt__['bigip.delete_profile'](hostname, username, password, profile_type, name)
# did we get rid of it?
if deleted['code'] == 200:
ret['result'] = True
ret['comment'] = 'Profile was successfully deleted.'
ret['changes']['old'] = existing['content']
ret['changes']['new'] = {}
# something bad happened
else:
ret = _load_result(deleted, ret)
# not found
elif existing['code'] == 404:
ret['result'] = True
ret['comment'] = 'This Profile already does not exist. No changes made.'
ret['changes']['old'] = {}
ret['changes']['new'] = {}
else:
ret = _load_result(existing, ret)
return ret
|
saltstack/salt | salt/cloud/clouds/scaleway.py | avail_images | python | def avail_images(call=None):
''' Return a list of the images that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
items = query(method='images', root='marketplace_root')
ret = {}
for image in items['images']:
ret[image['id']] = {}
for item in image:
ret[image['id']][item] = six.text_type(image[item])
return ret | Return a list of the images that are on the provider. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/scaleway.py#L72-L88 | [
"def query(method='servers', server_id=None, command=None, args=None,\n http_method='GET', root='api_root'):\n ''' Make a call to the Scaleway API.\n '''\n\n if root == 'api_root':\n default_url = 'https://cp-par1.scaleway.com'\n else:\n default_url = 'https://api-marketplace.scaleway.com'\n\n base_path = six.text_type(config.get_cloud_config_value(\n root,\n get_configured_provider(),\n __opts__,\n search_global=False,\n default=default_url\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if server_id:\n path += '{0}/'.format(server_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n token = config.get_cloud_config_value(\n 'token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n request = __utils__[\"http.query\"](path,\n method=http_method,\n data=data,\n status=True,\n decode=True,\n decode_type='json',\n data_render=True,\n data_renderer='json',\n headers=True,\n header_dict={'X-Auth-Token': token,\n 'User-Agent': \"salt-cloud\",\n 'Content-Type': 'application/json'})\n if request['status'] > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying Scaleway. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request['status'],\n request['error']\n )\n )\n\n # success without data\n if request['status'] == 204:\n return True\n\n return salt.utils.json.loads(request['body'])\n"
] | # -*- coding: utf-8 -*-
'''
Scaleway Cloud Module
=====================
.. versionadded:: 2015.8.0
The Scaleway cloud module is used to interact with your Scaleway BareMetal
Servers.
Use of this module only requires the ``api_key`` parameter to be set. Set up
the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/scaleway.conf``:
.. code-block:: yaml
scaleway-config:
# Scaleway organization and token
access_key: 0e604a2c-aea6-4081-acb2-e1d1258ef95c
token: be8fd96b-04eb-4d39-b6ba-a9edbcf17f12
driver: scaleway
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pprint
import os
import time
# Import Salt Libs
from salt.ext import six
from salt.ext.six.moves import range
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
log = logging.getLogger(__name__)
__virtualname__ = 'scaleway'
# Only load in this module if the Scaleway configurations are in place
def __virtual__():
'''
Check for Scaleway configurations.
'''
if get_configured_provider() is False:
return False
return __virtualname__
def get_configured_provider():
''' Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('token',)
)
def list_nodes(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
items = query(method='servers')
ret = {}
for node in items['servers']:
public_ips = []
private_ips = []
image_id = ''
if node.get('public_ip'):
public_ips = [node['public_ip']['address']]
if node.get('private_ip'):
private_ips = [node['private_ip']]
if node.get('image'):
image_id = node['image']['id']
ret[node['name']] = {
'id': node['id'],
'image_id': image_id,
'public_ips': public_ips,
'private_ips': private_ips,
'size': node['volumes']['0']['size'],
'state': node['state'],
}
return ret
def list_nodes_full(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'list_nodes_full must be called with -f or --function'
)
items = query(method='servers')
# For each server, iterate on its parameters.
ret = {}
for node in items['servers']:
ret[node['name']] = {}
for item in node:
value = node[item]
ret[node['name']][item] = value
return ret
def list_nodes_select(call=None):
''' Return a list of the BareMetal servers that are on the provider, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(server_):
''' Return the image object to use.
'''
images = avail_images()
server_image = six.text_type(config.get_cloud_config_value(
'image', server_, __opts__, search_global=False
))
for image in images:
if server_image in (images[image]['name'], images[image]['id']):
return images[image]['id']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(server_image)
)
def create_node(args):
''' Create a node.
'''
node = query(method='servers', args=args, http_method='POST')
action = query(
method='servers',
server_id=node['server']['id'],
command='action',
args={'action': 'poweron'},
http_method='POST'
)
return node
def create(server_):
'''
Create a single BareMetal server from a data dict.
'''
try:
# Check for required profile parameters before sending any API calls.
if server_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'scaleway',
server_['profile'],
vm_=server_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(server_['name']),
args=__utils__['cloud.filter_event']('creating', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating a BareMetal server %s', server_['name'])
access_key = config.get_cloud_config_value(
'access_key', get_configured_provider(), __opts__, search_global=False
)
commercial_type = config.get_cloud_config_value(
'commercial_type', server_, __opts__, default='C1'
)
key_filename = config.get_cloud_config_value(
'ssh_key_file', server_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
ssh_password = config.get_cloud_config_value(
'ssh_password', server_, __opts__
)
kwargs = {
'name': server_['name'],
'organization': access_key,
'image': get_image(server_),
'commercial_type': commercial_type,
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(server_['name']),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Scaleway\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
server_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(server_name):
''' Called to check if the server has a public IP address.
'''
data = show_instance(server_name, 'action')
if data and data.get('public_ip'):
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(server_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', server_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', server_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(server_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
server_['ssh_host'] = data['public_ip']['address']
server_['ssh_password'] = ssh_password
server_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](server_, __opts__)
ret.update(data)
log.info('Created BareMetal server \'%s\'', server_['name'])
log.debug(
'\'%s\' BareMetal server creation details:\n%s',
server_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(server_['name']),
args=__utils__['cloud.filter_event']('created', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='servers', server_id=None, command=None, args=None,
http_method='GET', root='api_root'):
''' Make a call to the Scaleway API.
'''
if root == 'api_root':
default_url = 'https://cp-par1.scaleway.com'
else:
default_url = 'https://api-marketplace.scaleway.com'
base_path = six.text_type(config.get_cloud_config_value(
root,
get_configured_provider(),
__opts__,
search_global=False,
default=default_url
))
path = '{0}/{1}/'.format(base_path, method)
if server_id:
path += '{0}/'.format(server_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
token = config.get_cloud_config_value(
'token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
request = __utils__["http.query"](path,
method=http_method,
data=data,
status=True,
decode=True,
decode_type='json',
data_render=True,
data_renderer='json',
headers=True,
header_dict={'X-Auth-Token': token,
'User-Agent': "salt-cloud",
'Content-Type': 'application/json'})
if request['status'] > 299:
raise SaltCloudSystemExit(
'An error occurred while querying Scaleway. HTTP Code: {0} '
'Error: \'{1}\''.format(
request['status'],
request['error']
)
)
# success without data
if request['status'] == 204:
return True
return salt.utils.json.loads(request['body'])
def script(server_):
''' Return the script deployment object.
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', server_, __opts__),
server_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, server_)
)
)
def show_instance(name, call=None):
''' Show the details from a Scaleway BareMetal server.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
for attempt in reversed(list(range(10))):
try:
return list_nodes_full()[name]
except KeyError:
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempt
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def destroy(name, call=None):
''' Destroy a node. Will check termination protection and warn if enabled.
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']
)
data = show_instance(name, call='action')
node = query(
method='servers', server_id=data['id'], command='action',
args={'action': 'terminate'}, http_method='POST'
)
__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 node
|
saltstack/salt | salt/cloud/clouds/scaleway.py | list_nodes | python | def list_nodes(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
items = query(method='servers')
ret = {}
for node in items['servers']:
public_ips = []
private_ips = []
image_id = ''
if node.get('public_ip'):
public_ips = [node['public_ip']['address']]
if node.get('private_ip'):
private_ips = [node['private_ip']]
if node.get('image'):
image_id = node['image']['id']
ret[node['name']] = {
'id': node['id'],
'image_id': image_id,
'public_ips': public_ips,
'private_ips': private_ips,
'size': node['volumes']['0']['size'],
'state': node['state'],
}
return ret | Return a list of the BareMetal servers that are on the provider. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/scaleway.py#L91-L124 | [
"def query(method='servers', server_id=None, command=None, args=None,\n http_method='GET', root='api_root'):\n ''' Make a call to the Scaleway API.\n '''\n\n if root == 'api_root':\n default_url = 'https://cp-par1.scaleway.com'\n else:\n default_url = 'https://api-marketplace.scaleway.com'\n\n base_path = six.text_type(config.get_cloud_config_value(\n root,\n get_configured_provider(),\n __opts__,\n search_global=False,\n default=default_url\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if server_id:\n path += '{0}/'.format(server_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n token = config.get_cloud_config_value(\n 'token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n request = __utils__[\"http.query\"](path,\n method=http_method,\n data=data,\n status=True,\n decode=True,\n decode_type='json',\n data_render=True,\n data_renderer='json',\n headers=True,\n header_dict={'X-Auth-Token': token,\n 'User-Agent': \"salt-cloud\",\n 'Content-Type': 'application/json'})\n if request['status'] > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying Scaleway. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request['status'],\n request['error']\n )\n )\n\n # success without data\n if request['status'] == 204:\n return True\n\n return salt.utils.json.loads(request['body'])\n"
] | # -*- coding: utf-8 -*-
'''
Scaleway Cloud Module
=====================
.. versionadded:: 2015.8.0
The Scaleway cloud module is used to interact with your Scaleway BareMetal
Servers.
Use of this module only requires the ``api_key`` parameter to be set. Set up
the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/scaleway.conf``:
.. code-block:: yaml
scaleway-config:
# Scaleway organization and token
access_key: 0e604a2c-aea6-4081-acb2-e1d1258ef95c
token: be8fd96b-04eb-4d39-b6ba-a9edbcf17f12
driver: scaleway
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pprint
import os
import time
# Import Salt Libs
from salt.ext import six
from salt.ext.six.moves import range
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
log = logging.getLogger(__name__)
__virtualname__ = 'scaleway'
# Only load in this module if the Scaleway configurations are in place
def __virtual__():
'''
Check for Scaleway configurations.
'''
if get_configured_provider() is False:
return False
return __virtualname__
def get_configured_provider():
''' Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('token',)
)
def avail_images(call=None):
''' Return a list of the images that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
items = query(method='images', root='marketplace_root')
ret = {}
for image in items['images']:
ret[image['id']] = {}
for item in image:
ret[image['id']][item] = six.text_type(image[item])
return ret
def list_nodes_full(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'list_nodes_full must be called with -f or --function'
)
items = query(method='servers')
# For each server, iterate on its parameters.
ret = {}
for node in items['servers']:
ret[node['name']] = {}
for item in node:
value = node[item]
ret[node['name']][item] = value
return ret
def list_nodes_select(call=None):
''' Return a list of the BareMetal servers that are on the provider, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(server_):
''' Return the image object to use.
'''
images = avail_images()
server_image = six.text_type(config.get_cloud_config_value(
'image', server_, __opts__, search_global=False
))
for image in images:
if server_image in (images[image]['name'], images[image]['id']):
return images[image]['id']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(server_image)
)
def create_node(args):
''' Create a node.
'''
node = query(method='servers', args=args, http_method='POST')
action = query(
method='servers',
server_id=node['server']['id'],
command='action',
args={'action': 'poweron'},
http_method='POST'
)
return node
def create(server_):
'''
Create a single BareMetal server from a data dict.
'''
try:
# Check for required profile parameters before sending any API calls.
if server_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'scaleway',
server_['profile'],
vm_=server_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(server_['name']),
args=__utils__['cloud.filter_event']('creating', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating a BareMetal server %s', server_['name'])
access_key = config.get_cloud_config_value(
'access_key', get_configured_provider(), __opts__, search_global=False
)
commercial_type = config.get_cloud_config_value(
'commercial_type', server_, __opts__, default='C1'
)
key_filename = config.get_cloud_config_value(
'ssh_key_file', server_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
ssh_password = config.get_cloud_config_value(
'ssh_password', server_, __opts__
)
kwargs = {
'name': server_['name'],
'organization': access_key,
'image': get_image(server_),
'commercial_type': commercial_type,
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(server_['name']),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Scaleway\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
server_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(server_name):
''' Called to check if the server has a public IP address.
'''
data = show_instance(server_name, 'action')
if data and data.get('public_ip'):
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(server_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', server_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', server_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(server_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
server_['ssh_host'] = data['public_ip']['address']
server_['ssh_password'] = ssh_password
server_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](server_, __opts__)
ret.update(data)
log.info('Created BareMetal server \'%s\'', server_['name'])
log.debug(
'\'%s\' BareMetal server creation details:\n%s',
server_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(server_['name']),
args=__utils__['cloud.filter_event']('created', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='servers', server_id=None, command=None, args=None,
http_method='GET', root='api_root'):
''' Make a call to the Scaleway API.
'''
if root == 'api_root':
default_url = 'https://cp-par1.scaleway.com'
else:
default_url = 'https://api-marketplace.scaleway.com'
base_path = six.text_type(config.get_cloud_config_value(
root,
get_configured_provider(),
__opts__,
search_global=False,
default=default_url
))
path = '{0}/{1}/'.format(base_path, method)
if server_id:
path += '{0}/'.format(server_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
token = config.get_cloud_config_value(
'token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
request = __utils__["http.query"](path,
method=http_method,
data=data,
status=True,
decode=True,
decode_type='json',
data_render=True,
data_renderer='json',
headers=True,
header_dict={'X-Auth-Token': token,
'User-Agent': "salt-cloud",
'Content-Type': 'application/json'})
if request['status'] > 299:
raise SaltCloudSystemExit(
'An error occurred while querying Scaleway. HTTP Code: {0} '
'Error: \'{1}\''.format(
request['status'],
request['error']
)
)
# success without data
if request['status'] == 204:
return True
return salt.utils.json.loads(request['body'])
def script(server_):
''' Return the script deployment object.
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', server_, __opts__),
server_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, server_)
)
)
def show_instance(name, call=None):
''' Show the details from a Scaleway BareMetal server.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
for attempt in reversed(list(range(10))):
try:
return list_nodes_full()[name]
except KeyError:
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempt
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def destroy(name, call=None):
''' Destroy a node. Will check termination protection and warn if enabled.
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']
)
data = show_instance(name, call='action')
node = query(
method='servers', server_id=data['id'], command='action',
args={'action': 'terminate'}, http_method='POST'
)
__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 node
|
saltstack/salt | salt/cloud/clouds/scaleway.py | list_nodes_full | python | def list_nodes_full(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'list_nodes_full must be called with -f or --function'
)
items = query(method='servers')
# For each server, iterate on its parameters.
ret = {}
for node in items['servers']:
ret[node['name']] = {}
for item in node:
value = node[item]
ret[node['name']][item] = value
return ret | Return a list of the BareMetal servers that are on the provider. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/scaleway.py#L127-L144 | [
"def query(method='servers', server_id=None, command=None, args=None,\n http_method='GET', root='api_root'):\n ''' Make a call to the Scaleway API.\n '''\n\n if root == 'api_root':\n default_url = 'https://cp-par1.scaleway.com'\n else:\n default_url = 'https://api-marketplace.scaleway.com'\n\n base_path = six.text_type(config.get_cloud_config_value(\n root,\n get_configured_provider(),\n __opts__,\n search_global=False,\n default=default_url\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if server_id:\n path += '{0}/'.format(server_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n token = config.get_cloud_config_value(\n 'token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n request = __utils__[\"http.query\"](path,\n method=http_method,\n data=data,\n status=True,\n decode=True,\n decode_type='json',\n data_render=True,\n data_renderer='json',\n headers=True,\n header_dict={'X-Auth-Token': token,\n 'User-Agent': \"salt-cloud\",\n 'Content-Type': 'application/json'})\n if request['status'] > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying Scaleway. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request['status'],\n request['error']\n )\n )\n\n # success without data\n if request['status'] == 204:\n return True\n\n return salt.utils.json.loads(request['body'])\n"
] | # -*- coding: utf-8 -*-
'''
Scaleway Cloud Module
=====================
.. versionadded:: 2015.8.0
The Scaleway cloud module is used to interact with your Scaleway BareMetal
Servers.
Use of this module only requires the ``api_key`` parameter to be set. Set up
the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/scaleway.conf``:
.. code-block:: yaml
scaleway-config:
# Scaleway organization and token
access_key: 0e604a2c-aea6-4081-acb2-e1d1258ef95c
token: be8fd96b-04eb-4d39-b6ba-a9edbcf17f12
driver: scaleway
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pprint
import os
import time
# Import Salt Libs
from salt.ext import six
from salt.ext.six.moves import range
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
log = logging.getLogger(__name__)
__virtualname__ = 'scaleway'
# Only load in this module if the Scaleway configurations are in place
def __virtual__():
'''
Check for Scaleway configurations.
'''
if get_configured_provider() is False:
return False
return __virtualname__
def get_configured_provider():
''' Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('token',)
)
def avail_images(call=None):
''' Return a list of the images that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
items = query(method='images', root='marketplace_root')
ret = {}
for image in items['images']:
ret[image['id']] = {}
for item in image:
ret[image['id']][item] = six.text_type(image[item])
return ret
def list_nodes(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
items = query(method='servers')
ret = {}
for node in items['servers']:
public_ips = []
private_ips = []
image_id = ''
if node.get('public_ip'):
public_ips = [node['public_ip']['address']]
if node.get('private_ip'):
private_ips = [node['private_ip']]
if node.get('image'):
image_id = node['image']['id']
ret[node['name']] = {
'id': node['id'],
'image_id': image_id,
'public_ips': public_ips,
'private_ips': private_ips,
'size': node['volumes']['0']['size'],
'state': node['state'],
}
return ret
def list_nodes_select(call=None):
''' Return a list of the BareMetal servers that are on the provider, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(server_):
''' Return the image object to use.
'''
images = avail_images()
server_image = six.text_type(config.get_cloud_config_value(
'image', server_, __opts__, search_global=False
))
for image in images:
if server_image in (images[image]['name'], images[image]['id']):
return images[image]['id']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(server_image)
)
def create_node(args):
''' Create a node.
'''
node = query(method='servers', args=args, http_method='POST')
action = query(
method='servers',
server_id=node['server']['id'],
command='action',
args={'action': 'poweron'},
http_method='POST'
)
return node
def create(server_):
'''
Create a single BareMetal server from a data dict.
'''
try:
# Check for required profile parameters before sending any API calls.
if server_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'scaleway',
server_['profile'],
vm_=server_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(server_['name']),
args=__utils__['cloud.filter_event']('creating', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating a BareMetal server %s', server_['name'])
access_key = config.get_cloud_config_value(
'access_key', get_configured_provider(), __opts__, search_global=False
)
commercial_type = config.get_cloud_config_value(
'commercial_type', server_, __opts__, default='C1'
)
key_filename = config.get_cloud_config_value(
'ssh_key_file', server_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
ssh_password = config.get_cloud_config_value(
'ssh_password', server_, __opts__
)
kwargs = {
'name': server_['name'],
'organization': access_key,
'image': get_image(server_),
'commercial_type': commercial_type,
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(server_['name']),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Scaleway\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
server_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(server_name):
''' Called to check if the server has a public IP address.
'''
data = show_instance(server_name, 'action')
if data and data.get('public_ip'):
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(server_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', server_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', server_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(server_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
server_['ssh_host'] = data['public_ip']['address']
server_['ssh_password'] = ssh_password
server_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](server_, __opts__)
ret.update(data)
log.info('Created BareMetal server \'%s\'', server_['name'])
log.debug(
'\'%s\' BareMetal server creation details:\n%s',
server_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(server_['name']),
args=__utils__['cloud.filter_event']('created', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='servers', server_id=None, command=None, args=None,
http_method='GET', root='api_root'):
''' Make a call to the Scaleway API.
'''
if root == 'api_root':
default_url = 'https://cp-par1.scaleway.com'
else:
default_url = 'https://api-marketplace.scaleway.com'
base_path = six.text_type(config.get_cloud_config_value(
root,
get_configured_provider(),
__opts__,
search_global=False,
default=default_url
))
path = '{0}/{1}/'.format(base_path, method)
if server_id:
path += '{0}/'.format(server_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
token = config.get_cloud_config_value(
'token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
request = __utils__["http.query"](path,
method=http_method,
data=data,
status=True,
decode=True,
decode_type='json',
data_render=True,
data_renderer='json',
headers=True,
header_dict={'X-Auth-Token': token,
'User-Agent': "salt-cloud",
'Content-Type': 'application/json'})
if request['status'] > 299:
raise SaltCloudSystemExit(
'An error occurred while querying Scaleway. HTTP Code: {0} '
'Error: \'{1}\''.format(
request['status'],
request['error']
)
)
# success without data
if request['status'] == 204:
return True
return salt.utils.json.loads(request['body'])
def script(server_):
''' Return the script deployment object.
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', server_, __opts__),
server_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, server_)
)
)
def show_instance(name, call=None):
''' Show the details from a Scaleway BareMetal server.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
for attempt in reversed(list(range(10))):
try:
return list_nodes_full()[name]
except KeyError:
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempt
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def destroy(name, call=None):
''' Destroy a node. Will check termination protection and warn if enabled.
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']
)
data = show_instance(name, call='action')
node = query(
method='servers', server_id=data['id'], command='action',
args={'action': 'terminate'}, http_method='POST'
)
__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 node
|
saltstack/salt | salt/cloud/clouds/scaleway.py | get_image | python | def get_image(server_):
''' Return the image object to use.
'''
images = avail_images()
server_image = six.text_type(config.get_cloud_config_value(
'image', server_, __opts__, search_global=False
))
for image in images:
if server_image in (images[image]['name'], images[image]['id']):
return images[image]['id']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(server_image)
) | Return the image object to use. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/scaleway.py#L156-L168 | [
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def avail_images(call=None):\n ''' Return a list of the images that are on the provider.\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_images function must be called with '\n '-f or --function, or with the --list-images option'\n )\n\n items = query(method='images', root='marketplace_root')\n ret = {}\n for image in items['images']:\n ret[image['id']] = {}\n for item in image:\n ret[image['id']][item] = six.text_type(image[item])\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
Scaleway Cloud Module
=====================
.. versionadded:: 2015.8.0
The Scaleway cloud module is used to interact with your Scaleway BareMetal
Servers.
Use of this module only requires the ``api_key`` parameter to be set. Set up
the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/scaleway.conf``:
.. code-block:: yaml
scaleway-config:
# Scaleway organization and token
access_key: 0e604a2c-aea6-4081-acb2-e1d1258ef95c
token: be8fd96b-04eb-4d39-b6ba-a9edbcf17f12
driver: scaleway
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pprint
import os
import time
# Import Salt Libs
from salt.ext import six
from salt.ext.six.moves import range
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
log = logging.getLogger(__name__)
__virtualname__ = 'scaleway'
# Only load in this module if the Scaleway configurations are in place
def __virtual__():
'''
Check for Scaleway configurations.
'''
if get_configured_provider() is False:
return False
return __virtualname__
def get_configured_provider():
''' Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('token',)
)
def avail_images(call=None):
''' Return a list of the images that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
items = query(method='images', root='marketplace_root')
ret = {}
for image in items['images']:
ret[image['id']] = {}
for item in image:
ret[image['id']][item] = six.text_type(image[item])
return ret
def list_nodes(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
items = query(method='servers')
ret = {}
for node in items['servers']:
public_ips = []
private_ips = []
image_id = ''
if node.get('public_ip'):
public_ips = [node['public_ip']['address']]
if node.get('private_ip'):
private_ips = [node['private_ip']]
if node.get('image'):
image_id = node['image']['id']
ret[node['name']] = {
'id': node['id'],
'image_id': image_id,
'public_ips': public_ips,
'private_ips': private_ips,
'size': node['volumes']['0']['size'],
'state': node['state'],
}
return ret
def list_nodes_full(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'list_nodes_full must be called with -f or --function'
)
items = query(method='servers')
# For each server, iterate on its parameters.
ret = {}
for node in items['servers']:
ret[node['name']] = {}
for item in node:
value = node[item]
ret[node['name']][item] = value
return ret
def list_nodes_select(call=None):
''' Return a list of the BareMetal servers that are on the provider, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def create_node(args):
''' Create a node.
'''
node = query(method='servers', args=args, http_method='POST')
action = query(
method='servers',
server_id=node['server']['id'],
command='action',
args={'action': 'poweron'},
http_method='POST'
)
return node
def create(server_):
'''
Create a single BareMetal server from a data dict.
'''
try:
# Check for required profile parameters before sending any API calls.
if server_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'scaleway',
server_['profile'],
vm_=server_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(server_['name']),
args=__utils__['cloud.filter_event']('creating', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating a BareMetal server %s', server_['name'])
access_key = config.get_cloud_config_value(
'access_key', get_configured_provider(), __opts__, search_global=False
)
commercial_type = config.get_cloud_config_value(
'commercial_type', server_, __opts__, default='C1'
)
key_filename = config.get_cloud_config_value(
'ssh_key_file', server_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
ssh_password = config.get_cloud_config_value(
'ssh_password', server_, __opts__
)
kwargs = {
'name': server_['name'],
'organization': access_key,
'image': get_image(server_),
'commercial_type': commercial_type,
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(server_['name']),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Scaleway\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
server_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(server_name):
''' Called to check if the server has a public IP address.
'''
data = show_instance(server_name, 'action')
if data and data.get('public_ip'):
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(server_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', server_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', server_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(server_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
server_['ssh_host'] = data['public_ip']['address']
server_['ssh_password'] = ssh_password
server_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](server_, __opts__)
ret.update(data)
log.info('Created BareMetal server \'%s\'', server_['name'])
log.debug(
'\'%s\' BareMetal server creation details:\n%s',
server_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(server_['name']),
args=__utils__['cloud.filter_event']('created', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='servers', server_id=None, command=None, args=None,
http_method='GET', root='api_root'):
''' Make a call to the Scaleway API.
'''
if root == 'api_root':
default_url = 'https://cp-par1.scaleway.com'
else:
default_url = 'https://api-marketplace.scaleway.com'
base_path = six.text_type(config.get_cloud_config_value(
root,
get_configured_provider(),
__opts__,
search_global=False,
default=default_url
))
path = '{0}/{1}/'.format(base_path, method)
if server_id:
path += '{0}/'.format(server_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
token = config.get_cloud_config_value(
'token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
request = __utils__["http.query"](path,
method=http_method,
data=data,
status=True,
decode=True,
decode_type='json',
data_render=True,
data_renderer='json',
headers=True,
header_dict={'X-Auth-Token': token,
'User-Agent': "salt-cloud",
'Content-Type': 'application/json'})
if request['status'] > 299:
raise SaltCloudSystemExit(
'An error occurred while querying Scaleway. HTTP Code: {0} '
'Error: \'{1}\''.format(
request['status'],
request['error']
)
)
# success without data
if request['status'] == 204:
return True
return salt.utils.json.loads(request['body'])
def script(server_):
''' Return the script deployment object.
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', server_, __opts__),
server_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, server_)
)
)
def show_instance(name, call=None):
''' Show the details from a Scaleway BareMetal server.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
for attempt in reversed(list(range(10))):
try:
return list_nodes_full()[name]
except KeyError:
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempt
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def destroy(name, call=None):
''' Destroy a node. Will check termination protection and warn if enabled.
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']
)
data = show_instance(name, call='action')
node = query(
method='servers', server_id=data['id'], command='action',
args={'action': 'terminate'}, http_method='POST'
)
__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 node
|
saltstack/salt | salt/cloud/clouds/scaleway.py | create_node | python | def create_node(args):
''' Create a node.
'''
node = query(method='servers', args=args, http_method='POST')
action = query(
method='servers',
server_id=node['server']['id'],
command='action',
args={'action': 'poweron'},
http_method='POST'
)
return node | Create a node. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/scaleway.py#L171-L183 | [
"def query(method='servers', server_id=None, command=None, args=None,\n http_method='GET', root='api_root'):\n ''' Make a call to the Scaleway API.\n '''\n\n if root == 'api_root':\n default_url = 'https://cp-par1.scaleway.com'\n else:\n default_url = 'https://api-marketplace.scaleway.com'\n\n base_path = six.text_type(config.get_cloud_config_value(\n root,\n get_configured_provider(),\n __opts__,\n search_global=False,\n default=default_url\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if server_id:\n path += '{0}/'.format(server_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n token = config.get_cloud_config_value(\n 'token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n request = __utils__[\"http.query\"](path,\n method=http_method,\n data=data,\n status=True,\n decode=True,\n decode_type='json',\n data_render=True,\n data_renderer='json',\n headers=True,\n header_dict={'X-Auth-Token': token,\n 'User-Agent': \"salt-cloud\",\n 'Content-Type': 'application/json'})\n if request['status'] > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying Scaleway. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request['status'],\n request['error']\n )\n )\n\n # success without data\n if request['status'] == 204:\n return True\n\n return salt.utils.json.loads(request['body'])\n"
] | # -*- coding: utf-8 -*-
'''
Scaleway Cloud Module
=====================
.. versionadded:: 2015.8.0
The Scaleway cloud module is used to interact with your Scaleway BareMetal
Servers.
Use of this module only requires the ``api_key`` parameter to be set. Set up
the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/scaleway.conf``:
.. code-block:: yaml
scaleway-config:
# Scaleway organization and token
access_key: 0e604a2c-aea6-4081-acb2-e1d1258ef95c
token: be8fd96b-04eb-4d39-b6ba-a9edbcf17f12
driver: scaleway
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pprint
import os
import time
# Import Salt Libs
from salt.ext import six
from salt.ext.six.moves import range
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
log = logging.getLogger(__name__)
__virtualname__ = 'scaleway'
# Only load in this module if the Scaleway configurations are in place
def __virtual__():
'''
Check for Scaleway configurations.
'''
if get_configured_provider() is False:
return False
return __virtualname__
def get_configured_provider():
''' Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('token',)
)
def avail_images(call=None):
''' Return a list of the images that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
items = query(method='images', root='marketplace_root')
ret = {}
for image in items['images']:
ret[image['id']] = {}
for item in image:
ret[image['id']][item] = six.text_type(image[item])
return ret
def list_nodes(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
items = query(method='servers')
ret = {}
for node in items['servers']:
public_ips = []
private_ips = []
image_id = ''
if node.get('public_ip'):
public_ips = [node['public_ip']['address']]
if node.get('private_ip'):
private_ips = [node['private_ip']]
if node.get('image'):
image_id = node['image']['id']
ret[node['name']] = {
'id': node['id'],
'image_id': image_id,
'public_ips': public_ips,
'private_ips': private_ips,
'size': node['volumes']['0']['size'],
'state': node['state'],
}
return ret
def list_nodes_full(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'list_nodes_full must be called with -f or --function'
)
items = query(method='servers')
# For each server, iterate on its parameters.
ret = {}
for node in items['servers']:
ret[node['name']] = {}
for item in node:
value = node[item]
ret[node['name']][item] = value
return ret
def list_nodes_select(call=None):
''' Return a list of the BareMetal servers that are on the provider, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(server_):
''' Return the image object to use.
'''
images = avail_images()
server_image = six.text_type(config.get_cloud_config_value(
'image', server_, __opts__, search_global=False
))
for image in images:
if server_image in (images[image]['name'], images[image]['id']):
return images[image]['id']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(server_image)
)
def create(server_):
'''
Create a single BareMetal server from a data dict.
'''
try:
# Check for required profile parameters before sending any API calls.
if server_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'scaleway',
server_['profile'],
vm_=server_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(server_['name']),
args=__utils__['cloud.filter_event']('creating', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating a BareMetal server %s', server_['name'])
access_key = config.get_cloud_config_value(
'access_key', get_configured_provider(), __opts__, search_global=False
)
commercial_type = config.get_cloud_config_value(
'commercial_type', server_, __opts__, default='C1'
)
key_filename = config.get_cloud_config_value(
'ssh_key_file', server_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
ssh_password = config.get_cloud_config_value(
'ssh_password', server_, __opts__
)
kwargs = {
'name': server_['name'],
'organization': access_key,
'image': get_image(server_),
'commercial_type': commercial_type,
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(server_['name']),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Scaleway\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
server_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(server_name):
''' Called to check if the server has a public IP address.
'''
data = show_instance(server_name, 'action')
if data and data.get('public_ip'):
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(server_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', server_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', server_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(server_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
server_['ssh_host'] = data['public_ip']['address']
server_['ssh_password'] = ssh_password
server_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](server_, __opts__)
ret.update(data)
log.info('Created BareMetal server \'%s\'', server_['name'])
log.debug(
'\'%s\' BareMetal server creation details:\n%s',
server_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(server_['name']),
args=__utils__['cloud.filter_event']('created', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='servers', server_id=None, command=None, args=None,
http_method='GET', root='api_root'):
''' Make a call to the Scaleway API.
'''
if root == 'api_root':
default_url = 'https://cp-par1.scaleway.com'
else:
default_url = 'https://api-marketplace.scaleway.com'
base_path = six.text_type(config.get_cloud_config_value(
root,
get_configured_provider(),
__opts__,
search_global=False,
default=default_url
))
path = '{0}/{1}/'.format(base_path, method)
if server_id:
path += '{0}/'.format(server_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
token = config.get_cloud_config_value(
'token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
request = __utils__["http.query"](path,
method=http_method,
data=data,
status=True,
decode=True,
decode_type='json',
data_render=True,
data_renderer='json',
headers=True,
header_dict={'X-Auth-Token': token,
'User-Agent': "salt-cloud",
'Content-Type': 'application/json'})
if request['status'] > 299:
raise SaltCloudSystemExit(
'An error occurred while querying Scaleway. HTTP Code: {0} '
'Error: \'{1}\''.format(
request['status'],
request['error']
)
)
# success without data
if request['status'] == 204:
return True
return salt.utils.json.loads(request['body'])
def script(server_):
''' Return the script deployment object.
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', server_, __opts__),
server_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, server_)
)
)
def show_instance(name, call=None):
''' Show the details from a Scaleway BareMetal server.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
for attempt in reversed(list(range(10))):
try:
return list_nodes_full()[name]
except KeyError:
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempt
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def destroy(name, call=None):
''' Destroy a node. Will check termination protection and warn if enabled.
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']
)
data = show_instance(name, call='action')
node = query(
method='servers', server_id=data['id'], command='action',
args={'action': 'terminate'}, http_method='POST'
)
__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 node
|
saltstack/salt | salt/cloud/clouds/scaleway.py | create | python | def create(server_):
'''
Create a single BareMetal server from a data dict.
'''
try:
# Check for required profile parameters before sending any API calls.
if server_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'scaleway',
server_['profile'],
vm_=server_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(server_['name']),
args=__utils__['cloud.filter_event']('creating', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating a BareMetal server %s', server_['name'])
access_key = config.get_cloud_config_value(
'access_key', get_configured_provider(), __opts__, search_global=False
)
commercial_type = config.get_cloud_config_value(
'commercial_type', server_, __opts__, default='C1'
)
key_filename = config.get_cloud_config_value(
'ssh_key_file', server_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
ssh_password = config.get_cloud_config_value(
'ssh_password', server_, __opts__
)
kwargs = {
'name': server_['name'],
'organization': access_key,
'image': get_image(server_),
'commercial_type': commercial_type,
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(server_['name']),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Scaleway\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
server_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(server_name):
''' Called to check if the server has a public IP address.
'''
data = show_instance(server_name, 'action')
if data and data.get('public_ip'):
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(server_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', server_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', server_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(server_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
server_['ssh_host'] = data['public_ip']['address']
server_['ssh_password'] = ssh_password
server_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](server_, __opts__)
ret.update(data)
log.info('Created BareMetal server \'%s\'', server_['name'])
log.debug(
'\'%s\' BareMetal server creation details:\n%s',
server_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(server_['name']),
args=__utils__['cloud.filter_event']('created', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret | Create a single BareMetal server from a data dict. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/scaleway.py#L186-L313 | [
"def destroy(name, call=None):\n ''' Destroy a node. Will check termination protection and warn if enabled.\n\n CLI Example:\n .. code-block:: bash\n\n salt-cloud --destroy mymachine\n '''\n if call == 'function':\n raise SaltCloudSystemExit(\n 'The destroy action must be called with -d, --destroy, '\n '-a or --action.'\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroying instance',\n 'salt/cloud/{0}/destroying'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n data = show_instance(name, call='action')\n node = query(\n method='servers', server_id=data['id'], command='action',\n args={'action': 'terminate'}, http_method='POST'\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroyed instance',\n 'salt/cloud/{0}/destroyed'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n if __opts__.get('update_cachedir', False) is True:\n __utils__['cloud.delete_minion_cachedir'](\n name, __active_provider_name__.split(':')[0], __opts__\n )\n\n return node\n",
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def is_profile_configured(opts, provider, profile_name, vm_=None):\n '''\n Check if the requested profile contains the minimum required parameters for\n a profile.\n\n Required parameters include image and provider for all drivers, while some\n drivers also require size keys.\n\n .. versionadded:: 2015.8.0\n '''\n # Standard dict keys required by all drivers.\n required_keys = ['provider']\n alias, driver = provider.split(':')\n\n # Most drivers need an image to be specified, but some do not.\n non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']\n\n # Most drivers need a size, but some do not.\n non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',\n 'softlayer', 'softlayer_hw', 'vmware', 'vsphere',\n 'virtualbox', 'libvirt', 'oneandone', 'profitbricks']\n\n provider_key = opts['providers'][alias][driver]\n profile_key = opts['providers'][alias][driver]['profiles'][profile_name]\n\n # If cloning on Linode, size and image are not necessary.\n # They are obtained from the to-be-cloned VM.\n if driver == 'linode' and profile_key.get('clonefrom', False):\n non_image_drivers.append('linode')\n non_size_drivers.append('linode')\n elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):\n non_image_drivers.append('gce')\n\n # If cloning on VMware, specifying image is not necessary.\n if driver == 'vmware' and 'image' not in list(profile_key.keys()):\n non_image_drivers.append('vmware')\n\n if driver not in non_image_drivers:\n required_keys.append('image')\n if driver == 'vmware':\n required_keys.append('datastore')\n elif driver in ['linode', 'virtualbox']:\n required_keys.append('clonefrom')\n elif driver == 'nova':\n nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']\n if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):\n required_keys.extend(nova_image_keys)\n\n if driver not in non_size_drivers:\n required_keys.append('size')\n\n # Check if required fields are supplied in the provider config. If they\n # are present, remove it from the required_keys list.\n for item in list(required_keys):\n if item in provider_key:\n required_keys.remove(item)\n\n # If a vm_ dict was passed in, use that information to get any other configs\n # that we might have missed thus far, such as a option provided in a map file.\n if vm_:\n for item in list(required_keys):\n if item in vm_:\n required_keys.remove(item)\n\n # Check for remaining required parameters in the profile config.\n for item in required_keys:\n if profile_key.get(item, None) is None:\n # There's at least one required configuration item which is not set.\n log.error(\n \"The required '%s' configuration setting is missing from \"\n \"the '%s' profile, which is configured under the '%s' alias.\",\n item, profile_name, alias\n )\n return False\n\n return True\n",
"def get_configured_provider():\n ''' Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__,\n __active_provider_name__ or __virtualname__,\n ('token',)\n )\n",
"def get_image(server_):\n ''' Return the image object to use.\n '''\n images = avail_images()\n server_image = six.text_type(config.get_cloud_config_value(\n 'image', server_, __opts__, search_global=False\n ))\n for image in images:\n if server_image in (images[image]['name'], images[image]['id']):\n return images[image]['id']\n raise SaltCloudNotFound(\n 'The specified image, \\'{0}\\', could not be found.'.format(server_image)\n )\n",
"def create_node(args):\n ''' Create a node.\n '''\n node = query(method='servers', args=args, http_method='POST')\n\n action = query(\n method='servers',\n server_id=node['server']['id'],\n command='action',\n args={'action': 'poweron'},\n http_method='POST'\n )\n return node\n",
"def wait_for_ip(update_callback,\n update_args=None,\n update_kwargs=None,\n timeout=5 * 60,\n interval=5,\n interval_multiplier=1,\n max_failures=10):\n '''\n Helper function that waits for an IP address for a specific maximum amount\n of time.\n\n :param update_callback: callback function which queries the cloud provider\n for the VM ip address. It must return None if the\n required data, IP included, is not available yet.\n :param update_args: Arguments to pass to update_callback\n :param update_kwargs: Keyword arguments to pass to update_callback\n :param timeout: The maximum amount of time(in seconds) to wait for the IP\n address.\n :param interval: The looping interval, i.e., the amount of time to sleep\n before the next iteration.\n :param interval_multiplier: Increase the interval by this multiplier after\n each request; helps with throttling\n :param max_failures: If update_callback returns ``False`` it's considered\n query failure. This value is the amount of failures\n accepted before giving up.\n :returns: The update_callback returned data\n :raises: SaltCloudExecutionTimeout\n\n '''\n if update_args is None:\n update_args = ()\n if update_kwargs is None:\n update_kwargs = {}\n\n duration = timeout\n while True:\n log.debug(\n 'Waiting for VM IP. Giving up in 00:%02d:%02d.',\n int(timeout // 60), int(timeout % 60)\n )\n data = update_callback(*update_args, **update_kwargs)\n if data is False:\n log.debug(\n '\\'update_callback\\' has returned \\'False\\', which is '\n 'considered a failure. Remaining Failures: %s.', max_failures\n )\n max_failures -= 1\n if max_failures <= 0:\n raise SaltCloudExecutionFailure(\n 'Too many failures occurred while waiting for '\n 'the IP address.'\n )\n elif data is not None:\n return data\n\n if timeout < 0:\n raise SaltCloudExecutionTimeout(\n 'Unable to get IP for 00:{0:02d}:{1:02d}.'.format(\n int(duration // 60),\n int(duration % 60)\n )\n )\n time.sleep(interval)\n timeout -= interval\n\n if interval_multiplier > 1:\n interval *= interval_multiplier\n if interval > timeout:\n interval = timeout + 1\n log.info('Interval multiplier in effect; interval is '\n 'now %ss.', interval)\n"
] | # -*- coding: utf-8 -*-
'''
Scaleway Cloud Module
=====================
.. versionadded:: 2015.8.0
The Scaleway cloud module is used to interact with your Scaleway BareMetal
Servers.
Use of this module only requires the ``api_key`` parameter to be set. Set up
the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/scaleway.conf``:
.. code-block:: yaml
scaleway-config:
# Scaleway organization and token
access_key: 0e604a2c-aea6-4081-acb2-e1d1258ef95c
token: be8fd96b-04eb-4d39-b6ba-a9edbcf17f12
driver: scaleway
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pprint
import os
import time
# Import Salt Libs
from salt.ext import six
from salt.ext.six.moves import range
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
log = logging.getLogger(__name__)
__virtualname__ = 'scaleway'
# Only load in this module if the Scaleway configurations are in place
def __virtual__():
'''
Check for Scaleway configurations.
'''
if get_configured_provider() is False:
return False
return __virtualname__
def get_configured_provider():
''' Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('token',)
)
def avail_images(call=None):
''' Return a list of the images that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
items = query(method='images', root='marketplace_root')
ret = {}
for image in items['images']:
ret[image['id']] = {}
for item in image:
ret[image['id']][item] = six.text_type(image[item])
return ret
def list_nodes(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
items = query(method='servers')
ret = {}
for node in items['servers']:
public_ips = []
private_ips = []
image_id = ''
if node.get('public_ip'):
public_ips = [node['public_ip']['address']]
if node.get('private_ip'):
private_ips = [node['private_ip']]
if node.get('image'):
image_id = node['image']['id']
ret[node['name']] = {
'id': node['id'],
'image_id': image_id,
'public_ips': public_ips,
'private_ips': private_ips,
'size': node['volumes']['0']['size'],
'state': node['state'],
}
return ret
def list_nodes_full(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'list_nodes_full must be called with -f or --function'
)
items = query(method='servers')
# For each server, iterate on its parameters.
ret = {}
for node in items['servers']:
ret[node['name']] = {}
for item in node:
value = node[item]
ret[node['name']][item] = value
return ret
def list_nodes_select(call=None):
''' Return a list of the BareMetal servers that are on the provider, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(server_):
''' Return the image object to use.
'''
images = avail_images()
server_image = six.text_type(config.get_cloud_config_value(
'image', server_, __opts__, search_global=False
))
for image in images:
if server_image in (images[image]['name'], images[image]['id']):
return images[image]['id']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(server_image)
)
def create_node(args):
''' Create a node.
'''
node = query(method='servers', args=args, http_method='POST')
action = query(
method='servers',
server_id=node['server']['id'],
command='action',
args={'action': 'poweron'},
http_method='POST'
)
return node
def query(method='servers', server_id=None, command=None, args=None,
http_method='GET', root='api_root'):
''' Make a call to the Scaleway API.
'''
if root == 'api_root':
default_url = 'https://cp-par1.scaleway.com'
else:
default_url = 'https://api-marketplace.scaleway.com'
base_path = six.text_type(config.get_cloud_config_value(
root,
get_configured_provider(),
__opts__,
search_global=False,
default=default_url
))
path = '{0}/{1}/'.format(base_path, method)
if server_id:
path += '{0}/'.format(server_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
token = config.get_cloud_config_value(
'token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
request = __utils__["http.query"](path,
method=http_method,
data=data,
status=True,
decode=True,
decode_type='json',
data_render=True,
data_renderer='json',
headers=True,
header_dict={'X-Auth-Token': token,
'User-Agent': "salt-cloud",
'Content-Type': 'application/json'})
if request['status'] > 299:
raise SaltCloudSystemExit(
'An error occurred while querying Scaleway. HTTP Code: {0} '
'Error: \'{1}\''.format(
request['status'],
request['error']
)
)
# success without data
if request['status'] == 204:
return True
return salt.utils.json.loads(request['body'])
def script(server_):
''' Return the script deployment object.
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', server_, __opts__),
server_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, server_)
)
)
def show_instance(name, call=None):
''' Show the details from a Scaleway BareMetal server.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
for attempt in reversed(list(range(10))):
try:
return list_nodes_full()[name]
except KeyError:
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempt
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def destroy(name, call=None):
''' Destroy a node. Will check termination protection and warn if enabled.
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']
)
data = show_instance(name, call='action')
node = query(
method='servers', server_id=data['id'], command='action',
args={'action': 'terminate'}, http_method='POST'
)
__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 node
|
saltstack/salt | salt/cloud/clouds/scaleway.py | query | python | def query(method='servers', server_id=None, command=None, args=None,
http_method='GET', root='api_root'):
''' Make a call to the Scaleway API.
'''
if root == 'api_root':
default_url = 'https://cp-par1.scaleway.com'
else:
default_url = 'https://api-marketplace.scaleway.com'
base_path = six.text_type(config.get_cloud_config_value(
root,
get_configured_provider(),
__opts__,
search_global=False,
default=default_url
))
path = '{0}/{1}/'.format(base_path, method)
if server_id:
path += '{0}/'.format(server_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
token = config.get_cloud_config_value(
'token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
request = __utils__["http.query"](path,
method=http_method,
data=data,
status=True,
decode=True,
decode_type='json',
data_render=True,
data_renderer='json',
headers=True,
header_dict={'X-Auth-Token': token,
'User-Agent': "salt-cloud",
'Content-Type': 'application/json'})
if request['status'] > 299:
raise SaltCloudSystemExit(
'An error occurred while querying Scaleway. HTTP Code: {0} '
'Error: \'{1}\''.format(
request['status'],
request['error']
)
)
# success without data
if request['status'] == 204:
return True
return salt.utils.json.loads(request['body']) | Make a call to the Scaleway API. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/scaleway.py#L316-L376 | [
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n",
"def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n",
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def get_configured_provider():\n ''' Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__,\n __active_provider_name__ or __virtualname__,\n ('token',)\n )\n"
] | # -*- coding: utf-8 -*-
'''
Scaleway Cloud Module
=====================
.. versionadded:: 2015.8.0
The Scaleway cloud module is used to interact with your Scaleway BareMetal
Servers.
Use of this module only requires the ``api_key`` parameter to be set. Set up
the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/scaleway.conf``:
.. code-block:: yaml
scaleway-config:
# Scaleway organization and token
access_key: 0e604a2c-aea6-4081-acb2-e1d1258ef95c
token: be8fd96b-04eb-4d39-b6ba-a9edbcf17f12
driver: scaleway
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pprint
import os
import time
# Import Salt Libs
from salt.ext import six
from salt.ext.six.moves import range
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
log = logging.getLogger(__name__)
__virtualname__ = 'scaleway'
# Only load in this module if the Scaleway configurations are in place
def __virtual__():
'''
Check for Scaleway configurations.
'''
if get_configured_provider() is False:
return False
return __virtualname__
def get_configured_provider():
''' Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('token',)
)
def avail_images(call=None):
''' Return a list of the images that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
items = query(method='images', root='marketplace_root')
ret = {}
for image in items['images']:
ret[image['id']] = {}
for item in image:
ret[image['id']][item] = six.text_type(image[item])
return ret
def list_nodes(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
items = query(method='servers')
ret = {}
for node in items['servers']:
public_ips = []
private_ips = []
image_id = ''
if node.get('public_ip'):
public_ips = [node['public_ip']['address']]
if node.get('private_ip'):
private_ips = [node['private_ip']]
if node.get('image'):
image_id = node['image']['id']
ret[node['name']] = {
'id': node['id'],
'image_id': image_id,
'public_ips': public_ips,
'private_ips': private_ips,
'size': node['volumes']['0']['size'],
'state': node['state'],
}
return ret
def list_nodes_full(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'list_nodes_full must be called with -f or --function'
)
items = query(method='servers')
# For each server, iterate on its parameters.
ret = {}
for node in items['servers']:
ret[node['name']] = {}
for item in node:
value = node[item]
ret[node['name']][item] = value
return ret
def list_nodes_select(call=None):
''' Return a list of the BareMetal servers that are on the provider, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(server_):
''' Return the image object to use.
'''
images = avail_images()
server_image = six.text_type(config.get_cloud_config_value(
'image', server_, __opts__, search_global=False
))
for image in images:
if server_image in (images[image]['name'], images[image]['id']):
return images[image]['id']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(server_image)
)
def create_node(args):
''' Create a node.
'''
node = query(method='servers', args=args, http_method='POST')
action = query(
method='servers',
server_id=node['server']['id'],
command='action',
args={'action': 'poweron'},
http_method='POST'
)
return node
def create(server_):
'''
Create a single BareMetal server from a data dict.
'''
try:
# Check for required profile parameters before sending any API calls.
if server_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'scaleway',
server_['profile'],
vm_=server_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(server_['name']),
args=__utils__['cloud.filter_event']('creating', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating a BareMetal server %s', server_['name'])
access_key = config.get_cloud_config_value(
'access_key', get_configured_provider(), __opts__, search_global=False
)
commercial_type = config.get_cloud_config_value(
'commercial_type', server_, __opts__, default='C1'
)
key_filename = config.get_cloud_config_value(
'ssh_key_file', server_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
ssh_password = config.get_cloud_config_value(
'ssh_password', server_, __opts__
)
kwargs = {
'name': server_['name'],
'organization': access_key,
'image': get_image(server_),
'commercial_type': commercial_type,
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(server_['name']),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Scaleway\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
server_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(server_name):
''' Called to check if the server has a public IP address.
'''
data = show_instance(server_name, 'action')
if data and data.get('public_ip'):
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(server_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', server_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', server_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(server_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
server_['ssh_host'] = data['public_ip']['address']
server_['ssh_password'] = ssh_password
server_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](server_, __opts__)
ret.update(data)
log.info('Created BareMetal server \'%s\'', server_['name'])
log.debug(
'\'%s\' BareMetal server creation details:\n%s',
server_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(server_['name']),
args=__utils__['cloud.filter_event']('created', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def script(server_):
''' Return the script deployment object.
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', server_, __opts__),
server_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, server_)
)
)
def show_instance(name, call=None):
''' Show the details from a Scaleway BareMetal server.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
for attempt in reversed(list(range(10))):
try:
return list_nodes_full()[name]
except KeyError:
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempt
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def destroy(name, call=None):
''' Destroy a node. Will check termination protection and warn if enabled.
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']
)
data = show_instance(name, call='action')
node = query(
method='servers', server_id=data['id'], command='action',
args={'action': 'terminate'}, http_method='POST'
)
__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 node
|
saltstack/salt | salt/cloud/clouds/scaleway.py | script | python | def script(server_):
''' Return the script deployment object.
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', server_, __opts__),
server_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, server_)
)
) | Return the script deployment object. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/scaleway.py#L379-L389 | [
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def minion_config(opts, vm_):\n '''\n Return a minion's configuration for the provided options and VM\n '''\n\n # Don't start with a copy of the default minion opts; they're not always\n # what we need. Some default options are Null, let's set a reasonable default\n minion = {\n 'master': 'salt',\n 'log_level': 'info',\n 'hash_type': 'sha256',\n }\n\n # Now, let's update it to our needs\n minion['id'] = vm_['name']\n master_finger = salt.config.get_cloud_config_value('master_finger', vm_, opts)\n if master_finger is not None:\n minion['master_finger'] = master_finger\n minion.update(\n # Get ANY defined minion settings, merging data, in the following order\n # 1. VM config\n # 2. Profile config\n # 3. Global configuration\n salt.config.get_cloud_config_value(\n 'minion', vm_, opts, default={}, search_global=True\n )\n )\n\n make_master = salt.config.get_cloud_config_value('make_master', vm_, opts)\n if 'master' not in minion and make_master is not True:\n raise SaltCloudConfigError(\n 'A master setting was not defined in the minion\\'s configuration.'\n )\n\n # Get ANY defined grains settings, merging data, in the following order\n # 1. VM config\n # 2. Profile config\n # 3. Global configuration\n minion.setdefault('grains', {}).update(\n salt.config.get_cloud_config_value(\n 'grains', vm_, opts, default={}, search_global=True\n )\n )\n return minion\n",
"def os_script(os_, vm_=None, opts=None, minion=''):\n '''\n Return the script as a string for the specific os\n '''\n if minion:\n minion = salt_config_to_yaml(minion)\n\n if os.path.isabs(os_):\n # The user provided an absolute path to the deploy script, let's use it\n return __render_script(os_, vm_, opts, minion)\n\n if os.path.isabs('{0}.sh'.format(os_)):\n # The user provided an absolute path to the deploy script, although no\n # extension was provided. Let's use it anyway.\n return __render_script('{0}.sh'.format(os_), vm_, opts, minion)\n\n for search_path in opts['deploy_scripts_search_path']:\n if os.path.isfile(os.path.join(search_path, os_)):\n return __render_script(\n os.path.join(search_path, os_), vm_, opts, minion\n )\n\n if os.path.isfile(os.path.join(search_path, '{0}.sh'.format(os_))):\n return __render_script(\n os.path.join(search_path, '{0}.sh'.format(os_)),\n vm_, opts, minion\n )\n # No deploy script was found, return an empty string\n return ''\n",
"def salt_config_to_yaml(configuration, line_break='\\n'):\n '''\n Return a salt configuration dictionary, master or minion, as a yaml dump\n '''\n return salt.utils.yaml.safe_dump(\n configuration,\n line_break=line_break,\n default_flow_style=False)\n"
] | # -*- coding: utf-8 -*-
'''
Scaleway Cloud Module
=====================
.. versionadded:: 2015.8.0
The Scaleway cloud module is used to interact with your Scaleway BareMetal
Servers.
Use of this module only requires the ``api_key`` parameter to be set. Set up
the cloud configuration at ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/scaleway.conf``:
.. code-block:: yaml
scaleway-config:
# Scaleway organization and token
access_key: 0e604a2c-aea6-4081-acb2-e1d1258ef95c
token: be8fd96b-04eb-4d39-b6ba-a9edbcf17f12
driver: scaleway
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pprint
import os
import time
# Import Salt Libs
from salt.ext import six
from salt.ext.six.moves import range
import salt.utils.cloud
import salt.utils.json
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
log = logging.getLogger(__name__)
__virtualname__ = 'scaleway'
# Only load in this module if the Scaleway configurations are in place
def __virtual__():
'''
Check for Scaleway configurations.
'''
if get_configured_provider() is False:
return False
return __virtualname__
def get_configured_provider():
''' Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('token',)
)
def avail_images(call=None):
''' Return a list of the images that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
items = query(method='images', root='marketplace_root')
ret = {}
for image in items['images']:
ret[image['id']] = {}
for item in image:
ret[image['id']][item] = six.text_type(image[item])
return ret
def list_nodes(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
items = query(method='servers')
ret = {}
for node in items['servers']:
public_ips = []
private_ips = []
image_id = ''
if node.get('public_ip'):
public_ips = [node['public_ip']['address']]
if node.get('private_ip'):
private_ips = [node['private_ip']]
if node.get('image'):
image_id = node['image']['id']
ret[node['name']] = {
'id': node['id'],
'image_id': image_id,
'public_ips': public_ips,
'private_ips': private_ips,
'size': node['volumes']['0']['size'],
'state': node['state'],
}
return ret
def list_nodes_full(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'list_nodes_full must be called with -f or --function'
)
items = query(method='servers')
# For each server, iterate on its parameters.
ret = {}
for node in items['servers']:
ret[node['name']] = {}
for item in node:
value = node[item]
ret[node['name']][item] = value
return ret
def list_nodes_select(call=None):
''' Return a list of the BareMetal servers that are on the provider, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(server_):
''' Return the image object to use.
'''
images = avail_images()
server_image = six.text_type(config.get_cloud_config_value(
'image', server_, __opts__, search_global=False
))
for image in images:
if server_image in (images[image]['name'], images[image]['id']):
return images[image]['id']
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(server_image)
)
def create_node(args):
''' Create a node.
'''
node = query(method='servers', args=args, http_method='POST')
action = query(
method='servers',
server_id=node['server']['id'],
command='action',
args={'action': 'poweron'},
http_method='POST'
)
return node
def create(server_):
'''
Create a single BareMetal server from a data dict.
'''
try:
# Check for required profile parameters before sending any API calls.
if server_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'scaleway',
server_['profile'],
vm_=server_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(server_['name']),
args=__utils__['cloud.filter_event']('creating', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating a BareMetal server %s', server_['name'])
access_key = config.get_cloud_config_value(
'access_key', get_configured_provider(), __opts__, search_global=False
)
commercial_type = config.get_cloud_config_value(
'commercial_type', server_, __opts__, default='C1'
)
key_filename = config.get_cloud_config_value(
'ssh_key_file', server_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
ssh_password = config.get_cloud_config_value(
'ssh_password', server_, __opts__
)
kwargs = {
'name': server_['name'],
'organization': access_key,
'image': get_image(server_),
'commercial_type': commercial_type,
}
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(server_['name']),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on Scaleway\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
server_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(server_name):
''' Called to check if the server has a public IP address.
'''
data = show_instance(server_name, 'action')
if data and data.get('public_ip'):
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(server_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', server_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', server_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(server_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
server_['ssh_host'] = data['public_ip']['address']
server_['ssh_password'] = ssh_password
server_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](server_, __opts__)
ret.update(data)
log.info('Created BareMetal server \'%s\'', server_['name'])
log.debug(
'\'%s\' BareMetal server creation details:\n%s',
server_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(server_['name']),
args=__utils__['cloud.filter_event']('created', server_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='servers', server_id=None, command=None, args=None,
http_method='GET', root='api_root'):
''' Make a call to the Scaleway API.
'''
if root == 'api_root':
default_url = 'https://cp-par1.scaleway.com'
else:
default_url = 'https://api-marketplace.scaleway.com'
base_path = six.text_type(config.get_cloud_config_value(
root,
get_configured_provider(),
__opts__,
search_global=False,
default=default_url
))
path = '{0}/{1}/'.format(base_path, method)
if server_id:
path += '{0}/'.format(server_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
token = config.get_cloud_config_value(
'token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
request = __utils__["http.query"](path,
method=http_method,
data=data,
status=True,
decode=True,
decode_type='json',
data_render=True,
data_renderer='json',
headers=True,
header_dict={'X-Auth-Token': token,
'User-Agent': "salt-cloud",
'Content-Type': 'application/json'})
if request['status'] > 299:
raise SaltCloudSystemExit(
'An error occurred while querying Scaleway. HTTP Code: {0} '
'Error: \'{1}\''.format(
request['status'],
request['error']
)
)
# success without data
if request['status'] == 204:
return True
return salt.utils.json.loads(request['body'])
def show_instance(name, call=None):
''' Show the details from a Scaleway BareMetal server.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
for attempt in reversed(list(range(10))):
try:
return list_nodes_full()[name]
except KeyError:
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempt
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def destroy(name, call=None):
''' Destroy a node. Will check termination protection and warn if enabled.
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']
)
data = show_instance(name, call='action')
node = query(
method='servers', server_id=data['id'], command='action',
args={'action': 'terminate'}, http_method='POST'
)
__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 node
|
saltstack/salt | salt/states/ssh_auth.py | present | python | def present(
name,
user,
enc='ssh-rsa',
comment='',
source='',
options=None,
config='.ssh/authorized_keys',
fingerprint_hash_type=None,
**kwargs):
'''
Verifies that the specified SSH key is present for the specified user
name
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment and enc
will be ignored.
.. note::
The source file must contain keys in the format ``<enc> <key>
<comment>``. If you have generated a keypair using PuTTYgen, then you
will need to do the following to retrieve an OpenSSH-compatible public
key.
1. In PuTTYgen, click ``Load``, and select the *private* key file (not
the public key), and click ``Open``.
2. Copy the public key from the box labeled ``Public key for pasting
into OpenSSH authorized_keys file``.
3. Paste it into a new file.
options
The options passed to the key, pass a list object
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if source == '':
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split(None, 1)
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split(None, 2)
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
if __opts__['test']:
ret['result'], ret['comment'] = _present_test(
user,
name,
enc,
comment,
options or [],
source,
config,
fingerprint_hash_type)
return ret
# Get only the path to the file without env referrences to check if exists
if source != '':
source_path = __salt__['cp.get_url'](
source,
None,
saltenv=__env__)
if source != '' and not source_path:
data = 'no key'
elif source != '' and source_path:
key = __salt__['cp.get_file_str'](
source,
saltenv=__env__)
filehasoptions = False
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(ssh\-|ecds).*')
key = key.rstrip().split('\n')
for keyline in key:
filehasoptions = sshre.match(keyline)
if not filehasoptions:
data = __salt__['ssh.set_auth_key_from_file'](
user,
source,
config=config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
else:
# Split keyline to get key and comment
keyline = keyline.split(' ')
key_type = keyline[0]
key_value = keyline[1]
key_comment = keyline[2] if len(keyline) > 2 else ''
data = __salt__['ssh.set_auth_key'](
user,
key_value,
enc=key_type,
comment=key_comment,
options=options or [],
config=config,
fingerprint_hash_type=fingerprint_hash_type)
else:
data = __salt__['ssh.set_auth_key'](
user,
name,
enc=enc,
comment=comment,
options=options or [],
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if data == 'replace':
ret['changes'][name] = 'Updated'
ret['comment'] = ('The authorized host key {0} for user {1} was '
'updated'.format(name, user))
return ret
elif data == 'no change':
ret['comment'] = ('The authorized host key {0} is already present '
'for user {1}'.format(name, user))
elif data == 'new':
ret['changes'][name] = 'New'
ret['comment'] = ('The authorized host key {0} for user {1} was added'
.format(name, user))
elif data == 'no key':
ret['result'] = False
ret['comment'] = ('Failed to add the ssh key. Source file {0} is '
'missing'.format(source))
elif data == 'fail':
ret['result'] = False
err = sys.modules[
__salt__['test.ping'].__module__
].__context__.pop('ssh_auth.error', None)
if err:
ret['comment'] = err
else:
ret['comment'] = ('Failed to add the ssh key. Is the home '
'directory available, and/or does the key file '
'exist?')
elif data == 'invalid' or data == 'Invalid public key':
ret['result'] = False
ret['comment'] = 'Invalid public ssh key, most likely has spaces or invalid syntax'
return ret | Verifies that the specified SSH key is present for the specified user
name
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment and enc
will be ignored.
.. note::
The source file must contain keys in the format ``<enc> <key>
<comment>``. If you have generated a keypair using PuTTYgen, then you
will need to do the following to retrieve an OpenSSH-compatible public
key.
1. In PuTTYgen, click ``Load``, and select the *private* key file (not
the public key), and click ``Open``.
2. Copy the public key from the box labeled ``Public key for pasting
into OpenSSH authorized_keys file``.
3. Paste it into a new file.
options
The options passed to the key, pass a list object
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ssh_auth.py#L215-L389 | [
"def _present_test(user, name, enc, comment, options, source, config, fingerprint_hash_type):\n '''\n Run checks for \"present\"\n '''\n result = None\n if source:\n keys = __salt__['ssh.check_key_file'](\n user,\n source,\n config,\n saltenv=__env__,\n fingerprint_hash_type=fingerprint_hash_type)\n if keys:\n comment = ''\n for key, status in six.iteritems(keys):\n if status == 'exists':\n continue\n comment += 'Set to {0}: {1}\\n'.format(status, key)\n if comment:\n return result, comment\n err = sys.modules[\n __salt__['test.ping'].__module__\n ].__context__.pop('ssh_auth.error', None)\n if err:\n return False, err\n else:\n return (\n True,\n 'All host keys in file {0} are already present'.format(source)\n )\n else:\n # check if this is of form {options} {enc} {key} {comment}\n sshre = re.compile(r'^(.*?)\\s?((?:ssh\\-|ecds)[\\w-]+\\s.+)$')\n fullkey = sshre.search(name)\n # if it is {key} [comment]\n if not fullkey:\n key_and_comment = name.split()\n name = key_and_comment[0]\n if len(key_and_comment) == 2:\n comment = key_and_comment[1]\n else:\n # if there are options, set them\n if fullkey.group(1):\n options = fullkey.group(1).split(',')\n # key is of format: {enc} {key} [comment]\n comps = fullkey.group(2).split()\n enc = comps[0]\n name = comps[1]\n if len(comps) == 3:\n comment = comps[2]\n\n check = __salt__['ssh.check_key'](\n user,\n name,\n enc,\n comment,\n options,\n config=config,\n fingerprint_hash_type=fingerprint_hash_type)\n if check == 'update':\n comment = (\n 'Key {0} for user {1} is set to be updated'\n ).format(name, user)\n elif check == 'add':\n comment = (\n 'Key {0} for user {1} is set to be added'\n ).format(name, user)\n elif check == 'exists':\n result = True\n comment = ('The authorized host key {0} is already present '\n 'for user {1}'.format(name, user))\n\n return result, comment\n"
] | # -*- coding: utf-8 -*-
'''
Control of entries in SSH authorized_key files
==============================================
The information stored in a user's SSH authorized key file can be easily
controlled via the ssh_auth state. Defaults can be set by the enc, options,
and comment keys. These defaults can be overridden by including them in the
name.
Since the YAML specification limits the length of simple keys to 1024
characters, and since SSH keys are often longer than that, you may have
to use a YAML 'explicit key', as demonstrated in the second example below.
.. code-block:: yaml
AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==:
ssh_auth.present:
- user: root
- enc: ssh-dss
? AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==...
:
ssh_auth.present:
- user: root
- enc: ssh-dss
thatch:
ssh_auth.present:
- user: root
- source: salt://ssh_keys/thatch.id_rsa.pub
- config: '%h/.ssh/authorized_keys'
sshkeys:
ssh_auth.present:
- user: root
- enc: ssh-rsa
- options:
- option1="value1"
- option2="value2 flag2"
- comment: myuser
- names:
- AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==
- ssh-dss AAAAB3NzaCL0sQ9fJ5bYTEyY== user@domain
- option3="value3" ssh-dss AAAAB3NzaC1kcQ9J5bYTEyY== other@testdomain
- AAAAB3NzaC1kcQ9fJFF435bYTEyY== newcomment
sshkeys:
ssh_auth.manage:
- user: root
- enc: ssh-rsa
- options:
- option1="value1"
- option2="value2 flag2"
- comment: myuser
- ssh_keys:
- AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==
- ssh-dss AAAAB3NzaCL0sQ9fJ5bYTEyY== user@domain
- option3="value3" ssh-dss AAAAB3NzaC1kcQ9J5bYTEyY== other@testdomain
- AAAAB3NzaC1kcQ9fJFF435bYTEyY== newcomment
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import re
import sys
# Import 3rd-party libs
from salt.ext import six
def _present_test(user, name, enc, comment, options, source, config, fingerprint_hash_type):
'''
Run checks for "present"
'''
result = None
if source:
keys = __salt__['ssh.check_key_file'](
user,
source,
config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
if keys:
comment = ''
for key, status in six.iteritems(keys):
if status == 'exists':
continue
comment += 'Set to {0}: {1}\n'.format(status, key)
if comment:
return result, comment
err = sys.modules[
__salt__['test.ping'].__module__
].__context__.pop('ssh_auth.error', None)
if err:
return False, err
else:
return (
True,
'All host keys in file {0} are already present'.format(source)
)
else:
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split()
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split()
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
check = __salt__['ssh.check_key'](
user,
name,
enc,
comment,
options,
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if check == 'update':
comment = (
'Key {0} for user {1} is set to be updated'
).format(name, user)
elif check == 'add':
comment = (
'Key {0} for user {1} is set to be added'
).format(name, user)
elif check == 'exists':
result = True
comment = ('The authorized host key {0} is already present '
'for user {1}'.format(name, user))
return result, comment
def _absent_test(user, name, enc, comment, options, source, config, fingerprint_hash_type):
'''
Run checks for "absent"
'''
result = None
if source:
keys = __salt__['ssh.check_key_file'](
user,
source,
config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
if keys:
comment = ''
for key, status in list(keys.items()):
if status == 'add':
continue
comment += 'Set to remove: {0}\n'.format(key)
if comment:
return result, comment
err = sys.modules[
__salt__['test.ping'].__module__
].__context__.pop('ssh_auth.error', None)
if err:
return False, err
else:
return (
True,
'All host keys in file {0} are already absent'.format(source)
)
else:
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split()
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split()
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
check = __salt__['ssh.check_key'](
user,
name,
enc,
comment,
options,
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if check == 'update' or check == 'exists':
comment = ('Key {0} for user {1} is set for removal').format(name, user)
else:
comment = ('Key is already absent')
result = True
return result, comment
def absent(name,
user,
enc='ssh-rsa',
comment='',
source='',
options=None,
config='.ssh/authorized_keys',
fingerprint_hash_type=None):
'''
Verifies that the specified SSH key is absent
name
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
options
The options passed to the key, pass a list object
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment, enc and
options will be ignored.
.. versionadded:: 2015.8.0
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified.
.. versionadded:: 2016.11.7
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if __opts__['test']:
ret['result'], ret['comment'] = _absent_test(
user,
name,
enc,
comment,
options or [],
source,
config,
fingerprint_hash_type)
return ret
# Extract Key from file if source is present
if source != '':
key = __salt__['cp.get_file_str'](
source,
saltenv=__env__)
filehasoptions = False
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(ssh\-|ecds).*')
key = key.rstrip().split('\n')
for keyline in key:
filehasoptions = sshre.match(keyline)
if not filehasoptions:
ret['comment'] = __salt__['ssh.rm_auth_key_from_file'](user,
source,
config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
else:
# Split keyline to get key
keyline = keyline.split(' ')
ret['comment'] = __salt__['ssh.rm_auth_key'](user,
keyline[1],
config=config,
fingerprint_hash_type=fingerprint_hash_type)
else:
# Get just the key
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split(None, 1)
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split()
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
ret['comment'] = __salt__['ssh.rm_auth_key'](user,
name,
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if ret['comment'] == 'User authorized keys file not present':
ret['result'] = False
return ret
elif ret['comment'] == 'Key removed':
ret['changes'][name] = 'Removed'
return ret
def manage(
name,
ssh_keys,
user,
enc='ssh-rsa',
comment='',
source='',
options=None,
config='.ssh/authorized_keys',
fingerprint_hash_type=None,
**kwargs):
'''
.. versionadded:: Neon
Ensures that only the specified ssh_keys are present for the specified user
ssh_keys
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment and enc
will be ignored.
.. note::
The source file must contain keys in the format ``<enc> <key>
<comment>``. If you have generated a keypair using PuTTYgen, then you
will need to do the following to retrieve an OpenSSH-compatible public
key.
1. In PuTTYgen, click ``Load``, and select the *private* key file (not
the public key), and click ``Open``.
2. Copy the public key from the box labeled ``Public key for pasting
into OpenSSH authorized_keys file``.
3. Paste it into a new file.
options
The options passed to the keys, pass a list object
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified.
'''
ret = {'name': '',
'changes': {},
'result': True,
'comment': ''}
all_potential_keys = []
for ssh_key in ssh_keys:
# gather list potential ssh keys for removal comparison
# options, enc, and comments could be in the mix
all_potential_keys.extend(ssh_key.split(' '))
existing_keys = __salt__['ssh.auth_keys'](user=user).keys()
remove_keys = set(existing_keys).difference(all_potential_keys)
for remove_key in remove_keys:
if __opts__['test']:
remove_comment = '{0} Key set for removal'.format(remove_key)
ret['comment'] = remove_comment
ret['result'] = None
else:
remove_comment = absent(remove_key, user)['comment']
ret['changes'][remove_key] = remove_comment
for ssh_key in ssh_keys:
run_return = present(ssh_key, user, enc, comment, source,
options, config, fingerprint_hash_type, **kwargs)
if run_return['changes']:
ret['changes'].update(run_return['changes'])
else:
ret['comment'] += '\n' + run_return['comment']
ret['comment'].strip()
if run_return['result'] is None:
ret['result'] = None
elif not run_return['result']:
ret['result'] = False
return ret
|
saltstack/salt | salt/states/ssh_auth.py | absent | python | def absent(name,
user,
enc='ssh-rsa',
comment='',
source='',
options=None,
config='.ssh/authorized_keys',
fingerprint_hash_type=None):
'''
Verifies that the specified SSH key is absent
name
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
options
The options passed to the key, pass a list object
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment, enc and
options will be ignored.
.. versionadded:: 2015.8.0
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified.
.. versionadded:: 2016.11.7
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if __opts__['test']:
ret['result'], ret['comment'] = _absent_test(
user,
name,
enc,
comment,
options or [],
source,
config,
fingerprint_hash_type)
return ret
# Extract Key from file if source is present
if source != '':
key = __salt__['cp.get_file_str'](
source,
saltenv=__env__)
filehasoptions = False
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(ssh\-|ecds).*')
key = key.rstrip().split('\n')
for keyline in key:
filehasoptions = sshre.match(keyline)
if not filehasoptions:
ret['comment'] = __salt__['ssh.rm_auth_key_from_file'](user,
source,
config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
else:
# Split keyline to get key
keyline = keyline.split(' ')
ret['comment'] = __salt__['ssh.rm_auth_key'](user,
keyline[1],
config=config,
fingerprint_hash_type=fingerprint_hash_type)
else:
# Get just the key
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split(None, 1)
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split()
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
ret['comment'] = __salt__['ssh.rm_auth_key'](user,
name,
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if ret['comment'] == 'User authorized keys file not present':
ret['result'] = False
return ret
elif ret['comment'] == 'Key removed':
ret['changes'][name] = 'Removed'
return ret | Verifies that the specified SSH key is absent
name
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
options
The options passed to the key, pass a list object
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment, enc and
options will be ignored.
.. versionadded:: 2015.8.0
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified.
.. versionadded:: 2016.11.7 | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ssh_auth.py#L392-L509 | [
"def _absent_test(user, name, enc, comment, options, source, config, fingerprint_hash_type):\n '''\n Run checks for \"absent\"\n '''\n result = None\n if source:\n keys = __salt__['ssh.check_key_file'](\n user,\n source,\n config,\n saltenv=__env__,\n fingerprint_hash_type=fingerprint_hash_type)\n if keys:\n comment = ''\n for key, status in list(keys.items()):\n if status == 'add':\n continue\n comment += 'Set to remove: {0}\\n'.format(key)\n if comment:\n return result, comment\n err = sys.modules[\n __salt__['test.ping'].__module__\n ].__context__.pop('ssh_auth.error', None)\n if err:\n return False, err\n else:\n return (\n True,\n 'All host keys in file {0} are already absent'.format(source)\n )\n else:\n # check if this is of form {options} {enc} {key} {comment}\n sshre = re.compile(r'^(.*?)\\s?((?:ssh\\-|ecds)[\\w-]+\\s.+)$')\n fullkey = sshre.search(name)\n # if it is {key} [comment]\n if not fullkey:\n key_and_comment = name.split()\n name = key_and_comment[0]\n if len(key_and_comment) == 2:\n comment = key_and_comment[1]\n else:\n # if there are options, set them\n if fullkey.group(1):\n options = fullkey.group(1).split(',')\n # key is of format: {enc} {key} [comment]\n comps = fullkey.group(2).split()\n enc = comps[0]\n name = comps[1]\n if len(comps) == 3:\n comment = comps[2]\n\n check = __salt__['ssh.check_key'](\n user,\n name,\n enc,\n comment,\n options,\n config=config,\n fingerprint_hash_type=fingerprint_hash_type)\n if check == 'update' or check == 'exists':\n comment = ('Key {0} for user {1} is set for removal').format(name, user)\n else:\n comment = ('Key is already absent')\n result = True\n\n return result, comment\n"
] | # -*- coding: utf-8 -*-
'''
Control of entries in SSH authorized_key files
==============================================
The information stored in a user's SSH authorized key file can be easily
controlled via the ssh_auth state. Defaults can be set by the enc, options,
and comment keys. These defaults can be overridden by including them in the
name.
Since the YAML specification limits the length of simple keys to 1024
characters, and since SSH keys are often longer than that, you may have
to use a YAML 'explicit key', as demonstrated in the second example below.
.. code-block:: yaml
AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==:
ssh_auth.present:
- user: root
- enc: ssh-dss
? AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==...
:
ssh_auth.present:
- user: root
- enc: ssh-dss
thatch:
ssh_auth.present:
- user: root
- source: salt://ssh_keys/thatch.id_rsa.pub
- config: '%h/.ssh/authorized_keys'
sshkeys:
ssh_auth.present:
- user: root
- enc: ssh-rsa
- options:
- option1="value1"
- option2="value2 flag2"
- comment: myuser
- names:
- AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==
- ssh-dss AAAAB3NzaCL0sQ9fJ5bYTEyY== user@domain
- option3="value3" ssh-dss AAAAB3NzaC1kcQ9J5bYTEyY== other@testdomain
- AAAAB3NzaC1kcQ9fJFF435bYTEyY== newcomment
sshkeys:
ssh_auth.manage:
- user: root
- enc: ssh-rsa
- options:
- option1="value1"
- option2="value2 flag2"
- comment: myuser
- ssh_keys:
- AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==
- ssh-dss AAAAB3NzaCL0sQ9fJ5bYTEyY== user@domain
- option3="value3" ssh-dss AAAAB3NzaC1kcQ9J5bYTEyY== other@testdomain
- AAAAB3NzaC1kcQ9fJFF435bYTEyY== newcomment
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import re
import sys
# Import 3rd-party libs
from salt.ext import six
def _present_test(user, name, enc, comment, options, source, config, fingerprint_hash_type):
'''
Run checks for "present"
'''
result = None
if source:
keys = __salt__['ssh.check_key_file'](
user,
source,
config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
if keys:
comment = ''
for key, status in six.iteritems(keys):
if status == 'exists':
continue
comment += 'Set to {0}: {1}\n'.format(status, key)
if comment:
return result, comment
err = sys.modules[
__salt__['test.ping'].__module__
].__context__.pop('ssh_auth.error', None)
if err:
return False, err
else:
return (
True,
'All host keys in file {0} are already present'.format(source)
)
else:
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split()
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split()
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
check = __salt__['ssh.check_key'](
user,
name,
enc,
comment,
options,
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if check == 'update':
comment = (
'Key {0} for user {1} is set to be updated'
).format(name, user)
elif check == 'add':
comment = (
'Key {0} for user {1} is set to be added'
).format(name, user)
elif check == 'exists':
result = True
comment = ('The authorized host key {0} is already present '
'for user {1}'.format(name, user))
return result, comment
def _absent_test(user, name, enc, comment, options, source, config, fingerprint_hash_type):
'''
Run checks for "absent"
'''
result = None
if source:
keys = __salt__['ssh.check_key_file'](
user,
source,
config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
if keys:
comment = ''
for key, status in list(keys.items()):
if status == 'add':
continue
comment += 'Set to remove: {0}\n'.format(key)
if comment:
return result, comment
err = sys.modules[
__salt__['test.ping'].__module__
].__context__.pop('ssh_auth.error', None)
if err:
return False, err
else:
return (
True,
'All host keys in file {0} are already absent'.format(source)
)
else:
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split()
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split()
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
check = __salt__['ssh.check_key'](
user,
name,
enc,
comment,
options,
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if check == 'update' or check == 'exists':
comment = ('Key {0} for user {1} is set for removal').format(name, user)
else:
comment = ('Key is already absent')
result = True
return result, comment
def present(
name,
user,
enc='ssh-rsa',
comment='',
source='',
options=None,
config='.ssh/authorized_keys',
fingerprint_hash_type=None,
**kwargs):
'''
Verifies that the specified SSH key is present for the specified user
name
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment and enc
will be ignored.
.. note::
The source file must contain keys in the format ``<enc> <key>
<comment>``. If you have generated a keypair using PuTTYgen, then you
will need to do the following to retrieve an OpenSSH-compatible public
key.
1. In PuTTYgen, click ``Load``, and select the *private* key file (not
the public key), and click ``Open``.
2. Copy the public key from the box labeled ``Public key for pasting
into OpenSSH authorized_keys file``.
3. Paste it into a new file.
options
The options passed to the key, pass a list object
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if source == '':
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split(None, 1)
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split(None, 2)
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
if __opts__['test']:
ret['result'], ret['comment'] = _present_test(
user,
name,
enc,
comment,
options or [],
source,
config,
fingerprint_hash_type)
return ret
# Get only the path to the file without env referrences to check if exists
if source != '':
source_path = __salt__['cp.get_url'](
source,
None,
saltenv=__env__)
if source != '' and not source_path:
data = 'no key'
elif source != '' and source_path:
key = __salt__['cp.get_file_str'](
source,
saltenv=__env__)
filehasoptions = False
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(ssh\-|ecds).*')
key = key.rstrip().split('\n')
for keyline in key:
filehasoptions = sshre.match(keyline)
if not filehasoptions:
data = __salt__['ssh.set_auth_key_from_file'](
user,
source,
config=config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
else:
# Split keyline to get key and comment
keyline = keyline.split(' ')
key_type = keyline[0]
key_value = keyline[1]
key_comment = keyline[2] if len(keyline) > 2 else ''
data = __salt__['ssh.set_auth_key'](
user,
key_value,
enc=key_type,
comment=key_comment,
options=options or [],
config=config,
fingerprint_hash_type=fingerprint_hash_type)
else:
data = __salt__['ssh.set_auth_key'](
user,
name,
enc=enc,
comment=comment,
options=options or [],
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if data == 'replace':
ret['changes'][name] = 'Updated'
ret['comment'] = ('The authorized host key {0} for user {1} was '
'updated'.format(name, user))
return ret
elif data == 'no change':
ret['comment'] = ('The authorized host key {0} is already present '
'for user {1}'.format(name, user))
elif data == 'new':
ret['changes'][name] = 'New'
ret['comment'] = ('The authorized host key {0} for user {1} was added'
.format(name, user))
elif data == 'no key':
ret['result'] = False
ret['comment'] = ('Failed to add the ssh key. Source file {0} is '
'missing'.format(source))
elif data == 'fail':
ret['result'] = False
err = sys.modules[
__salt__['test.ping'].__module__
].__context__.pop('ssh_auth.error', None)
if err:
ret['comment'] = err
else:
ret['comment'] = ('Failed to add the ssh key. Is the home '
'directory available, and/or does the key file '
'exist?')
elif data == 'invalid' or data == 'Invalid public key':
ret['result'] = False
ret['comment'] = 'Invalid public ssh key, most likely has spaces or invalid syntax'
return ret
def manage(
name,
ssh_keys,
user,
enc='ssh-rsa',
comment='',
source='',
options=None,
config='.ssh/authorized_keys',
fingerprint_hash_type=None,
**kwargs):
'''
.. versionadded:: Neon
Ensures that only the specified ssh_keys are present for the specified user
ssh_keys
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment and enc
will be ignored.
.. note::
The source file must contain keys in the format ``<enc> <key>
<comment>``. If you have generated a keypair using PuTTYgen, then you
will need to do the following to retrieve an OpenSSH-compatible public
key.
1. In PuTTYgen, click ``Load``, and select the *private* key file (not
the public key), and click ``Open``.
2. Copy the public key from the box labeled ``Public key for pasting
into OpenSSH authorized_keys file``.
3. Paste it into a new file.
options
The options passed to the keys, pass a list object
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified.
'''
ret = {'name': '',
'changes': {},
'result': True,
'comment': ''}
all_potential_keys = []
for ssh_key in ssh_keys:
# gather list potential ssh keys for removal comparison
# options, enc, and comments could be in the mix
all_potential_keys.extend(ssh_key.split(' '))
existing_keys = __salt__['ssh.auth_keys'](user=user).keys()
remove_keys = set(existing_keys).difference(all_potential_keys)
for remove_key in remove_keys:
if __opts__['test']:
remove_comment = '{0} Key set for removal'.format(remove_key)
ret['comment'] = remove_comment
ret['result'] = None
else:
remove_comment = absent(remove_key, user)['comment']
ret['changes'][remove_key] = remove_comment
for ssh_key in ssh_keys:
run_return = present(ssh_key, user, enc, comment, source,
options, config, fingerprint_hash_type, **kwargs)
if run_return['changes']:
ret['changes'].update(run_return['changes'])
else:
ret['comment'] += '\n' + run_return['comment']
ret['comment'].strip()
if run_return['result'] is None:
ret['result'] = None
elif not run_return['result']:
ret['result'] = False
return ret
|
saltstack/salt | salt/states/ssh_auth.py | manage | python | def manage(
name,
ssh_keys,
user,
enc='ssh-rsa',
comment='',
source='',
options=None,
config='.ssh/authorized_keys',
fingerprint_hash_type=None,
**kwargs):
'''
.. versionadded:: Neon
Ensures that only the specified ssh_keys are present for the specified user
ssh_keys
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment and enc
will be ignored.
.. note::
The source file must contain keys in the format ``<enc> <key>
<comment>``. If you have generated a keypair using PuTTYgen, then you
will need to do the following to retrieve an OpenSSH-compatible public
key.
1. In PuTTYgen, click ``Load``, and select the *private* key file (not
the public key), and click ``Open``.
2. Copy the public key from the box labeled ``Public key for pasting
into OpenSSH authorized_keys file``.
3. Paste it into a new file.
options
The options passed to the keys, pass a list object
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified.
'''
ret = {'name': '',
'changes': {},
'result': True,
'comment': ''}
all_potential_keys = []
for ssh_key in ssh_keys:
# gather list potential ssh keys for removal comparison
# options, enc, and comments could be in the mix
all_potential_keys.extend(ssh_key.split(' '))
existing_keys = __salt__['ssh.auth_keys'](user=user).keys()
remove_keys = set(existing_keys).difference(all_potential_keys)
for remove_key in remove_keys:
if __opts__['test']:
remove_comment = '{0} Key set for removal'.format(remove_key)
ret['comment'] = remove_comment
ret['result'] = None
else:
remove_comment = absent(remove_key, user)['comment']
ret['changes'][remove_key] = remove_comment
for ssh_key in ssh_keys:
run_return = present(ssh_key, user, enc, comment, source,
options, config, fingerprint_hash_type, **kwargs)
if run_return['changes']:
ret['changes'].update(run_return['changes'])
else:
ret['comment'] += '\n' + run_return['comment']
ret['comment'].strip()
if run_return['result'] is None:
ret['result'] = None
elif not run_return['result']:
ret['result'] = False
return ret | .. versionadded:: Neon
Ensures that only the specified ssh_keys are present for the specified user
ssh_keys
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment and enc
will be ignored.
.. note::
The source file must contain keys in the format ``<enc> <key>
<comment>``. If you have generated a keypair using PuTTYgen, then you
will need to do the following to retrieve an OpenSSH-compatible public
key.
1. In PuTTYgen, click ``Load``, and select the *private* key file (not
the public key), and click ``Open``.
2. Copy the public key from the box labeled ``Public key for pasting
into OpenSSH authorized_keys file``.
3. Paste it into a new file.
options
The options passed to the keys, pass a list object
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ssh_auth.py#L512-L605 | [
"def present(\n name,\n user,\n enc='ssh-rsa',\n comment='',\n source='',\n options=None,\n config='.ssh/authorized_keys',\n fingerprint_hash_type=None,\n **kwargs):\n '''\n Verifies that the specified SSH key is present for the specified user\n\n name\n The SSH key to manage\n\n user\n The user who owns the SSH authorized keys file to modify\n\n enc\n Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa\n or ssh-dss\n\n comment\n The comment to be placed with the SSH public key\n\n source\n The source file for the key(s). Can contain any number of public keys,\n in standard \"authorized_keys\" format. If this is set, comment and enc\n will be ignored.\n\n .. note::\n The source file must contain keys in the format ``<enc> <key>\n <comment>``. If you have generated a keypair using PuTTYgen, then you\n will need to do the following to retrieve an OpenSSH-compatible public\n key.\n\n 1. In PuTTYgen, click ``Load``, and select the *private* key file (not\n the public key), and click ``Open``.\n 2. Copy the public key from the box labeled ``Public key for pasting\n into OpenSSH authorized_keys file``.\n 3. Paste it into a new file.\n\n options\n The options passed to the key, pass a list object\n\n config\n The location of the authorized keys file relative to the user's home\n directory, defaults to \".ssh/authorized_keys\". Token expansion %u and\n %h for username and home path supported.\n\n fingerprint_hash_type\n The public key fingerprint hash type that the public key fingerprint\n was originally hashed with. This defaults to ``sha256`` if not specified.\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': True,\n 'comment': ''}\n\n if source == '':\n # check if this is of form {options} {enc} {key} {comment}\n sshre = re.compile(r'^(.*?)\\s?((?:ssh\\-|ecds)[\\w-]+\\s.+)$')\n fullkey = sshre.search(name)\n # if it is {key} [comment]\n if not fullkey:\n key_and_comment = name.split(None, 1)\n name = key_and_comment[0]\n if len(key_and_comment) == 2:\n comment = key_and_comment[1]\n else:\n # if there are options, set them\n if fullkey.group(1):\n options = fullkey.group(1).split(',')\n # key is of format: {enc} {key} [comment]\n comps = fullkey.group(2).split(None, 2)\n enc = comps[0]\n name = comps[1]\n if len(comps) == 3:\n comment = comps[2]\n\n if __opts__['test']:\n ret['result'], ret['comment'] = _present_test(\n user,\n name,\n enc,\n comment,\n options or [],\n source,\n config,\n fingerprint_hash_type)\n return ret\n\n # Get only the path to the file without env referrences to check if exists\n if source != '':\n source_path = __salt__['cp.get_url'](\n source,\n None,\n saltenv=__env__)\n\n if source != '' and not source_path:\n data = 'no key'\n elif source != '' and source_path:\n key = __salt__['cp.get_file_str'](\n source,\n saltenv=__env__)\n filehasoptions = False\n # check if this is of form {options} {enc} {key} {comment}\n sshre = re.compile(r'^(ssh\\-|ecds).*')\n key = key.rstrip().split('\\n')\n for keyline in key:\n filehasoptions = sshre.match(keyline)\n if not filehasoptions:\n data = __salt__['ssh.set_auth_key_from_file'](\n user,\n source,\n config=config,\n saltenv=__env__,\n fingerprint_hash_type=fingerprint_hash_type)\n else:\n # Split keyline to get key and comment\n keyline = keyline.split(' ')\n key_type = keyline[0]\n key_value = keyline[1]\n key_comment = keyline[2] if len(keyline) > 2 else ''\n data = __salt__['ssh.set_auth_key'](\n user,\n key_value,\n enc=key_type,\n comment=key_comment,\n options=options or [],\n config=config,\n fingerprint_hash_type=fingerprint_hash_type)\n else:\n data = __salt__['ssh.set_auth_key'](\n user,\n name,\n enc=enc,\n comment=comment,\n options=options or [],\n config=config,\n fingerprint_hash_type=fingerprint_hash_type)\n\n if data == 'replace':\n ret['changes'][name] = 'Updated'\n ret['comment'] = ('The authorized host key {0} for user {1} was '\n 'updated'.format(name, user))\n return ret\n elif data == 'no change':\n ret['comment'] = ('The authorized host key {0} is already present '\n 'for user {1}'.format(name, user))\n elif data == 'new':\n ret['changes'][name] = 'New'\n ret['comment'] = ('The authorized host key {0} for user {1} was added'\n .format(name, user))\n elif data == 'no key':\n ret['result'] = False\n ret['comment'] = ('Failed to add the ssh key. Source file {0} is '\n 'missing'.format(source))\n elif data == 'fail':\n ret['result'] = False\n err = sys.modules[\n __salt__['test.ping'].__module__\n ].__context__.pop('ssh_auth.error', None)\n if err:\n ret['comment'] = err\n else:\n ret['comment'] = ('Failed to add the ssh key. Is the home '\n 'directory available, and/or does the key file '\n 'exist?')\n elif data == 'invalid' or data == 'Invalid public key':\n ret['result'] = False\n ret['comment'] = 'Invalid public ssh key, most likely has spaces or invalid syntax'\n\n return ret\n",
"def absent(name,\n user,\n enc='ssh-rsa',\n comment='',\n source='',\n options=None,\n config='.ssh/authorized_keys',\n fingerprint_hash_type=None):\n '''\n Verifies that the specified SSH key is absent\n\n name\n The SSH key to manage\n\n user\n The user who owns the SSH authorized keys file to modify\n\n enc\n Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa\n or ssh-dss\n\n comment\n The comment to be placed with the SSH public key\n\n options\n The options passed to the key, pass a list object\n\n source\n The source file for the key(s). Can contain any number of public keys,\n in standard \"authorized_keys\" format. If this is set, comment, enc and\n options will be ignored.\n\n .. versionadded:: 2015.8.0\n\n config\n The location of the authorized keys file relative to the user's home\n directory, defaults to \".ssh/authorized_keys\". Token expansion %u and\n %h for username and home path supported.\n\n fingerprint_hash_type\n The public key fingerprint hash type that the public key fingerprint\n was originally hashed with. This defaults to ``sha256`` if not specified.\n\n .. versionadded:: 2016.11.7\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': True,\n 'comment': ''}\n\n if __opts__['test']:\n ret['result'], ret['comment'] = _absent_test(\n user,\n name,\n enc,\n comment,\n options or [],\n source,\n config,\n fingerprint_hash_type)\n return ret\n\n # Extract Key from file if source is present\n if source != '':\n key = __salt__['cp.get_file_str'](\n source,\n saltenv=__env__)\n filehasoptions = False\n # check if this is of form {options} {enc} {key} {comment}\n sshre = re.compile(r'^(ssh\\-|ecds).*')\n key = key.rstrip().split('\\n')\n for keyline in key:\n filehasoptions = sshre.match(keyline)\n if not filehasoptions:\n ret['comment'] = __salt__['ssh.rm_auth_key_from_file'](user,\n source,\n config,\n saltenv=__env__,\n fingerprint_hash_type=fingerprint_hash_type)\n else:\n # Split keyline to get key\n keyline = keyline.split(' ')\n ret['comment'] = __salt__['ssh.rm_auth_key'](user,\n keyline[1],\n config=config,\n fingerprint_hash_type=fingerprint_hash_type)\n else:\n # Get just the key\n sshre = re.compile(r'^(.*?)\\s?((?:ssh\\-|ecds)[\\w-]+\\s.+)$')\n fullkey = sshre.search(name)\n # if it is {key} [comment]\n if not fullkey:\n key_and_comment = name.split(None, 1)\n name = key_and_comment[0]\n if len(key_and_comment) == 2:\n comment = key_and_comment[1]\n else:\n # if there are options, set them\n if fullkey.group(1):\n options = fullkey.group(1).split(',')\n # key is of format: {enc} {key} [comment]\n comps = fullkey.group(2).split()\n enc = comps[0]\n name = comps[1]\n if len(comps) == 3:\n comment = comps[2]\n ret['comment'] = __salt__['ssh.rm_auth_key'](user,\n name,\n config=config,\n fingerprint_hash_type=fingerprint_hash_type)\n\n if ret['comment'] == 'User authorized keys file not present':\n ret['result'] = False\n return ret\n elif ret['comment'] == 'Key removed':\n ret['changes'][name] = 'Removed'\n\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
Control of entries in SSH authorized_key files
==============================================
The information stored in a user's SSH authorized key file can be easily
controlled via the ssh_auth state. Defaults can be set by the enc, options,
and comment keys. These defaults can be overridden by including them in the
name.
Since the YAML specification limits the length of simple keys to 1024
characters, and since SSH keys are often longer than that, you may have
to use a YAML 'explicit key', as demonstrated in the second example below.
.. code-block:: yaml
AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==:
ssh_auth.present:
- user: root
- enc: ssh-dss
? AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==...
:
ssh_auth.present:
- user: root
- enc: ssh-dss
thatch:
ssh_auth.present:
- user: root
- source: salt://ssh_keys/thatch.id_rsa.pub
- config: '%h/.ssh/authorized_keys'
sshkeys:
ssh_auth.present:
- user: root
- enc: ssh-rsa
- options:
- option1="value1"
- option2="value2 flag2"
- comment: myuser
- names:
- AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==
- ssh-dss AAAAB3NzaCL0sQ9fJ5bYTEyY== user@domain
- option3="value3" ssh-dss AAAAB3NzaC1kcQ9J5bYTEyY== other@testdomain
- AAAAB3NzaC1kcQ9fJFF435bYTEyY== newcomment
sshkeys:
ssh_auth.manage:
- user: root
- enc: ssh-rsa
- options:
- option1="value1"
- option2="value2 flag2"
- comment: myuser
- ssh_keys:
- AAAAB3NzaC1kc3MAAACBAL0sQ9fJ5bYTEyY==
- ssh-dss AAAAB3NzaCL0sQ9fJ5bYTEyY== user@domain
- option3="value3" ssh-dss AAAAB3NzaC1kcQ9J5bYTEyY== other@testdomain
- AAAAB3NzaC1kcQ9fJFF435bYTEyY== newcomment
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import re
import sys
# Import 3rd-party libs
from salt.ext import six
def _present_test(user, name, enc, comment, options, source, config, fingerprint_hash_type):
'''
Run checks for "present"
'''
result = None
if source:
keys = __salt__['ssh.check_key_file'](
user,
source,
config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
if keys:
comment = ''
for key, status in six.iteritems(keys):
if status == 'exists':
continue
comment += 'Set to {0}: {1}\n'.format(status, key)
if comment:
return result, comment
err = sys.modules[
__salt__['test.ping'].__module__
].__context__.pop('ssh_auth.error', None)
if err:
return False, err
else:
return (
True,
'All host keys in file {0} are already present'.format(source)
)
else:
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split()
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split()
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
check = __salt__['ssh.check_key'](
user,
name,
enc,
comment,
options,
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if check == 'update':
comment = (
'Key {0} for user {1} is set to be updated'
).format(name, user)
elif check == 'add':
comment = (
'Key {0} for user {1} is set to be added'
).format(name, user)
elif check == 'exists':
result = True
comment = ('The authorized host key {0} is already present '
'for user {1}'.format(name, user))
return result, comment
def _absent_test(user, name, enc, comment, options, source, config, fingerprint_hash_type):
'''
Run checks for "absent"
'''
result = None
if source:
keys = __salt__['ssh.check_key_file'](
user,
source,
config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
if keys:
comment = ''
for key, status in list(keys.items()):
if status == 'add':
continue
comment += 'Set to remove: {0}\n'.format(key)
if comment:
return result, comment
err = sys.modules[
__salt__['test.ping'].__module__
].__context__.pop('ssh_auth.error', None)
if err:
return False, err
else:
return (
True,
'All host keys in file {0} are already absent'.format(source)
)
else:
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split()
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split()
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
check = __salt__['ssh.check_key'](
user,
name,
enc,
comment,
options,
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if check == 'update' or check == 'exists':
comment = ('Key {0} for user {1} is set for removal').format(name, user)
else:
comment = ('Key is already absent')
result = True
return result, comment
def present(
name,
user,
enc='ssh-rsa',
comment='',
source='',
options=None,
config='.ssh/authorized_keys',
fingerprint_hash_type=None,
**kwargs):
'''
Verifies that the specified SSH key is present for the specified user
name
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment and enc
will be ignored.
.. note::
The source file must contain keys in the format ``<enc> <key>
<comment>``. If you have generated a keypair using PuTTYgen, then you
will need to do the following to retrieve an OpenSSH-compatible public
key.
1. In PuTTYgen, click ``Load``, and select the *private* key file (not
the public key), and click ``Open``.
2. Copy the public key from the box labeled ``Public key for pasting
into OpenSSH authorized_keys file``.
3. Paste it into a new file.
options
The options passed to the key, pass a list object
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if source == '':
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split(None, 1)
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split(None, 2)
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
if __opts__['test']:
ret['result'], ret['comment'] = _present_test(
user,
name,
enc,
comment,
options or [],
source,
config,
fingerprint_hash_type)
return ret
# Get only the path to the file without env referrences to check if exists
if source != '':
source_path = __salt__['cp.get_url'](
source,
None,
saltenv=__env__)
if source != '' and not source_path:
data = 'no key'
elif source != '' and source_path:
key = __salt__['cp.get_file_str'](
source,
saltenv=__env__)
filehasoptions = False
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(ssh\-|ecds).*')
key = key.rstrip().split('\n')
for keyline in key:
filehasoptions = sshre.match(keyline)
if not filehasoptions:
data = __salt__['ssh.set_auth_key_from_file'](
user,
source,
config=config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
else:
# Split keyline to get key and comment
keyline = keyline.split(' ')
key_type = keyline[0]
key_value = keyline[1]
key_comment = keyline[2] if len(keyline) > 2 else ''
data = __salt__['ssh.set_auth_key'](
user,
key_value,
enc=key_type,
comment=key_comment,
options=options or [],
config=config,
fingerprint_hash_type=fingerprint_hash_type)
else:
data = __salt__['ssh.set_auth_key'](
user,
name,
enc=enc,
comment=comment,
options=options or [],
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if data == 'replace':
ret['changes'][name] = 'Updated'
ret['comment'] = ('The authorized host key {0} for user {1} was '
'updated'.format(name, user))
return ret
elif data == 'no change':
ret['comment'] = ('The authorized host key {0} is already present '
'for user {1}'.format(name, user))
elif data == 'new':
ret['changes'][name] = 'New'
ret['comment'] = ('The authorized host key {0} for user {1} was added'
.format(name, user))
elif data == 'no key':
ret['result'] = False
ret['comment'] = ('Failed to add the ssh key. Source file {0} is '
'missing'.format(source))
elif data == 'fail':
ret['result'] = False
err = sys.modules[
__salt__['test.ping'].__module__
].__context__.pop('ssh_auth.error', None)
if err:
ret['comment'] = err
else:
ret['comment'] = ('Failed to add the ssh key. Is the home '
'directory available, and/or does the key file '
'exist?')
elif data == 'invalid' or data == 'Invalid public key':
ret['result'] = False
ret['comment'] = 'Invalid public ssh key, most likely has spaces or invalid syntax'
return ret
def absent(name,
user,
enc='ssh-rsa',
comment='',
source='',
options=None,
config='.ssh/authorized_keys',
fingerprint_hash_type=None):
'''
Verifies that the specified SSH key is absent
name
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
options
The options passed to the key, pass a list object
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment, enc and
options will be ignored.
.. versionadded:: 2015.8.0
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified.
.. versionadded:: 2016.11.7
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if __opts__['test']:
ret['result'], ret['comment'] = _absent_test(
user,
name,
enc,
comment,
options or [],
source,
config,
fingerprint_hash_type)
return ret
# Extract Key from file if source is present
if source != '':
key = __salt__['cp.get_file_str'](
source,
saltenv=__env__)
filehasoptions = False
# check if this is of form {options} {enc} {key} {comment}
sshre = re.compile(r'^(ssh\-|ecds).*')
key = key.rstrip().split('\n')
for keyline in key:
filehasoptions = sshre.match(keyline)
if not filehasoptions:
ret['comment'] = __salt__['ssh.rm_auth_key_from_file'](user,
source,
config,
saltenv=__env__,
fingerprint_hash_type=fingerprint_hash_type)
else:
# Split keyline to get key
keyline = keyline.split(' ')
ret['comment'] = __salt__['ssh.rm_auth_key'](user,
keyline[1],
config=config,
fingerprint_hash_type=fingerprint_hash_type)
else:
# Get just the key
sshre = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
fullkey = sshre.search(name)
# if it is {key} [comment]
if not fullkey:
key_and_comment = name.split(None, 1)
name = key_and_comment[0]
if len(key_and_comment) == 2:
comment = key_and_comment[1]
else:
# if there are options, set them
if fullkey.group(1):
options = fullkey.group(1).split(',')
# key is of format: {enc} {key} [comment]
comps = fullkey.group(2).split()
enc = comps[0]
name = comps[1]
if len(comps) == 3:
comment = comps[2]
ret['comment'] = __salt__['ssh.rm_auth_key'](user,
name,
config=config,
fingerprint_hash_type=fingerprint_hash_type)
if ret['comment'] == 'User authorized keys file not present':
ret['result'] = False
return ret
elif ret['comment'] == 'Key removed':
ret['changes'][name] = 'Removed'
return ret
|
saltstack/salt | salt/runners/smartos_vmadm.py | _action | python | def _action(action='get', search=None, one=True, force=False):
'''
Multi action helper for start, stop, get, ...
'''
vms = {}
matched_vms = []
client = salt.client.get_local_client(__opts__['conf_file'])
## lookup vms
try:
vmadm_args = {}
vmadm_args['order'] = 'uuid,alias,hostname,state'
if '=' in search:
vmadm_args['search'] = search
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'vmadm.list', kwarg=vmadm_args,
tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
for vm in cn[node]['ret']:
vmcfg = cn[node]['ret'][vm]
vmcfg['node'] = node
vms[vm] = vmcfg
except SaltClientError as client_error:
pass
## check if we have vms
if not vms:
return {'Error': 'No vms found.'}
## simple search
if '=' not in search:
loop_pass = 0
while loop_pass < 3:
## each pass will try a different field
if loop_pass == 0:
field = 'uuid'
elif loop_pass == 1:
field = 'hostname'
else:
field = 'alias'
## loop vms and try to match
for vm in vms:
if field == 'uuid' and vm == search:
matched_vms.append(vm)
break # exit for on uuid match (max = 1)
elif field in vms[vm] and vms[vm][field] == search:
matched_vms.append(vm)
## exit on match(es) or try again
if matched_vms:
break
else:
loop_pass += 1
else:
for vm in vms:
matched_vms.append(vm)
## check if we have vms
if not matched_vms:
return {'Error': 'No vms matched.'}
## multiple allowed?
if one and len(matched_vms) > 1:
return {
'Error': 'Matched {0} vms, only one allowed!'.format(len(matched_vms)),
'Matches': matched_vms
}
## perform action
ret = {}
if action in ['start', 'stop', 'reboot', 'get']:
for vm in matched_vms:
vmadm_args = {
'key': 'uuid',
'vm': vm
}
try:
for vmadm_res in client.cmd_iter(vms[vm]['node'], 'vmadm.{0}'.format(action), kwarg=vmadm_args):
if not vmadm_res:
continue
if vms[vm]['node'] in vmadm_res:
ret[vm] = vmadm_res[vms[vm]['node']]['ret']
except SaltClientError as client_error:
ret[vm] = False
elif action in ['is_running']:
ret = True
for vm in matched_vms:
if vms[vm]['state'] != 'running':
ret = False
break
return ret | Multi action helper for start, stop, get, ... | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/smartos_vmadm.py#L36-L133 | [
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n",
"def get_local_client(\n c_path=os.path.join(syspaths.CONFIG_DIR, 'master'),\n mopts=None,\n skip_perm_errors=False,\n io_loop=None,\n auto_reconnect=False):\n '''\n .. versionadded:: 2014.7.0\n\n Read in the config and return the correct LocalClient object based on\n the configured transport\n\n :param IOLoop io_loop: io_loop used for events.\n Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n if mopts:\n opts = mopts\n else:\n # Late import to prevent circular import\n import salt.config\n opts = salt.config.client_config(c_path)\n\n # TODO: AIO core is separate from transport\n return LocalClient(\n mopts=opts,\n skip_perm_errors=skip_perm_errors,\n io_loop=io_loop,\n auto_reconnect=auto_reconnect)\n"
] | # -*- coding: utf-8 -*-
'''
Runner for SmartOS minions control vmadm
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.client
from salt.exceptions import SaltClientError
from salt.utils.odict import OrderedDict
# Import 3rd party libs
from salt.ext import six
# Function aliases
__func_alias__ = {
'list_vms': 'list'
}
# Define the module's virtual name
__virtualname__ = 'vmadm'
def __virtual__():
'''
Provides vmadm runner
'''
# NOTE: always load vmadm runner
# we could check using test.ping + a grain
# match, but doing this on master startup is
# not acceptable
return __virtualname__
def nodes(verbose=False):
'''
List all compute nodes
verbose : boolean
print additional information about the node
e.g. platform version, hvm capable, ...
CLI Example:
.. code-block:: bash
salt-run vmadm.nodes
salt-run vmadm.nodes verbose=True
'''
ret = {} if verbose else []
client = salt.client.get_local_client(__opts__['conf_file'])
## get list of nodes
try:
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'grains.items', tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
if verbose:
ret[node] = {}
ret[node]['version'] = {}
ret[node]['version']['platform'] = cn[node]['ret']['osrelease']
if 'computenode_sdc_version' in cn[node]['ret']:
ret[node]['version']['sdc'] = cn[node]['ret']['computenode_sdc_version']
ret[node]['vms'] = {}
if 'computenode_vm_capable' in cn[node]['ret'] and \
cn[node]['ret']['computenode_vm_capable'] and \
'computenode_vm_hw_virt' in cn[node]['ret']:
ret[node]['vms']['hw_cap'] = cn[node]['ret']['computenode_vm_hw_virt']
else:
ret[node]['vms']['hw_cap'] = False
if 'computenode_vms_running' in cn[node]['ret']:
ret[node]['vms']['running'] = cn[node]['ret']['computenode_vms_running']
else:
ret.append(node)
except SaltClientError as client_error:
return "{0}".format(client_error)
if not verbose:
ret.sort()
return ret
def list_vms(search=None, verbose=False):
'''
List all vms
search : string
filter vms, see the execution module
verbose : boolean
print additional information about the vm
CLI Example:
.. code-block:: bash
salt-run vmadm.list
salt-run vmadm.list search='type=KVM'
salt-run vmadm.list verbose=True
'''
ret = OrderedDict() if verbose else []
client = salt.client.get_local_client(__opts__['conf_file'])
try:
vmadm_args = {}
vmadm_args['order'] = 'uuid,alias,hostname,state,type,cpu_cap,vcpus,ram'
if search:
vmadm_args['search'] = search
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'vmadm.list', kwarg=vmadm_args,
tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
for vm in cn[node]['ret']:
vmcfg = cn[node]['ret'][vm]
if verbose:
ret[vm] = OrderedDict()
ret[vm]['hostname'] = vmcfg['hostname']
ret[vm]['alias'] = vmcfg['alias']
ret[vm]['computenode'] = node
ret[vm]['state'] = vmcfg['state']
ret[vm]['resources'] = OrderedDict()
ret[vm]['resources']['memory'] = vmcfg['ram']
if vmcfg['type'] == 'KVM':
ret[vm]['resources']['cpu'] = "{0:.2f}".format(int(vmcfg['vcpus']))
else:
if vmcfg['cpu_cap'] != '':
ret[vm]['resources']['cpu'] = "{0:.2f}".format(int(vmcfg['cpu_cap'])/100)
else:
ret.append(vm)
except SaltClientError as client_error:
return "{0}".format(client_error)
if not verbose:
ret = sorted(ret)
return ret
def start(search, one=True):
'''
Start one or more vms
search : string
filter vms, see the execution module.
one : boolean
start only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.start 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.start search='alias=jiska'
salt-run vmadm.start search='type=KVM' one=False
'''
return _action('start', search, one)
def stop(search, one=True):
'''
Stop one or more vms
search : string
filter vms, see the execution module.
one : boolean
stop only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.stop 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.stop search='alias=jody'
salt-run vmadm.stop search='type=KVM' one=False
'''
return _action('stop', search, one)
def reboot(search, one=True, force=False):
'''
Reboot one or more vms
search : string
filter vms, see the execution module.
one : boolean
reboot only one vm
force : boolean
force reboot, faster but no graceful shutdown
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.reboot 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.reboot search='alias=marije'
salt-run vmadm.reboot search='type=KVM' one=False
'''
return _action('reboot', search, one, force)
def get(search, one=True):
'''
Return information for vms
search : string
filter vms, see the execution module.
one : boolean
return only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.get 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.get search='alias=saskia'
'''
return _action('get', search, one)
def is_running(search):
'''
Return true if vm is running
search : string
filter vms, see the execution module.
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
.. note::
If multiple vms are matched, the result will be true of ALL vms are running
CLI Example:
.. code-block:: bash
salt-run vmadm.is_running 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.is_running search='alias=julia'
'''
return _action('is_running', search, False)
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt | salt/runners/smartos_vmadm.py | nodes | python | def nodes(verbose=False):
'''
List all compute nodes
verbose : boolean
print additional information about the node
e.g. platform version, hvm capable, ...
CLI Example:
.. code-block:: bash
salt-run vmadm.nodes
salt-run vmadm.nodes verbose=True
'''
ret = {} if verbose else []
client = salt.client.get_local_client(__opts__['conf_file'])
## get list of nodes
try:
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'grains.items', tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
if verbose:
ret[node] = {}
ret[node]['version'] = {}
ret[node]['version']['platform'] = cn[node]['ret']['osrelease']
if 'computenode_sdc_version' in cn[node]['ret']:
ret[node]['version']['sdc'] = cn[node]['ret']['computenode_sdc_version']
ret[node]['vms'] = {}
if 'computenode_vm_capable' in cn[node]['ret'] and \
cn[node]['ret']['computenode_vm_capable'] and \
'computenode_vm_hw_virt' in cn[node]['ret']:
ret[node]['vms']['hw_cap'] = cn[node]['ret']['computenode_vm_hw_virt']
else:
ret[node]['vms']['hw_cap'] = False
if 'computenode_vms_running' in cn[node]['ret']:
ret[node]['vms']['running'] = cn[node]['ret']['computenode_vms_running']
else:
ret.append(node)
except SaltClientError as client_error:
return "{0}".format(client_error)
if not verbose:
ret.sort()
return ret | List all compute nodes
verbose : boolean
print additional information about the node
e.g. platform version, hvm capable, ...
CLI Example:
.. code-block:: bash
salt-run vmadm.nodes
salt-run vmadm.nodes verbose=True | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/smartos_vmadm.py#L136-L187 | [
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n",
"def get_local_client(\n c_path=os.path.join(syspaths.CONFIG_DIR, 'master'),\n mopts=None,\n skip_perm_errors=False,\n io_loop=None,\n auto_reconnect=False):\n '''\n .. versionadded:: 2014.7.0\n\n Read in the config and return the correct LocalClient object based on\n the configured transport\n\n :param IOLoop io_loop: io_loop used for events.\n Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n if mopts:\n opts = mopts\n else:\n # Late import to prevent circular import\n import salt.config\n opts = salt.config.client_config(c_path)\n\n # TODO: AIO core is separate from transport\n return LocalClient(\n mopts=opts,\n skip_perm_errors=skip_perm_errors,\n io_loop=io_loop,\n auto_reconnect=auto_reconnect)\n",
"def cmd_iter(\n self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n ret='',\n kwarg=None,\n **kwargs):\n '''\n Yields the individual minion returns as they come in\n\n The function signature is the same as :py:meth:`cmd` with the\n following exceptions.\n\n Normally :py:meth:`cmd_iter` does not yield results for minions that\n are not connected. If you want it to return results for disconnected\n minions set `expect_minions=True` in `kwargs`.\n\n :return: A generator yielding the individual minion returns\n\n .. code-block:: python\n\n >>> ret = local.cmd_iter('*', 'test.ping')\n >>> for i in ret:\n ... print(i)\n {'jerry': {'ret': True}}\n {'dave': {'ret': True}}\n {'stewart': {'ret': True}}\n '''\n was_listening = self.event.cpub\n\n try:\n pub_data = self.run_job(\n tgt,\n fun,\n arg,\n tgt_type,\n ret,\n timeout,\n kwarg=kwarg,\n listen=True,\n **kwargs)\n\n if not pub_data:\n yield pub_data\n else:\n if kwargs.get('yield_pub_data'):\n yield pub_data\n for fn_ret in self.get_iter_returns(pub_data['jid'],\n pub_data['minions'],\n timeout=self._get_timeout(timeout),\n tgt=tgt,\n tgt_type=tgt_type,\n **kwargs):\n if not fn_ret:\n continue\n yield fn_ret\n self._clean_up_subscriptions(pub_data['jid'])\n finally:\n if not was_listening:\n self.event.close_pub()\n"
] | # -*- coding: utf-8 -*-
'''
Runner for SmartOS minions control vmadm
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.client
from salt.exceptions import SaltClientError
from salt.utils.odict import OrderedDict
# Import 3rd party libs
from salt.ext import six
# Function aliases
__func_alias__ = {
'list_vms': 'list'
}
# Define the module's virtual name
__virtualname__ = 'vmadm'
def __virtual__():
'''
Provides vmadm runner
'''
# NOTE: always load vmadm runner
# we could check using test.ping + a grain
# match, but doing this on master startup is
# not acceptable
return __virtualname__
def _action(action='get', search=None, one=True, force=False):
'''
Multi action helper for start, stop, get, ...
'''
vms = {}
matched_vms = []
client = salt.client.get_local_client(__opts__['conf_file'])
## lookup vms
try:
vmadm_args = {}
vmadm_args['order'] = 'uuid,alias,hostname,state'
if '=' in search:
vmadm_args['search'] = search
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'vmadm.list', kwarg=vmadm_args,
tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
for vm in cn[node]['ret']:
vmcfg = cn[node]['ret'][vm]
vmcfg['node'] = node
vms[vm] = vmcfg
except SaltClientError as client_error:
pass
## check if we have vms
if not vms:
return {'Error': 'No vms found.'}
## simple search
if '=' not in search:
loop_pass = 0
while loop_pass < 3:
## each pass will try a different field
if loop_pass == 0:
field = 'uuid'
elif loop_pass == 1:
field = 'hostname'
else:
field = 'alias'
## loop vms and try to match
for vm in vms:
if field == 'uuid' and vm == search:
matched_vms.append(vm)
break # exit for on uuid match (max = 1)
elif field in vms[vm] and vms[vm][field] == search:
matched_vms.append(vm)
## exit on match(es) or try again
if matched_vms:
break
else:
loop_pass += 1
else:
for vm in vms:
matched_vms.append(vm)
## check if we have vms
if not matched_vms:
return {'Error': 'No vms matched.'}
## multiple allowed?
if one and len(matched_vms) > 1:
return {
'Error': 'Matched {0} vms, only one allowed!'.format(len(matched_vms)),
'Matches': matched_vms
}
## perform action
ret = {}
if action in ['start', 'stop', 'reboot', 'get']:
for vm in matched_vms:
vmadm_args = {
'key': 'uuid',
'vm': vm
}
try:
for vmadm_res in client.cmd_iter(vms[vm]['node'], 'vmadm.{0}'.format(action), kwarg=vmadm_args):
if not vmadm_res:
continue
if vms[vm]['node'] in vmadm_res:
ret[vm] = vmadm_res[vms[vm]['node']]['ret']
except SaltClientError as client_error:
ret[vm] = False
elif action in ['is_running']:
ret = True
for vm in matched_vms:
if vms[vm]['state'] != 'running':
ret = False
break
return ret
def list_vms(search=None, verbose=False):
'''
List all vms
search : string
filter vms, see the execution module
verbose : boolean
print additional information about the vm
CLI Example:
.. code-block:: bash
salt-run vmadm.list
salt-run vmadm.list search='type=KVM'
salt-run vmadm.list verbose=True
'''
ret = OrderedDict() if verbose else []
client = salt.client.get_local_client(__opts__['conf_file'])
try:
vmadm_args = {}
vmadm_args['order'] = 'uuid,alias,hostname,state,type,cpu_cap,vcpus,ram'
if search:
vmadm_args['search'] = search
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'vmadm.list', kwarg=vmadm_args,
tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
for vm in cn[node]['ret']:
vmcfg = cn[node]['ret'][vm]
if verbose:
ret[vm] = OrderedDict()
ret[vm]['hostname'] = vmcfg['hostname']
ret[vm]['alias'] = vmcfg['alias']
ret[vm]['computenode'] = node
ret[vm]['state'] = vmcfg['state']
ret[vm]['resources'] = OrderedDict()
ret[vm]['resources']['memory'] = vmcfg['ram']
if vmcfg['type'] == 'KVM':
ret[vm]['resources']['cpu'] = "{0:.2f}".format(int(vmcfg['vcpus']))
else:
if vmcfg['cpu_cap'] != '':
ret[vm]['resources']['cpu'] = "{0:.2f}".format(int(vmcfg['cpu_cap'])/100)
else:
ret.append(vm)
except SaltClientError as client_error:
return "{0}".format(client_error)
if not verbose:
ret = sorted(ret)
return ret
def start(search, one=True):
'''
Start one or more vms
search : string
filter vms, see the execution module.
one : boolean
start only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.start 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.start search='alias=jiska'
salt-run vmadm.start search='type=KVM' one=False
'''
return _action('start', search, one)
def stop(search, one=True):
'''
Stop one or more vms
search : string
filter vms, see the execution module.
one : boolean
stop only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.stop 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.stop search='alias=jody'
salt-run vmadm.stop search='type=KVM' one=False
'''
return _action('stop', search, one)
def reboot(search, one=True, force=False):
'''
Reboot one or more vms
search : string
filter vms, see the execution module.
one : boolean
reboot only one vm
force : boolean
force reboot, faster but no graceful shutdown
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.reboot 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.reboot search='alias=marije'
salt-run vmadm.reboot search='type=KVM' one=False
'''
return _action('reboot', search, one, force)
def get(search, one=True):
'''
Return information for vms
search : string
filter vms, see the execution module.
one : boolean
return only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.get 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.get search='alias=saskia'
'''
return _action('get', search, one)
def is_running(search):
'''
Return true if vm is running
search : string
filter vms, see the execution module.
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
.. note::
If multiple vms are matched, the result will be true of ALL vms are running
CLI Example:
.. code-block:: bash
salt-run vmadm.is_running 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.is_running search='alias=julia'
'''
return _action('is_running', search, False)
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt | salt/runners/smartos_vmadm.py | list_vms | python | def list_vms(search=None, verbose=False):
'''
List all vms
search : string
filter vms, see the execution module
verbose : boolean
print additional information about the vm
CLI Example:
.. code-block:: bash
salt-run vmadm.list
salt-run vmadm.list search='type=KVM'
salt-run vmadm.list verbose=True
'''
ret = OrderedDict() if verbose else []
client = salt.client.get_local_client(__opts__['conf_file'])
try:
vmadm_args = {}
vmadm_args['order'] = 'uuid,alias,hostname,state,type,cpu_cap,vcpus,ram'
if search:
vmadm_args['search'] = search
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'vmadm.list', kwarg=vmadm_args,
tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
for vm in cn[node]['ret']:
vmcfg = cn[node]['ret'][vm]
if verbose:
ret[vm] = OrderedDict()
ret[vm]['hostname'] = vmcfg['hostname']
ret[vm]['alias'] = vmcfg['alias']
ret[vm]['computenode'] = node
ret[vm]['state'] = vmcfg['state']
ret[vm]['resources'] = OrderedDict()
ret[vm]['resources']['memory'] = vmcfg['ram']
if vmcfg['type'] == 'KVM':
ret[vm]['resources']['cpu'] = "{0:.2f}".format(int(vmcfg['vcpus']))
else:
if vmcfg['cpu_cap'] != '':
ret[vm]['resources']['cpu'] = "{0:.2f}".format(int(vmcfg['cpu_cap'])/100)
else:
ret.append(vm)
except SaltClientError as client_error:
return "{0}".format(client_error)
if not verbose:
ret = sorted(ret)
return ret | List all vms
search : string
filter vms, see the execution module
verbose : boolean
print additional information about the vm
CLI Example:
.. code-block:: bash
salt-run vmadm.list
salt-run vmadm.list search='type=KVM'
salt-run vmadm.list verbose=True | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/smartos_vmadm.py#L190-L247 | [
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n",
"def get_local_client(\n c_path=os.path.join(syspaths.CONFIG_DIR, 'master'),\n mopts=None,\n skip_perm_errors=False,\n io_loop=None,\n auto_reconnect=False):\n '''\n .. versionadded:: 2014.7.0\n\n Read in the config and return the correct LocalClient object based on\n the configured transport\n\n :param IOLoop io_loop: io_loop used for events.\n Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n if mopts:\n opts = mopts\n else:\n # Late import to prevent circular import\n import salt.config\n opts = salt.config.client_config(c_path)\n\n # TODO: AIO core is separate from transport\n return LocalClient(\n mopts=opts,\n skip_perm_errors=skip_perm_errors,\n io_loop=io_loop,\n auto_reconnect=auto_reconnect)\n",
"def cmd_iter(\n self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n ret='',\n kwarg=None,\n **kwargs):\n '''\n Yields the individual minion returns as they come in\n\n The function signature is the same as :py:meth:`cmd` with the\n following exceptions.\n\n Normally :py:meth:`cmd_iter` does not yield results for minions that\n are not connected. If you want it to return results for disconnected\n minions set `expect_minions=True` in `kwargs`.\n\n :return: A generator yielding the individual minion returns\n\n .. code-block:: python\n\n >>> ret = local.cmd_iter('*', 'test.ping')\n >>> for i in ret:\n ... print(i)\n {'jerry': {'ret': True}}\n {'dave': {'ret': True}}\n {'stewart': {'ret': True}}\n '''\n was_listening = self.event.cpub\n\n try:\n pub_data = self.run_job(\n tgt,\n fun,\n arg,\n tgt_type,\n ret,\n timeout,\n kwarg=kwarg,\n listen=True,\n **kwargs)\n\n if not pub_data:\n yield pub_data\n else:\n if kwargs.get('yield_pub_data'):\n yield pub_data\n for fn_ret in self.get_iter_returns(pub_data['jid'],\n pub_data['minions'],\n timeout=self._get_timeout(timeout),\n tgt=tgt,\n tgt_type=tgt_type,\n **kwargs):\n if not fn_ret:\n continue\n yield fn_ret\n self._clean_up_subscriptions(pub_data['jid'])\n finally:\n if not was_listening:\n self.event.close_pub()\n"
] | # -*- coding: utf-8 -*-
'''
Runner for SmartOS minions control vmadm
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.client
from salt.exceptions import SaltClientError
from salt.utils.odict import OrderedDict
# Import 3rd party libs
from salt.ext import six
# Function aliases
__func_alias__ = {
'list_vms': 'list'
}
# Define the module's virtual name
__virtualname__ = 'vmadm'
def __virtual__():
'''
Provides vmadm runner
'''
# NOTE: always load vmadm runner
# we could check using test.ping + a grain
# match, but doing this on master startup is
# not acceptable
return __virtualname__
def _action(action='get', search=None, one=True, force=False):
'''
Multi action helper for start, stop, get, ...
'''
vms = {}
matched_vms = []
client = salt.client.get_local_client(__opts__['conf_file'])
## lookup vms
try:
vmadm_args = {}
vmadm_args['order'] = 'uuid,alias,hostname,state'
if '=' in search:
vmadm_args['search'] = search
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'vmadm.list', kwarg=vmadm_args,
tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
for vm in cn[node]['ret']:
vmcfg = cn[node]['ret'][vm]
vmcfg['node'] = node
vms[vm] = vmcfg
except SaltClientError as client_error:
pass
## check if we have vms
if not vms:
return {'Error': 'No vms found.'}
## simple search
if '=' not in search:
loop_pass = 0
while loop_pass < 3:
## each pass will try a different field
if loop_pass == 0:
field = 'uuid'
elif loop_pass == 1:
field = 'hostname'
else:
field = 'alias'
## loop vms and try to match
for vm in vms:
if field == 'uuid' and vm == search:
matched_vms.append(vm)
break # exit for on uuid match (max = 1)
elif field in vms[vm] and vms[vm][field] == search:
matched_vms.append(vm)
## exit on match(es) or try again
if matched_vms:
break
else:
loop_pass += 1
else:
for vm in vms:
matched_vms.append(vm)
## check if we have vms
if not matched_vms:
return {'Error': 'No vms matched.'}
## multiple allowed?
if one and len(matched_vms) > 1:
return {
'Error': 'Matched {0} vms, only one allowed!'.format(len(matched_vms)),
'Matches': matched_vms
}
## perform action
ret = {}
if action in ['start', 'stop', 'reboot', 'get']:
for vm in matched_vms:
vmadm_args = {
'key': 'uuid',
'vm': vm
}
try:
for vmadm_res in client.cmd_iter(vms[vm]['node'], 'vmadm.{0}'.format(action), kwarg=vmadm_args):
if not vmadm_res:
continue
if vms[vm]['node'] in vmadm_res:
ret[vm] = vmadm_res[vms[vm]['node']]['ret']
except SaltClientError as client_error:
ret[vm] = False
elif action in ['is_running']:
ret = True
for vm in matched_vms:
if vms[vm]['state'] != 'running':
ret = False
break
return ret
def nodes(verbose=False):
'''
List all compute nodes
verbose : boolean
print additional information about the node
e.g. platform version, hvm capable, ...
CLI Example:
.. code-block:: bash
salt-run vmadm.nodes
salt-run vmadm.nodes verbose=True
'''
ret = {} if verbose else []
client = salt.client.get_local_client(__opts__['conf_file'])
## get list of nodes
try:
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'grains.items', tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
if verbose:
ret[node] = {}
ret[node]['version'] = {}
ret[node]['version']['platform'] = cn[node]['ret']['osrelease']
if 'computenode_sdc_version' in cn[node]['ret']:
ret[node]['version']['sdc'] = cn[node]['ret']['computenode_sdc_version']
ret[node]['vms'] = {}
if 'computenode_vm_capable' in cn[node]['ret'] and \
cn[node]['ret']['computenode_vm_capable'] and \
'computenode_vm_hw_virt' in cn[node]['ret']:
ret[node]['vms']['hw_cap'] = cn[node]['ret']['computenode_vm_hw_virt']
else:
ret[node]['vms']['hw_cap'] = False
if 'computenode_vms_running' in cn[node]['ret']:
ret[node]['vms']['running'] = cn[node]['ret']['computenode_vms_running']
else:
ret.append(node)
except SaltClientError as client_error:
return "{0}".format(client_error)
if not verbose:
ret.sort()
return ret
def start(search, one=True):
'''
Start one or more vms
search : string
filter vms, see the execution module.
one : boolean
start only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.start 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.start search='alias=jiska'
salt-run vmadm.start search='type=KVM' one=False
'''
return _action('start', search, one)
def stop(search, one=True):
'''
Stop one or more vms
search : string
filter vms, see the execution module.
one : boolean
stop only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.stop 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.stop search='alias=jody'
salt-run vmadm.stop search='type=KVM' one=False
'''
return _action('stop', search, one)
def reboot(search, one=True, force=False):
'''
Reboot one or more vms
search : string
filter vms, see the execution module.
one : boolean
reboot only one vm
force : boolean
force reboot, faster but no graceful shutdown
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.reboot 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.reboot search='alias=marije'
salt-run vmadm.reboot search='type=KVM' one=False
'''
return _action('reboot', search, one, force)
def get(search, one=True):
'''
Return information for vms
search : string
filter vms, see the execution module.
one : boolean
return only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.get 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.get search='alias=saskia'
'''
return _action('get', search, one)
def is_running(search):
'''
Return true if vm is running
search : string
filter vms, see the execution module.
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
.. note::
If multiple vms are matched, the result will be true of ALL vms are running
CLI Example:
.. code-block:: bash
salt-run vmadm.is_running 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.is_running search='alias=julia'
'''
return _action('is_running', search, False)
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt | salt/runners/smartos_vmadm.py | reboot | python | def reboot(search, one=True, force=False):
'''
Reboot one or more vms
search : string
filter vms, see the execution module.
one : boolean
reboot only one vm
force : boolean
force reboot, faster but no graceful shutdown
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.reboot 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.reboot search='alias=marije'
salt-run vmadm.reboot search='type=KVM' one=False
'''
return _action('reboot', search, one, force) | Reboot one or more vms
search : string
filter vms, see the execution module.
one : boolean
reboot only one vm
force : boolean
force reboot, faster but no graceful shutdown
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.reboot 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.reboot search='alias=marije'
salt-run vmadm.reboot search='type=KVM' one=False | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/smartos_vmadm.py#L298-L321 | [
"def _action(action='get', search=None, one=True, force=False):\n '''\n Multi action helper for start, stop, get, ...\n '''\n vms = {}\n matched_vms = []\n client = salt.client.get_local_client(__opts__['conf_file'])\n\n ## lookup vms\n try:\n vmadm_args = {}\n vmadm_args['order'] = 'uuid,alias,hostname,state'\n if '=' in search:\n vmadm_args['search'] = search\n for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',\n 'vmadm.list', kwarg=vmadm_args,\n tgt_type='compound'):\n if not cn:\n continue\n node = next(six.iterkeys(cn))\n if not isinstance(cn[node], dict) or \\\n 'ret' not in cn[node] or \\\n not isinstance(cn[node]['ret'], dict):\n continue\n for vm in cn[node]['ret']:\n vmcfg = cn[node]['ret'][vm]\n vmcfg['node'] = node\n vms[vm] = vmcfg\n except SaltClientError as client_error:\n pass\n\n ## check if we have vms\n if not vms:\n return {'Error': 'No vms found.'}\n\n ## simple search\n if '=' not in search:\n loop_pass = 0\n while loop_pass < 3:\n ## each pass will try a different field\n if loop_pass == 0:\n field = 'uuid'\n elif loop_pass == 1:\n field = 'hostname'\n else:\n field = 'alias'\n\n ## loop vms and try to match\n for vm in vms:\n if field == 'uuid' and vm == search:\n matched_vms.append(vm)\n break # exit for on uuid match (max = 1)\n elif field in vms[vm] and vms[vm][field] == search:\n matched_vms.append(vm)\n\n ## exit on match(es) or try again\n if matched_vms:\n break\n else:\n loop_pass += 1\n else:\n for vm in vms:\n matched_vms.append(vm)\n\n ## check if we have vms\n if not matched_vms:\n return {'Error': 'No vms matched.'}\n\n ## multiple allowed?\n if one and len(matched_vms) > 1:\n return {\n 'Error': 'Matched {0} vms, only one allowed!'.format(len(matched_vms)),\n 'Matches': matched_vms\n }\n\n ## perform action\n ret = {}\n if action in ['start', 'stop', 'reboot', 'get']:\n for vm in matched_vms:\n vmadm_args = {\n 'key': 'uuid',\n 'vm': vm\n }\n try:\n for vmadm_res in client.cmd_iter(vms[vm]['node'], 'vmadm.{0}'.format(action), kwarg=vmadm_args):\n if not vmadm_res:\n continue\n if vms[vm]['node'] in vmadm_res:\n ret[vm] = vmadm_res[vms[vm]['node']]['ret']\n except SaltClientError as client_error:\n ret[vm] = False\n elif action in ['is_running']:\n ret = True\n for vm in matched_vms:\n if vms[vm]['state'] != 'running':\n ret = False\n break\n return ret\n"
] | # -*- coding: utf-8 -*-
'''
Runner for SmartOS minions control vmadm
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.client
from salt.exceptions import SaltClientError
from salt.utils.odict import OrderedDict
# Import 3rd party libs
from salt.ext import six
# Function aliases
__func_alias__ = {
'list_vms': 'list'
}
# Define the module's virtual name
__virtualname__ = 'vmadm'
def __virtual__():
'''
Provides vmadm runner
'''
# NOTE: always load vmadm runner
# we could check using test.ping + a grain
# match, but doing this on master startup is
# not acceptable
return __virtualname__
def _action(action='get', search=None, one=True, force=False):
'''
Multi action helper for start, stop, get, ...
'''
vms = {}
matched_vms = []
client = salt.client.get_local_client(__opts__['conf_file'])
## lookup vms
try:
vmadm_args = {}
vmadm_args['order'] = 'uuid,alias,hostname,state'
if '=' in search:
vmadm_args['search'] = search
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'vmadm.list', kwarg=vmadm_args,
tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
for vm in cn[node]['ret']:
vmcfg = cn[node]['ret'][vm]
vmcfg['node'] = node
vms[vm] = vmcfg
except SaltClientError as client_error:
pass
## check if we have vms
if not vms:
return {'Error': 'No vms found.'}
## simple search
if '=' not in search:
loop_pass = 0
while loop_pass < 3:
## each pass will try a different field
if loop_pass == 0:
field = 'uuid'
elif loop_pass == 1:
field = 'hostname'
else:
field = 'alias'
## loop vms and try to match
for vm in vms:
if field == 'uuid' and vm == search:
matched_vms.append(vm)
break # exit for on uuid match (max = 1)
elif field in vms[vm] and vms[vm][field] == search:
matched_vms.append(vm)
## exit on match(es) or try again
if matched_vms:
break
else:
loop_pass += 1
else:
for vm in vms:
matched_vms.append(vm)
## check if we have vms
if not matched_vms:
return {'Error': 'No vms matched.'}
## multiple allowed?
if one and len(matched_vms) > 1:
return {
'Error': 'Matched {0} vms, only one allowed!'.format(len(matched_vms)),
'Matches': matched_vms
}
## perform action
ret = {}
if action in ['start', 'stop', 'reboot', 'get']:
for vm in matched_vms:
vmadm_args = {
'key': 'uuid',
'vm': vm
}
try:
for vmadm_res in client.cmd_iter(vms[vm]['node'], 'vmadm.{0}'.format(action), kwarg=vmadm_args):
if not vmadm_res:
continue
if vms[vm]['node'] in vmadm_res:
ret[vm] = vmadm_res[vms[vm]['node']]['ret']
except SaltClientError as client_error:
ret[vm] = False
elif action in ['is_running']:
ret = True
for vm in matched_vms:
if vms[vm]['state'] != 'running':
ret = False
break
return ret
def nodes(verbose=False):
'''
List all compute nodes
verbose : boolean
print additional information about the node
e.g. platform version, hvm capable, ...
CLI Example:
.. code-block:: bash
salt-run vmadm.nodes
salt-run vmadm.nodes verbose=True
'''
ret = {} if verbose else []
client = salt.client.get_local_client(__opts__['conf_file'])
## get list of nodes
try:
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'grains.items', tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
if verbose:
ret[node] = {}
ret[node]['version'] = {}
ret[node]['version']['platform'] = cn[node]['ret']['osrelease']
if 'computenode_sdc_version' in cn[node]['ret']:
ret[node]['version']['sdc'] = cn[node]['ret']['computenode_sdc_version']
ret[node]['vms'] = {}
if 'computenode_vm_capable' in cn[node]['ret'] and \
cn[node]['ret']['computenode_vm_capable'] and \
'computenode_vm_hw_virt' in cn[node]['ret']:
ret[node]['vms']['hw_cap'] = cn[node]['ret']['computenode_vm_hw_virt']
else:
ret[node]['vms']['hw_cap'] = False
if 'computenode_vms_running' in cn[node]['ret']:
ret[node]['vms']['running'] = cn[node]['ret']['computenode_vms_running']
else:
ret.append(node)
except SaltClientError as client_error:
return "{0}".format(client_error)
if not verbose:
ret.sort()
return ret
def list_vms(search=None, verbose=False):
'''
List all vms
search : string
filter vms, see the execution module
verbose : boolean
print additional information about the vm
CLI Example:
.. code-block:: bash
salt-run vmadm.list
salt-run vmadm.list search='type=KVM'
salt-run vmadm.list verbose=True
'''
ret = OrderedDict() if verbose else []
client = salt.client.get_local_client(__opts__['conf_file'])
try:
vmadm_args = {}
vmadm_args['order'] = 'uuid,alias,hostname,state,type,cpu_cap,vcpus,ram'
if search:
vmadm_args['search'] = search
for cn in client.cmd_iter('G@virtual:physical and G@os:smartos',
'vmadm.list', kwarg=vmadm_args,
tgt_type='compound'):
if not cn:
continue
node = next(six.iterkeys(cn))
if not isinstance(cn[node], dict) or \
'ret' not in cn[node] or \
not isinstance(cn[node]['ret'], dict):
continue
for vm in cn[node]['ret']:
vmcfg = cn[node]['ret'][vm]
if verbose:
ret[vm] = OrderedDict()
ret[vm]['hostname'] = vmcfg['hostname']
ret[vm]['alias'] = vmcfg['alias']
ret[vm]['computenode'] = node
ret[vm]['state'] = vmcfg['state']
ret[vm]['resources'] = OrderedDict()
ret[vm]['resources']['memory'] = vmcfg['ram']
if vmcfg['type'] == 'KVM':
ret[vm]['resources']['cpu'] = "{0:.2f}".format(int(vmcfg['vcpus']))
else:
if vmcfg['cpu_cap'] != '':
ret[vm]['resources']['cpu'] = "{0:.2f}".format(int(vmcfg['cpu_cap'])/100)
else:
ret.append(vm)
except SaltClientError as client_error:
return "{0}".format(client_error)
if not verbose:
ret = sorted(ret)
return ret
def start(search, one=True):
'''
Start one or more vms
search : string
filter vms, see the execution module.
one : boolean
start only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.start 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.start search='alias=jiska'
salt-run vmadm.start search='type=KVM' one=False
'''
return _action('start', search, one)
def stop(search, one=True):
'''
Stop one or more vms
search : string
filter vms, see the execution module.
one : boolean
stop only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.stop 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.stop search='alias=jody'
salt-run vmadm.stop search='type=KVM' one=False
'''
return _action('stop', search, one)
def get(search, one=True):
'''
Return information for vms
search : string
filter vms, see the execution module.
one : boolean
return only one vm
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
CLI Example:
.. code-block:: bash
salt-run vmadm.get 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.get search='alias=saskia'
'''
return _action('get', search, one)
def is_running(search):
'''
Return true if vm is running
search : string
filter vms, see the execution module.
.. note::
If the search parameter does not contain an equal (=) symbol it will be
assumed it will be tried as uuid, hostname, and alias.
.. note::
If multiple vms are matched, the result will be true of ALL vms are running
CLI Example:
.. code-block:: bash
salt-run vmadm.is_running 91244bba-1146-e4ec-c07e-e825e0223aa9
salt-run vmadm.is_running search='alias=julia'
'''
return _action('is_running', search, False)
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt | salt/cloud/clouds/ec2.py | _xml_to_dict | python | def _xml_to_dict(xmltree):
'''
Convert an XML tree into a dict
'''
if sys.version_info < (2, 7):
children_len = len(xmltree.getchildren())
else:
children_len = len(xmltree)
if children_len < 1:
name = xmltree.tag
if '}' in name:
comps = name.split('}')
name = comps[1]
return {name: xmltree.text}
xmldict = {}
for item in xmltree:
name = item.tag
if '}' in name:
comps = name.split('}')
name = comps[1]
if name not in xmldict:
if sys.version_info < (2, 7):
children_len = len(item.getchildren())
else:
children_len = len(item)
if children_len > 0:
xmldict[name] = _xml_to_dict(item)
else:
xmldict[name] = item.text
else:
if not isinstance(xmldict[name], list):
tempvar = xmldict[name]
xmldict[name] = []
xmldict[name].append(tempvar)
xmldict[name].append(_xml_to_dict(item))
return xmldict | Convert an XML tree into a dict | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/ec2.py#L225-L263 | null | # -*- coding: utf-8 -*-
'''
The EC2 Cloud Module
====================
The EC2 cloud module is used to interact with the Amazon Elastic Compute Cloud.
To use the EC2 cloud module, set up the cloud configuration at
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/ec2.conf``:
.. code-block:: yaml
my-ec2-config:
# EC2 API credentials: Access Key ID and Secret Access Key.
# Alternatively, to use IAM Instance Role credentials available via
# EC2 metadata set both id and key to 'use-instance-role-credentials'
id: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# If 'role_arn' is specified the above credentials are used to
# to assume to the role. By default, role_arn is set to None.
role_arn: arn:aws:iam::012345678910:role/SomeRoleName
# The ssh keyname to use
keyname: default
# The amazon security group
securitygroup: ssh_open
# The location of the private key which corresponds to the keyname
private_key: /root/default.pem
# Be default, service_url is set to amazonaws.com. If you are using this
# driver for something other than Amazon EC2, change it here:
service_url: amazonaws.com
# The endpoint that is ultimately used is usually formed using the region
# and the service_url. If you would like to override that entirely, you
# can explicitly define the endpoint:
endpoint: myendpoint.example.com:1138/services/Cloud
# SSH Gateways can be used with this provider. Gateways can be used
# when a salt-master is not on the same private network as the instance
# that is being deployed.
# Defaults to None
# Required
ssh_gateway: gateway.example.com
# Defaults to port 22
# Optional
ssh_gateway_port: 22
# Defaults to root
# Optional
ssh_gateway_username: root
# Default to nc -q0 %h %p
# Optional
ssh_gateway_command: "-W %h:%p"
# One authentication method is required. If both
# are specified, Private key wins.
# Private key defaults to None
ssh_gateway_private_key: /path/to/key.pem
# Password defaults to None
ssh_gateway_password: ExamplePasswordHere
driver: ec2
# Pass userdata to the instance to be created
userdata_file: /etc/salt/my-userdata-file
# Instance termination protection setting
# Default is disabled
termination_protection: False
:depends: requests
'''
# pylint: disable=invalid-name,function-redefined
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import stat
import time
import uuid
import pprint
import logging
# Import libs for talking to the EC2 API
import hmac
import hashlib
import binascii
import datetime
import base64
import re
import decimal
# Import Salt Libs
import salt.utils.cloud
import salt.utils.compat
import salt.utils.files
import salt.utils.hashutils
import salt.utils.json
import salt.utils.msgpack
import salt.utils.stringutils
import salt.utils.yaml
from salt._compat import ElementTree as ET
import salt.utils.http as http
import salt.utils.aws as aws
import salt.config as config
from salt.exceptions import (
SaltCloudException,
SaltCloudSystemExit,
SaltCloudConfigError,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure
)
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, zip
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse, urlencode as _urlencode
# Import 3rd-Party Libs
# Try to import PyCrypto, which may not be installed on a RAET-based system
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
import Crypto
# PKCS1_v1_5 was added in PyCrypto 2.5
from Crypto.Cipher import PKCS1_v1_5 # pylint: disable=E0611
from Crypto.Hash import SHA # pylint: disable=E0611,W0611
HAS_PYCRYPTO = True
except ImportError:
HAS_PYCRYPTO = False
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# pylint: enable=import-error,no-name-in-module,redefined-builtin
# Get logging started
log = logging.getLogger(__name__)
EC2_LOCATIONS = {
'ap-northeast-1': 'ec2_ap_northeast',
'ap-northeast-2': 'ec2_ap_northeast_2',
'ap-southeast-1': 'ec2_ap_southeast',
'ap-southeast-2': 'ec2_ap_southeast_2',
'eu-west-1': 'ec2_eu_west',
'eu-central-1': 'ec2_eu_central',
'sa-east-1': 'ec2_sa_east',
'us-east-1': 'ec2_us_east',
'us-gov-west-1': 'ec2_us_gov_west_1',
'us-west-1': 'ec2_us_west',
'us-west-2': 'ec2_us_west_oregon',
}
DEFAULT_LOCATION = 'us-east-1'
DEFAULT_EC2_API_VERSION = '2014-10-01'
EC2_RETRY_CODES = [
'RequestLimitExceeded',
'InsufficientInstanceCapacity',
'InternalError',
'Unavailable',
'InsufficientAddressCapacity',
'InsufficientReservedInstanceCapacity',
]
JS_COMMENT_RE = re.compile(r'/\*.*?\*/', re.S)
__virtualname__ = 'ec2'
# Only load in this module if the EC2 configurations are in place
def __virtual__():
'''
Set up the libcloud functions and check for EC2 configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'requests': HAS_REQUESTS,
'pycrypto or m2crypto': HAS_M2 or HAS_PYCRYPTO
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def optimize_providers(providers):
'''
Return an optimized list of providers.
We want to reduce the duplication of querying
the same region.
If a provider is using the same credentials for the same region
the same data will be returned for each provider, thus causing
un-wanted duplicate data and API calls to EC2.
'''
tmp_providers = {}
optimized_providers = {}
for name, data in six.iteritems(providers):
if 'location' not in data:
data['location'] = DEFAULT_LOCATION
if data['location'] not in tmp_providers:
tmp_providers[data['location']] = {}
creds = (data['id'], data['key'])
if creds not in tmp_providers[data['location']]:
tmp_providers[data['location']][creds] = {'name': name,
'data': data,
}
for location, tmp_data in six.iteritems(tmp_providers):
for creds, data in six.iteritems(tmp_data):
_id, _key = creds
_name = data['name']
_data = data['data']
if _name not in optimized_providers:
optimized_providers[_name] = _data
return optimized_providers
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
def query(params=None, setname=None, requesturl=None, location=None,
return_url=False, return_root=False):
provider = get_configured_provider()
service_url = provider.get('service_url', 'amazonaws.com')
# Retrieve access credentials from meta-data, or use provided
access_key_id, secret_access_key, token = aws.creds(provider)
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
params_with_headers = params.copy()
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
if not location:
location = get_location()
if not requesturl:
endpoint = provider.get(
'endpoint',
'ec2.{0}.{1}'.format(location, service_url)
)
requesturl = 'https://{0}/'.format(endpoint)
endpoint = _urlparse(requesturl).netloc
endpoint_path = _urlparse(requesturl).path
else:
endpoint = _urlparse(requesturl).netloc
endpoint_path = _urlparse(requesturl).path
if endpoint == '':
endpoint_err = (
'Could not find a valid endpoint in the '
'requesturl: {0}. Looking for something '
'like https://some.ec2.endpoint/?args').format(requesturl)
log.error(endpoint_err)
if return_url is True:
return {'error': endpoint_err}, requesturl
return {'error': endpoint_err}
log.debug('Using EC2 endpoint: %s', endpoint)
# AWS v4 signature
method = 'GET'
region = location
service = 'ec2'
canonical_uri = _urlparse(requesturl).path
host = endpoint.strip()
# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ') # Format date as YYYYMMDD'T'HHMMSS'Z'
datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'
signed_headers = 'host;x-amz-date'
payload_hash = salt.utils.hashutils.sha256_digest('')
ec2_api_version = provider.get(
'ec2_api_version',
DEFAULT_EC2_API_VERSION
)
params_with_headers['Version'] = ec2_api_version
keys = sorted(list(params_with_headers))
values = map(params_with_headers.get, keys)
querystring = _urlencode(list(zip(keys, values)))
querystring = querystring.replace('+', '%20')
canonical_request = method + '\n' + canonical_uri + '\n' + \
querystring + '\n' + canonical_headers + '\n' + \
signed_headers + '\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amz_date + '\n' + \
credential_scope + '\n' + \
salt.utils.hashutils.sha256_digest(canonical_request)
kDate = sign(('AWS4' + provider['key']).encode('utf-8'), datestamp)
kRegion = sign(kDate, region)
kService = sign(kRegion, service)
signing_key = sign(kService, 'aws4_request')
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'),
hashlib.sha256).hexdigest()
authorization_header = algorithm + ' ' + 'Credential=' + \
provider['id'] + '/' + credential_scope + \
', ' + 'SignedHeaders=' + signed_headers + \
', ' + 'Signature=' + signature
headers = {'x-amz-date': amz_date, 'Authorization': authorization_header}
log.debug('EC2 Request: %s', requesturl)
log.trace('EC2 Request Parameters: %s', params_with_headers)
try:
result = requests.get(requesturl, headers=headers, params=params_with_headers)
log.debug(
'EC2 Response Status Code: %s',
# result.getcode()
result.status_code
)
log.trace('EC2 Response Text: %s', result.text)
result.raise_for_status()
break
except requests.exceptions.HTTPError as exc:
root = ET.fromstring(exc.response.content)
data = _xml_to_dict(root)
# check to see if we should retry the query
err_code = data.get('Errors', {}).get('Error', {}).get('Code', '')
if err_code and err_code in EC2_RETRY_CODES:
attempts += 1
log.error(
'EC2 Response Status Code and Error: [%s %s] %s; '
'Attempts remaining: %s',
exc.response.status_code, exc, data, attempts
)
aws.sleep_exponential_backoff(attempts)
continue
log.error(
'EC2 Response Status Code and Error: [%s %s] %s',
exc.response.status_code, exc, data
)
if return_url is True:
return {'error': data}, requesturl
return {'error': data}
else:
log.error(
'EC2 Response Status Code and Error: [%s %s] %s',
exc.response.status_code, exc, data
)
if return_url is True:
return {'error': data}, requesturl
return {'error': data}
response = result.text
root = ET.fromstring(response)
items = root[1]
if return_root is True:
items = root
if setname:
if sys.version_info < (2, 7):
children_len = len(root.getchildren())
else:
children_len = len(root)
for item in range(0, children_len):
comps = root[item].tag.split('}')
if comps[1] == setname:
items = root[item]
ret = []
for item in items:
ret.append(_xml_to_dict(item))
if return_url is True:
return ret, requesturl
return ret
def _wait_for_spot_instance(update_callback,
update_args=None,
update_kwargs=None,
timeout=10 * 60,
interval=30,
interval_multiplier=1,
max_failures=10):
'''
Helper function that waits for a spot instance request to become active
for a specific maximum amount of time.
:param update_callback: callback function which queries the cloud provider
for spot instance request. It must return None if
the required data, running instance included, is
not available yet.
:param update_args: Arguments to pass to update_callback
:param update_kwargs: Keyword arguments to pass to update_callback
:param timeout: The maximum amount of time(in seconds) to wait for the IP
address.
:param interval: The looping interval, i.e., the amount of time to sleep
before the next iteration.
:param interval_multiplier: Increase the interval by this multiplier after
each request; helps with throttling
:param max_failures: If update_callback returns ``False`` it's considered
query failure. This value is the amount of failures
accepted before giving up.
:returns: The update_callback returned data
:raises: SaltCloudExecutionTimeout
'''
if update_args is None:
update_args = ()
if update_kwargs is None:
update_kwargs = {}
duration = timeout
while True:
log.debug(
'Waiting for spot instance reservation. Giving up in '
'00:%02d:%02d', int(timeout // 60), int(timeout % 60)
)
data = update_callback(*update_args, **update_kwargs)
if data is False:
log.debug(
'update_callback has returned False which is considered a '
'failure. Remaining Failures: %s', max_failures
)
max_failures -= 1
if max_failures <= 0:
raise SaltCloudExecutionFailure(
'Too many failures occurred while waiting for '
'the spot instance reservation to become active.'
)
elif data is not None:
return data
if timeout < 0:
raise SaltCloudExecutionTimeout(
'Unable to get an active spot instance request for '
'00:{0:02d}:{1:02d}'.format(
int(duration // 60),
int(duration % 60)
)
)
time.sleep(interval)
timeout -= interval
if interval_multiplier > 1:
interval *= interval_multiplier
if interval > timeout:
interval = timeout + 1
log.info('Interval multiplier in effect; interval is '
'now %ss', interval)
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. Latest version can be found at:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
sizes = {
'Cluster Compute': {
'cc2.8xlarge': {
'id': 'cc2.8xlarge',
'cores': '16 (2 x Intel Xeon E5-2670, eight-core with '
'hyperthread)',
'disk': '3360 GiB (4 x 840 GiB)',
'ram': '60.5 GiB'
},
'cc1.4xlarge': {
'id': 'cc1.4xlarge',
'cores': '8 (2 x Intel Xeon X5570, quad-core with '
'hyperthread)',
'disk': '1690 GiB (2 x 840 GiB)',
'ram': '22.5 GiB'
},
},
'Cluster CPU': {
'cg1.4xlarge': {
'id': 'cg1.4xlarge',
'cores': '8 (2 x Intel Xeon X5570, quad-core with '
'hyperthread), plus 2 NVIDIA Tesla M2050 GPUs',
'disk': '1680 GiB (2 x 840 GiB)',
'ram': '22.5 GiB'
},
},
'Compute Optimized': {
'c4.large': {
'id': 'c4.large',
'cores': '2',
'disk': 'EBS - 500 Mbps',
'ram': '3.75 GiB'
},
'c4.xlarge': {
'id': 'c4.xlarge',
'cores': '4',
'disk': 'EBS - 750 Mbps',
'ram': '7.5 GiB'
},
'c4.2xlarge': {
'id': 'c4.2xlarge',
'cores': '8',
'disk': 'EBS - 1000 Mbps',
'ram': '15 GiB'
},
'c4.4xlarge': {
'id': 'c4.4xlarge',
'cores': '16',
'disk': 'EBS - 2000 Mbps',
'ram': '30 GiB'
},
'c4.8xlarge': {
'id': 'c4.8xlarge',
'cores': '36',
'disk': 'EBS - 4000 Mbps',
'ram': '60 GiB'
},
'c3.large': {
'id': 'c3.large',
'cores': '2',
'disk': '32 GiB (2 x 16 GiB SSD)',
'ram': '3.75 GiB'
},
'c3.xlarge': {
'id': 'c3.xlarge',
'cores': '4',
'disk': '80 GiB (2 x 40 GiB SSD)',
'ram': '7.5 GiB'
},
'c3.2xlarge': {
'id': 'c3.2xlarge',
'cores': '8',
'disk': '160 GiB (2 x 80 GiB SSD)',
'ram': '15 GiB'
},
'c3.4xlarge': {
'id': 'c3.4xlarge',
'cores': '16',
'disk': '320 GiB (2 x 160 GiB SSD)',
'ram': '30 GiB'
},
'c3.8xlarge': {
'id': 'c3.8xlarge',
'cores': '32',
'disk': '640 GiB (2 x 320 GiB SSD)',
'ram': '60 GiB'
}
},
'Dense Storage': {
'd2.xlarge': {
'id': 'd2.xlarge',
'cores': '4',
'disk': '6 TiB (3 x 2 TiB hard disk drives)',
'ram': '30.5 GiB'
},
'd2.2xlarge': {
'id': 'd2.2xlarge',
'cores': '8',
'disk': '12 TiB (6 x 2 TiB hard disk drives)',
'ram': '61 GiB'
},
'd2.4xlarge': {
'id': 'd2.4xlarge',
'cores': '16',
'disk': '24 TiB (12 x 2 TiB hard disk drives)',
'ram': '122 GiB'
},
'd2.8xlarge': {
'id': 'd2.8xlarge',
'cores': '36',
'disk': '24 TiB (24 x 2 TiB hard disk drives)',
'ram': '244 GiB'
},
},
'GPU': {
'g2.2xlarge': {
'id': 'g2.2xlarge',
'cores': '8',
'disk': '60 GiB (1 x 60 GiB SSD)',
'ram': '15 GiB'
},
'g2.8xlarge': {
'id': 'g2.8xlarge',
'cores': '32',
'disk': '240 GiB (2 x 120 GiB SSD)',
'ram': '60 GiB'
},
},
'GPU Compute': {
'p2.xlarge': {
'id': 'p2.xlarge',
'cores': '4',
'disk': 'EBS',
'ram': '61 GiB'
},
'p2.8xlarge': {
'id': 'p2.8xlarge',
'cores': '32',
'disk': 'EBS',
'ram': '488 GiB'
},
'p2.16xlarge': {
'id': 'p2.16xlarge',
'cores': '64',
'disk': 'EBS',
'ram': '732 GiB'
},
},
'High I/O': {
'i2.xlarge': {
'id': 'i2.xlarge',
'cores': '4',
'disk': 'SSD (1 x 800 GiB)',
'ram': '30.5 GiB'
},
'i2.2xlarge': {
'id': 'i2.2xlarge',
'cores': '8',
'disk': 'SSD (2 x 800 GiB)',
'ram': '61 GiB'
},
'i2.4xlarge': {
'id': 'i2.4xlarge',
'cores': '16',
'disk': 'SSD (4 x 800 GiB)',
'ram': '122 GiB'
},
'i2.8xlarge': {
'id': 'i2.8xlarge',
'cores': '32',
'disk': 'SSD (8 x 800 GiB)',
'ram': '244 GiB'
}
},
'High Memory': {
'x1.16xlarge': {
'id': 'x1.16xlarge',
'cores': '64 (with 5.45 ECUs each)',
'disk': '1920 GiB (1 x 1920 GiB)',
'ram': '976 GiB'
},
'x1.32xlarge': {
'id': 'x1.32xlarge',
'cores': '128 (with 2.73 ECUs each)',
'disk': '3840 GiB (2 x 1920 GiB)',
'ram': '1952 GiB'
},
'r4.large': {
'id': 'r4.large',
'cores': '2 (with 3.45 ECUs each)',
'disk': 'EBS',
'ram': '15.25 GiB'
},
'r4.xlarge': {
'id': 'r4.xlarge',
'cores': '4 (with 3.35 ECUs each)',
'disk': 'EBS',
'ram': '30.5 GiB'
},
'r4.2xlarge': {
'id': 'r4.2xlarge',
'cores': '8 (with 3.35 ECUs each)',
'disk': 'EBS',
'ram': '61 GiB'
},
'r4.4xlarge': {
'id': 'r4.4xlarge',
'cores': '16 (with 3.3 ECUs each)',
'disk': 'EBS',
'ram': '122 GiB'
},
'r4.8xlarge': {
'id': 'r4.8xlarge',
'cores': '32 (with 3.1 ECUs each)',
'disk': 'EBS',
'ram': '244 GiB'
},
'r4.16xlarge': {
'id': 'r4.16xlarge',
'cores': '64 (with 3.05 ECUs each)',
'disk': 'EBS',
'ram': '488 GiB'
},
'r3.large': {
'id': 'r3.large',
'cores': '2 (with 3.25 ECUs each)',
'disk': '32 GiB (1 x 32 GiB SSD)',
'ram': '15 GiB'
},
'r3.xlarge': {
'id': 'r3.xlarge',
'cores': '4 (with 3.25 ECUs each)',
'disk': '80 GiB (1 x 80 GiB SSD)',
'ram': '30.5 GiB'
},
'r3.2xlarge': {
'id': 'r3.2xlarge',
'cores': '8 (with 3.25 ECUs each)',
'disk': '160 GiB (1 x 160 GiB SSD)',
'ram': '61 GiB'
},
'r3.4xlarge': {
'id': 'r3.4xlarge',
'cores': '16 (with 3.25 ECUs each)',
'disk': '320 GiB (1 x 320 GiB SSD)',
'ram': '122 GiB'
},
'r3.8xlarge': {
'id': 'r3.8xlarge',
'cores': '32 (with 3.25 ECUs each)',
'disk': '640 GiB (2 x 320 GiB SSD)',
'ram': '244 GiB'
}
},
'High-Memory Cluster': {
'cr1.8xlarge': {
'id': 'cr1.8xlarge',
'cores': '16 (2 x Intel Xeon E5-2670, eight-core)',
'disk': '240 GiB (2 x 120 GiB SSD)',
'ram': '244 GiB'
},
},
'High Storage': {
'hs1.8xlarge': {
'id': 'hs1.8xlarge',
'cores': '16 (8 cores + 8 hyperthreads)',
'disk': '48 TiB (24 x 2 TiB hard disk drives)',
'ram': '117 GiB'
},
},
'General Purpose': {
't2.nano': {
'id': 't2.nano',
'cores': '1',
'disk': 'EBS',
'ram': '512 MiB'
},
't2.micro': {
'id': 't2.micro',
'cores': '1',
'disk': 'EBS',
'ram': '1 GiB'
},
't2.small': {
'id': 't2.small',
'cores': '1',
'disk': 'EBS',
'ram': '2 GiB'
},
't2.medium': {
'id': 't2.medium',
'cores': '2',
'disk': 'EBS',
'ram': '4 GiB'
},
't2.large': {
'id': 't2.large',
'cores': '2',
'disk': 'EBS',
'ram': '8 GiB'
},
't2.xlarge': {
'id': 't2.xlarge',
'cores': '4',
'disk': 'EBS',
'ram': '16 GiB'
},
't2.2xlarge': {
'id': 't2.2xlarge',
'cores': '8',
'disk': 'EBS',
'ram': '32 GiB'
},
'm4.large': {
'id': 'm4.large',
'cores': '2',
'disk': 'EBS - 450 Mbps',
'ram': '8 GiB'
},
'm4.xlarge': {
'id': 'm4.xlarge',
'cores': '4',
'disk': 'EBS - 750 Mbps',
'ram': '16 GiB'
},
'm4.2xlarge': {
'id': 'm4.2xlarge',
'cores': '8',
'disk': 'EBS - 1000 Mbps',
'ram': '32 GiB'
},
'm4.4xlarge': {
'id': 'm4.4xlarge',
'cores': '16',
'disk': 'EBS - 2000 Mbps',
'ram': '64 GiB'
},
'm4.10xlarge': {
'id': 'm4.10xlarge',
'cores': '40',
'disk': 'EBS - 4000 Mbps',
'ram': '160 GiB'
},
'm4.16xlarge': {
'id': 'm4.16xlarge',
'cores': '64',
'disk': 'EBS - 10000 Mbps',
'ram': '256 GiB'
},
'm3.medium': {
'id': 'm3.medium',
'cores': '1',
'disk': 'SSD (1 x 4)',
'ram': '3.75 GiB'
},
'm3.large': {
'id': 'm3.large',
'cores': '2',
'disk': 'SSD (1 x 32)',
'ram': '7.5 GiB'
},
'm3.xlarge': {
'id': 'm3.xlarge',
'cores': '4',
'disk': 'SSD (2 x 40)',
'ram': '15 GiB'
},
'm3.2xlarge': {
'id': 'm3.2xlarge',
'cores': '8',
'disk': 'SSD (2 x 80)',
'ram': '30 GiB'
},
}
}
return sizes
def avail_images(kwargs=None, 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'
)
if not isinstance(kwargs, dict):
kwargs = {}
if 'owner' in kwargs:
owner = kwargs['owner']
else:
provider = get_configured_provider()
owner = config.get_cloud_config_value(
'owner', provider, __opts__, default='amazon'
)
ret = {}
params = {'Action': 'DescribeImages',
'Owner': owner}
images = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
for image in images:
ret[image['imageId']] = image
return ret
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def keyname(vm_):
'''
Return the keyname
'''
return config.get_cloud_config_value(
'keyname', vm_, __opts__, search_global=False
)
def securitygroup(vm_):
'''
Return the security group
'''
return config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
def iam_profile(vm_):
'''
Return the IAM profile.
The IAM instance profile to associate with the instances.
This is either the Amazon Resource Name (ARN) of the instance profile
or the name of the role.
Type: String
Default: None
Required: No
Example: arn:aws:iam::111111111111:instance-profile/s3access
Example: s3access
'''
return config.get_cloud_config_value(
'iam_profile', vm_, __opts__, search_global=False
)
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
ret = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, default='public_ips',
search_global=False
)
if ret not in ('public_ips', 'private_ips'):
log.warning(
'Invalid ssh_interface: %s. '
'Allowed options are ("public_ips", "private_ips"). '
'Defaulting to "public_ips".', ret
)
ret = 'public_ips'
return ret
def get_ssh_gateway_config(vm_):
'''
Return the ssh_gateway configuration.
'''
ssh_gateway = config.get_cloud_config_value(
'ssh_gateway', vm_, __opts__, default=None,
search_global=False
)
# Check to see if a SSH Gateway will be used.
if not isinstance(ssh_gateway, six.string_types):
return None
# Create dictionary of configuration items
# ssh_gateway
ssh_gateway_config = {'ssh_gateway': ssh_gateway}
# ssh_gateway_port
ssh_gateway_config['ssh_gateway_port'] = config.get_cloud_config_value(
'ssh_gateway_port', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_username
ssh_gateway_config['ssh_gateway_user'] = config.get_cloud_config_value(
'ssh_gateway_username', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_private_key
ssh_gateway_config['ssh_gateway_key'] = config.get_cloud_config_value(
'ssh_gateway_private_key', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_password
ssh_gateway_config['ssh_gateway_password'] = config.get_cloud_config_value(
'ssh_gateway_password', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_command
ssh_gateway_config['ssh_gateway_command'] = config.get_cloud_config_value(
'ssh_gateway_command', vm_, __opts__, default=None,
search_global=False
)
# Check if private key exists
key_filename = ssh_gateway_config['ssh_gateway_key']
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_gateway_private_key \'{0}\' does not exist'
.format(key_filename)
)
elif (
key_filename is None and
not ssh_gateway_config['ssh_gateway_password']
):
raise SaltCloudConfigError(
'No authentication method. Please define: '
' ssh_gateway_password or ssh_gateway_private_key'
)
return ssh_gateway_config
def get_location(vm_=None):
'''
Return the EC2 region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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 = {}
params = {'Action': 'DescribeRegions'}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
for region in result:
ret[region['regionName']] = {
'name': region['regionName'],
'endpoint': region['regionEndpoint'],
}
return ret
def get_availability_zone(vm_):
'''
Return the availability zone to use
'''
avz = config.get_cloud_config_value(
'availability_zone', vm_, __opts__, search_global=False
)
if avz is None:
return None
zones = _list_availability_zones(vm_)
# Validate user-specified AZ
if avz not in zones:
raise SaltCloudException(
'The specified availability zone isn\'t valid in this region: '
'{0}\n'.format(
avz
)
)
# check specified AZ is available
elif zones[avz] != 'available':
raise SaltCloudException(
'The specified availability zone isn\'t currently available: '
'{0}\n'.format(
avz
)
)
return avz
def get_tenancy(vm_):
'''
Returns the Tenancy to use.
Can be "dedicated" or "default". Cannot be present for spot instances.
'''
return config.get_cloud_config_value(
'tenancy', vm_, __opts__, search_global=False
)
def get_imageid(vm_):
'''
Returns the ImageId to use
'''
image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if image.startswith('ami-'):
return image
# a poor man's cache
if not hasattr(get_imageid, 'images'):
get_imageid.images = {}
elif image in get_imageid.images:
return get_imageid.images[image]
params = {'Action': 'DescribeImages',
'Filter.0.Name': 'name',
'Filter.0.Value.0': image}
# Query AWS, sort by 'creationDate' and get the last imageId
_t = lambda x: datetime.datetime.strptime(x['creationDate'], '%Y-%m-%dT%H:%M:%S.%fZ')
image_id = sorted(aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'),
lambda i, j: salt.utils.compat.cmp(_t(i), _t(j))
)[-1]['imageId']
get_imageid.images[image] = image_id
return image_id
def _get_subnetname_id(subnetname):
'''
Returns the SubnetId of a SubnetName to use
'''
params = {'Action': 'DescribeSubnets'}
for subnet in aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'):
tags = subnet.get('tagSet', {}).get('item', {})
if not isinstance(tags, list):
tags = [tags]
for tag in tags:
if tag['key'] == 'Name' and tag['value'] == subnetname:
log.debug(
'AWS Subnet ID of %s is %s',
subnetname, subnet['subnetId']
)
return subnet['subnetId']
return None
def get_subnetid(vm_):
'''
Returns the SubnetId to use
'''
subnetid = config.get_cloud_config_value(
'subnetid', vm_, __opts__, search_global=False
)
if subnetid:
return subnetid
subnetname = config.get_cloud_config_value(
'subnetname', vm_, __opts__, search_global=False
)
if subnetname:
return _get_subnetname_id(subnetname)
return None
def _get_securitygroupname_id(securitygroupname_list):
'''
Returns the SecurityGroupId of a SecurityGroupName to use
'''
securitygroupid_set = set()
if not isinstance(securitygroupname_list, list):
securitygroupname_list = [securitygroupname_list]
params = {'Action': 'DescribeSecurityGroups'}
for sg in aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'):
if sg['groupName'] in securitygroupname_list:
log.debug(
'AWS SecurityGroup ID of %s is %s',
sg['groupName'], sg['groupId']
)
securitygroupid_set.add(sg['groupId'])
return list(securitygroupid_set)
def securitygroupid(vm_):
'''
Returns the SecurityGroupId
'''
securitygroupid_set = set()
securitygroupid_list = config.get_cloud_config_value(
'securitygroupid',
vm_,
__opts__,
search_global=False
)
# If the list is None, then the set will remain empty
# If the list is already a set then calling 'set' on it is a no-op
# If the list is a string, then calling 'set' generates a one-element set
# If the list is anything else, stacktrace
if securitygroupid_list:
securitygroupid_set = securitygroupid_set.union(set(securitygroupid_list))
securitygroupname_list = config.get_cloud_config_value(
'securitygroupname', vm_, __opts__, search_global=False
)
if securitygroupname_list:
if not isinstance(securitygroupname_list, list):
securitygroupname_list = [securitygroupname_list]
params = {'Action': 'DescribeSecurityGroups'}
for sg in aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'):
if sg['groupName'] in securitygroupname_list:
log.debug(
'AWS SecurityGroup ID of %s is %s',
sg['groupName'], sg['groupId']
)
securitygroupid_set.add(sg['groupId'])
return list(securitygroupid_set)
def get_placementgroup(vm_):
'''
Returns the PlacementGroup to use
'''
return config.get_cloud_config_value(
'placementgroup', vm_, __opts__, search_global=False
)
def get_spot_config(vm_):
'''
Returns the spot instance configuration for the provided vm
'''
return config.get_cloud_config_value(
'spot_config', vm_, __opts__, search_global=False
)
def get_provider(vm_=None):
'''
Extract the provider name from vm
'''
if vm_ is None:
provider = __active_provider_name__ or 'ec2'
else:
provider = vm_.get('provider', 'ec2')
if ':' in provider:
prov_comps = provider.split(':')
provider = prov_comps[0]
return provider
def _list_availability_zones(vm_=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeAvailabilityZones',
'Filter.0.Name': 'region-name',
'Filter.0.Value.0': get_location(vm_)}
result = aws.query(params,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
for zone in result:
ret[zone['zoneName']] = zone['zoneState']
return ret
def block_device_mappings(vm_):
'''
Return the block device mapping:
.. code-block:: python
[{'DeviceName': '/dev/sdb', 'VirtualName': 'ephemeral0'},
{'DeviceName': '/dev/sdc', 'VirtualName': 'ephemeral1'}]
'''
return config.get_cloud_config_value(
'block_device_mappings', vm_, __opts__, search_global=True
)
def _request_eip(interface, vm_):
'''
Request and return Elastic IP
'''
params = {'Action': 'AllocateAddress'}
params['Domain'] = interface.setdefault('domain', 'vpc')
eips = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
for eip in eips:
if 'allocationId' in eip:
return eip['allocationId']
return None
def _create_eni_if_necessary(interface, vm_):
'''
Create an Elastic Interface if necessary and return a Network Interface Specification
'''
if 'NetworkInterfaceId' in interface and interface['NetworkInterfaceId'] is not None:
return {'DeviceIndex': interface['DeviceIndex'],
'NetworkInterfaceId': interface['NetworkInterfaceId']}
params = {'Action': 'DescribeSubnets'}
subnet_query = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'SecurityGroupId' not in interface and 'securitygroupname' in interface:
interface['SecurityGroupId'] = _get_securitygroupname_id(interface['securitygroupname'])
if 'SubnetId' not in interface and 'subnetname' in interface:
interface['SubnetId'] = _get_subnetname_id(interface['subnetname'])
subnet_id = _get_subnet_id_for_interface(subnet_query, interface)
if not subnet_id:
raise SaltCloudConfigError(
'No such subnet <{0}>'.format(interface.get('SubnetId'))
)
params = {'SubnetId': subnet_id}
for k in 'Description', 'PrivateIpAddress', 'SecondaryPrivateIpAddressCount':
if k in interface:
params[k] = interface[k]
for k in 'PrivateIpAddresses', 'SecurityGroupId':
if k in interface:
params.update(_param_from_config(k, interface[k]))
if 'AssociatePublicIpAddress' in interface:
# Associating a public address in a VPC only works when the interface is not
# created beforehand, but as a part of the machine creation request.
for k in ('DeviceIndex', 'AssociatePublicIpAddress', 'NetworkInterfaceId'):
if k in interface:
params[k] = interface[k]
params['DeleteOnTermination'] = interface.get('delete_interface_on_terminate', True)
return params
params['Action'] = 'CreateNetworkInterface'
result = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
eni_desc = result[1]
if not eni_desc or not eni_desc.get('networkInterfaceId'):
raise SaltCloudException('Failed to create interface: {0}'.format(result))
eni_id = eni_desc.get('networkInterfaceId')
log.debug(
'Created network interface %s inst %s',
eni_id, interface['DeviceIndex']
)
associate_public_ip = interface.get('AssociatePublicIpAddress', False)
if isinstance(associate_public_ip, six.string_types):
# Assume id of EIP as value
_associate_eip_with_interface(eni_id, associate_public_ip, vm_=vm_)
if interface.get('associate_eip'):
_associate_eip_with_interface(eni_id, interface.get('associate_eip'), vm_=vm_)
elif interface.get('allocate_new_eip'):
_new_eip = _request_eip(interface, vm_)
_associate_eip_with_interface(eni_id, _new_eip, vm_=vm_)
elif interface.get('allocate_new_eips'):
addr_list = _list_interface_private_addrs(eni_desc)
eip_list = []
for idx, addr in enumerate(addr_list):
eip_list.append(_request_eip(interface, vm_))
for idx, addr in enumerate(addr_list):
_associate_eip_with_interface(eni_id, eip_list[idx], addr, vm_=vm_)
if 'Name' in interface:
tag_params = {'Action': 'CreateTags',
'ResourceId.0': eni_id,
'Tag.0.Key': 'Name',
'Tag.0.Value': interface['Name']}
tag_response = aws.query(tag_params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'error' in tag_response:
log.error('Failed to set name of interface {0}')
return {'DeviceIndex': interface['DeviceIndex'],
'NetworkInterfaceId': eni_id}
def _get_subnet_id_for_interface(subnet_query, interface):
for subnet_query_result in subnet_query:
if 'item' in subnet_query_result:
if isinstance(subnet_query_result['item'], dict):
subnet_id = _get_subnet_from_subnet_query(subnet_query_result['item'],
interface)
if subnet_id is not None:
return subnet_id
else:
for subnet in subnet_query_result['item']:
subnet_id = _get_subnet_from_subnet_query(subnet, interface)
if subnet_id is not None:
return subnet_id
def _get_subnet_from_subnet_query(subnet_query, interface):
if 'subnetId' in subnet_query:
if interface.get('SubnetId'):
if subnet_query['subnetId'] == interface['SubnetId']:
return subnet_query['subnetId']
else:
return subnet_query['subnetId']
def _list_interface_private_addrs(eni_desc):
'''
Returns a list of all of the private IP addresses attached to a
network interface. The 'primary' address will be listed first.
'''
primary = eni_desc.get('privateIpAddress')
if not primary:
return None
addresses = [primary]
lst = eni_desc.get('privateIpAddressesSet', {}).get('item', [])
if not isinstance(lst, list):
return addresses
for entry in lst:
if entry.get('primary') == 'true':
continue
if entry.get('privateIpAddress'):
addresses.append(entry.get('privateIpAddress'))
return addresses
def _modify_eni_properties(eni_id, properties=None, vm_=None):
'''
Change properties of the interface
with id eni_id to the values in properties dict
'''
if not isinstance(properties, dict):
raise SaltCloudException(
'ENI properties must be a dictionary'
)
params = {'Action': 'ModifyNetworkInterfaceAttribute',
'NetworkInterfaceId': eni_id}
for k, v in six.iteritems(properties):
params[k] = v
result = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if isinstance(result, dict) and result.get('error'):
raise SaltCloudException(
'Could not change interface <{0}> attributes <\'{1}\'>'.format(
eni_id, properties
)
)
else:
return result
def _associate_eip_with_interface(eni_id, eip_id, private_ip=None, vm_=None):
'''
Accept the id of a network interface, and the id of an elastic ip
address, and associate the two of them, such that traffic sent to the
elastic ip address will be forwarded (NATted) to this network interface.
Optionally specify the private (10.x.x.x) IP address that traffic should
be NATted to - useful if you have multiple IP addresses assigned to an
interface.
'''
params = {'Action': 'AssociateAddress',
'NetworkInterfaceId': eni_id,
'AllocationId': eip_id}
if private_ip:
params['PrivateIpAddress'] = private_ip
result = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if not result[2].get('associationId'):
raise SaltCloudException(
'Could not associate elastic ip address '
'<{0}> with network interface <{1}>'.format(
eip_id, eni_id
)
)
log.debug(
'Associated ElasticIP address %s with interface %s',
eip_id, eni_id
)
return result[2].get('associationId')
def _update_enis(interfaces, instance, vm_=None):
config_enis = {}
instance_enis = []
for interface in interfaces:
if 'DeviceIndex' in interface:
if interface['DeviceIndex'] in config_enis:
log.error(
'Duplicate DeviceIndex in profile. Cannot update ENIs.'
)
return None
config_enis[six.text_type(interface['DeviceIndex'])] = interface
query_enis = instance[0]['instancesSet']['item']['networkInterfaceSet']['item']
if isinstance(query_enis, list):
for query_eni in query_enis:
instance_enis.append((query_eni['networkInterfaceId'], query_eni['attachment']))
else:
instance_enis.append((query_enis['networkInterfaceId'], query_enis['attachment']))
for eni_id, eni_data in instance_enis:
delete_on_terminate = True
if 'DeleteOnTermination' in config_enis[eni_data['deviceIndex']]:
delete_on_terminate = config_enis[eni_data['deviceIndex']]['DeleteOnTermination']
elif 'delete_interface_on_terminate' in config_enis[eni_data['deviceIndex']]:
delete_on_terminate = config_enis[eni_data['deviceIndex']]['delete_interface_on_terminate']
params_attachment = {'Attachment.AttachmentId': eni_data['attachmentId'],
'Attachment.DeleteOnTermination': delete_on_terminate}
set_eni_attachment_attributes = _modify_eni_properties(eni_id, params_attachment, vm_=vm_)
if 'SourceDestCheck' in config_enis[eni_data['deviceIndex']]:
params_sourcedest = {'SourceDestCheck.Value': config_enis[eni_data['deviceIndex']]['SourceDestCheck']}
set_eni_sourcedest_property = _modify_eni_properties(eni_id, params_sourcedest, vm_=vm_)
return None
def _param_from_config(key, data):
'''
Return EC2 API parameters based on the given config data.
Examples:
1. List of dictionaries
>>> data = [
... {'DeviceIndex': 0, 'SubnetId': 'subid0',
... 'AssociatePublicIpAddress': True},
... {'DeviceIndex': 1,
... 'SubnetId': 'subid1',
... 'PrivateIpAddress': '192.168.1.128'}
... ]
>>> _param_from_config('NetworkInterface', data)
... {'NetworkInterface.0.SubnetId': 'subid0',
... 'NetworkInterface.0.DeviceIndex': 0,
... 'NetworkInterface.1.SubnetId': 'subid1',
... 'NetworkInterface.1.PrivateIpAddress': '192.168.1.128',
... 'NetworkInterface.0.AssociatePublicIpAddress': 'true',
... 'NetworkInterface.1.DeviceIndex': 1}
2. List of nested dictionaries
>>> data = [
... {'DeviceName': '/dev/sdf',
... 'Ebs': {
... 'SnapshotId': 'dummy0',
... 'VolumeSize': 200,
... 'VolumeType': 'standard'}},
... {'DeviceName': '/dev/sdg',
... 'Ebs': {
... 'SnapshotId': 'dummy1',
... 'VolumeSize': 100,
... 'VolumeType': 'standard'}}
... ]
>>> _param_from_config('BlockDeviceMapping', data)
... {'BlockDeviceMapping.0.Ebs.VolumeType': 'standard',
... 'BlockDeviceMapping.1.Ebs.SnapshotId': 'dummy1',
... 'BlockDeviceMapping.0.Ebs.VolumeSize': 200,
... 'BlockDeviceMapping.0.Ebs.SnapshotId': 'dummy0',
... 'BlockDeviceMapping.1.Ebs.VolumeType': 'standard',
... 'BlockDeviceMapping.1.DeviceName': '/dev/sdg',
... 'BlockDeviceMapping.1.Ebs.VolumeSize': 100,
... 'BlockDeviceMapping.0.DeviceName': '/dev/sdf'}
3. Dictionary of dictionaries
>>> data = { 'Arn': 'dummyarn', 'Name': 'Tester' }
>>> _param_from_config('IamInstanceProfile', data)
{'IamInstanceProfile.Arn': 'dummyarn', 'IamInstanceProfile.Name': 'Tester'}
'''
param = {}
if isinstance(data, dict):
for k, v in six.iteritems(data):
param.update(_param_from_config('{0}.{1}'.format(key, k), v))
elif isinstance(data, list) or isinstance(data, tuple):
for idx, conf_item in enumerate(data):
prefix = '{0}.{1}'.format(key, idx)
param.update(_param_from_config(prefix, conf_item))
else:
if isinstance(data, bool):
# convert boolean True/False to 'true'/'false'
param.update({key: six.text_type(data).lower()})
else:
param.update({key: data})
return param
def request_instance(vm_=None, call=None):
'''
Put together all of the information necessary to request an instance on EC2,
and then fire off the request the instance.
Returns data about the instance
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
location = vm_.get('location', get_location(vm_))
# do we launch a regular vm or a spot instance?
# see http://goo.gl/hYZ13f for more information on EC2 API
spot_config = get_spot_config(vm_)
if spot_config is not None:
if 'spot_price' not in spot_config:
raise SaltCloudSystemExit(
'Spot instance config for {0} requires a spot_price '
'attribute.'.format(vm_['name'])
)
params = {'Action': 'RequestSpotInstances',
'InstanceCount': '1',
'Type': spot_config['type']
if 'type' in spot_config else 'one-time',
'SpotPrice': spot_config['spot_price']}
# All of the necessary launch parameters for a VM when using
# spot instances are the same except for the prefix below
# being tacked on.
spot_prefix = 'LaunchSpecification.'
# regular EC2 instance
else:
# WARNING! EXPERIMENTAL!
# This allows more than one instance to be spun up in a single call.
# The first instance will be called by the name provided, but all other
# instances will be nameless (or more specifically, they will use the
# InstanceId as the name). This interface is expected to change, so
# use at your own risk.
min_instance = config.get_cloud_config_value(
'min_instance', vm_, __opts__, search_global=False, default=1
)
max_instance = config.get_cloud_config_value(
'max_instance', vm_, __opts__, search_global=False, default=1
)
params = {'Action': 'RunInstances',
'MinCount': min_instance,
'MaxCount': max_instance}
# Normal instances should have no prefix.
spot_prefix = ''
image_id = get_imageid(vm_)
params[spot_prefix + 'ImageId'] = image_id
userdata = None
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is None:
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
else:
log.trace('userdata_file: %s', userdata_file)
if os.path.exists(userdata_file):
with salt.utils.files.fopen(userdata_file, 'r') as fh_:
userdata = salt.utils.stringutils.to_unicode(fh_.read())
userdata = salt.utils.cloud.userdata_template(__opts__, vm_, userdata)
if userdata is not None:
try:
params[spot_prefix + 'UserData'] = base64.b64encode(
salt.utils.stringutils.to_bytes(userdata)
)
except Exception as exc:
log.exception('Failed to encode userdata: %s', exc)
vm_size = config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
)
params[spot_prefix + 'InstanceType'] = vm_size
ex_keyname = keyname(vm_)
if ex_keyname:
params[spot_prefix + 'KeyName'] = ex_keyname
ex_securitygroup = securitygroup(vm_)
if ex_securitygroup:
if not isinstance(ex_securitygroup, list):
params[spot_prefix + 'SecurityGroup.1'] = ex_securitygroup
else:
for counter, sg_ in enumerate(ex_securitygroup):
params[spot_prefix + 'SecurityGroup.{0}'.format(counter)] = sg_
ex_iam_profile = iam_profile(vm_)
if ex_iam_profile:
try:
if ex_iam_profile.startswith('arn:aws:iam:'):
params[
spot_prefix + 'IamInstanceProfile.Arn'
] = ex_iam_profile
else:
params[
spot_prefix + 'IamInstanceProfile.Name'
] = ex_iam_profile
except AttributeError:
raise SaltCloudConfigError(
'\'iam_profile\' should be a string value.'
)
az_ = get_availability_zone(vm_)
if az_ is not None:
params[spot_prefix + 'Placement.AvailabilityZone'] = az_
tenancy_ = get_tenancy(vm_)
if tenancy_ is not None:
if spot_config is not None:
raise SaltCloudConfigError(
'Spot instance config for {0} does not support '
'specifying tenancy.'.format(vm_['name'])
)
params['Placement.Tenancy'] = tenancy_
subnetid_ = get_subnetid(vm_)
if subnetid_ is not None:
params[spot_prefix + 'SubnetId'] = subnetid_
ex_securitygroupid = securitygroupid(vm_)
if ex_securitygroupid:
if not isinstance(ex_securitygroupid, list):
params[spot_prefix + 'SecurityGroupId.1'] = ex_securitygroupid
else:
for counter, sg_ in enumerate(ex_securitygroupid):
params[
spot_prefix + 'SecurityGroupId.{0}'.format(counter)
] = sg_
placementgroup_ = get_placementgroup(vm_)
if placementgroup_ is not None:
params[spot_prefix + 'Placement.GroupName'] = placementgroup_
blockdevicemappings_holder = block_device_mappings(vm_)
if blockdevicemappings_holder:
for _bd in blockdevicemappings_holder:
if 'tag' in _bd:
_bd.pop('tag')
ex_blockdevicemappings = blockdevicemappings_holder
if ex_blockdevicemappings:
params.update(_param_from_config(spot_prefix + 'BlockDeviceMapping',
ex_blockdevicemappings))
network_interfaces = config.get_cloud_config_value(
'network_interfaces',
vm_,
__opts__,
search_global=False
)
if network_interfaces:
eni_devices = []
for interface in network_interfaces:
log.debug('Create network interface: %s', interface)
_new_eni = _create_eni_if_necessary(interface, vm_)
eni_devices.append(_new_eni)
params.update(_param_from_config(spot_prefix + 'NetworkInterface',
eni_devices))
set_ebs_optimized = config.get_cloud_config_value(
'ebs_optimized', vm_, __opts__, search_global=False
)
if set_ebs_optimized is not None:
if not isinstance(set_ebs_optimized, bool):
raise SaltCloudConfigError(
'\'ebs_optimized\' should be a boolean value.'
)
params[spot_prefix + 'EbsOptimized'] = set_ebs_optimized
set_del_root_vol_on_destroy = config.get_cloud_config_value(
'del_root_vol_on_destroy', vm_, __opts__, search_global=False
)
set_termination_protection = config.get_cloud_config_value(
'termination_protection', vm_, __opts__, search_global=False
)
if set_termination_protection is not None:
if not isinstance(set_termination_protection, bool):
raise SaltCloudConfigError(
'\'termination_protection\' should be a boolean value.'
)
params.update(_param_from_config(spot_prefix + 'DisableApiTermination',
set_termination_protection))
if set_del_root_vol_on_destroy and not isinstance(set_del_root_vol_on_destroy, bool):
raise SaltCloudConfigError(
'\'del_root_vol_on_destroy\' should be a boolean value.'
)
vm_['set_del_root_vol_on_destroy'] = set_del_root_vol_on_destroy
if set_del_root_vol_on_destroy:
# first make sure to look up the root device name
# as Ubuntu and CentOS (and most likely other OSs)
# use different device identifiers
log.info('Attempting to look up root device name for image id %s on '
'VM %s', image_id, vm_['name'])
rd_params = {
'Action': 'DescribeImages',
'ImageId.1': image_id
}
try:
rd_data = aws.query(rd_params,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'error' in rd_data:
return rd_data['error']
log.debug('EC2 Response: \'%s\'', rd_data)
except Exception as exc:
log.error(
'Error getting root device name for image id %s for '
'VM %s: \n%s', image_id, vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
raise
# make sure we have a response
if not rd_data:
err_msg = 'There was an error querying EC2 for the root device ' \
'of image id {0}. Empty response.'.format(image_id)
raise SaltCloudSystemExit(err_msg)
# pull the root device name from the result and use it when
# launching the new VM
rd_name = None
rd_type = None
if 'blockDeviceMapping' in rd_data[0]:
# Some ami instances do not have a root volume. Ignore such cases
if rd_data[0]['blockDeviceMapping'] is not None:
item = rd_data[0]['blockDeviceMapping']['item']
if isinstance(item, list):
item = item[0]
rd_name = item['deviceName']
# Grab the volume type
rd_type = item['ebs'].get('volumeType', None)
log.info('Found root device name: %s', rd_name)
if rd_name is not None:
if ex_blockdevicemappings:
dev_list = [
dev['DeviceName'] for dev in ex_blockdevicemappings
]
else:
dev_list = []
if rd_name in dev_list:
# Device already listed, just grab the index
dev_index = dev_list.index(rd_name)
else:
dev_index = len(dev_list)
# Add the device name in since it wasn't already there
params[
'{0}BlockDeviceMapping.{1}.DeviceName'.format(
spot_prefix, dev_index
)
] = rd_name
# Set the termination value
termination_key = '{0}BlockDeviceMapping.{1}.Ebs.DeleteOnTermination'.format(spot_prefix, dev_index)
params[termination_key] = six.text_type(set_del_root_vol_on_destroy).lower()
# Use default volume type if not specified
if ex_blockdevicemappings and dev_index < len(ex_blockdevicemappings) and \
'Ebs.VolumeType' not in ex_blockdevicemappings[dev_index]:
type_key = '{0}BlockDeviceMapping.{1}.Ebs.VolumeType'.format(spot_prefix, dev_index)
params[type_key] = rd_type
set_del_all_vols_on_destroy = config.get_cloud_config_value(
'del_all_vols_on_destroy', vm_, __opts__, search_global=False, default=False
)
if set_del_all_vols_on_destroy and not isinstance(set_del_all_vols_on_destroy, bool):
raise SaltCloudConfigError(
'\'del_all_vols_on_destroy\' should be a boolean value.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={
'kwargs': __utils__['cloud.filter_event'](
'requesting', params, list(params)
),
'location': location,
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
provider = get_provider(vm_)
try:
data = aws.query(params,
'instancesSet',
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if 'error' in data:
return data['error']
except Exception as exc:
log.error(
'Error creating %s on EC2 when trying to run the initial '
'deployment: \n%s', vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
raise
# if we're using spot instances, we need to wait for the spot request
# to become active before we continue
if spot_config:
sir_id = data[0]['spotInstanceRequestId']
vm_['spotRequestId'] = sir_id
def __query_spot_instance_request(sir_id, location):
params = {'Action': 'DescribeSpotInstanceRequests',
'SpotInstanceRequestId.1': sir_id}
data = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if not data:
log.error(
'There was an error while querying EC2. Empty response'
)
# Trigger a failure in the wait for spot instance method
return False
if isinstance(data, dict) and 'error' in data:
log.warning('There was an error in the query. %s', data['error'])
# Trigger a failure in the wait for spot instance method
return False
log.debug('Returned query data: %s', data)
state = data[0].get('state')
if state == 'active':
return data
if state == 'open':
# Still waiting for an active state
log.info('Spot instance status: %s', data[0]['status']['message'])
return None
if state in ['cancelled', 'failed', 'closed']:
# Request will never be active, fail
log.error('Spot instance request resulted in state \'{0}\'. '
'Nothing else we can do here.')
return False
__utils__['cloud.fire_event'](
'event',
'waiting for spot instance',
'salt/cloud/{0}/waiting_for_spot'.format(vm_['name']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = _wait_for_spot_instance(
__query_spot_instance_request,
update_args=(sir_id, location),
timeout=config.get_cloud_config_value(
'wait_for_spot_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_spot_interval', vm_, __opts__, default=30),
interval_multiplier=config.get_cloud_config_value(
'wait_for_spot_interval_multiplier',
vm_,
__opts__,
default=1),
max_failures=config.get_cloud_config_value(
'wait_for_spot_max_failures',
vm_,
__opts__,
default=10),
)
log.debug('wait_for_spot_instance data %s', data)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# Cancel the existing spot instance request
params = {'Action': 'CancelSpotInstanceRequests',
'SpotInstanceRequestId.1': sir_id}
data = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
log.debug('Canceled spot instance request %s. Data '
'returned: %s', sir_id, data)
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
return data, vm_
def query_instance(vm_=None, call=None):
'''
Query an instance upon creation from the EC2 API
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The query_instance action must be called with -a or --action.'
)
instance_id = vm_['instance_id']
location = vm_.get('location', get_location(vm_))
__utils__['cloud.fire_event'](
'event',
'querying instance',
'salt/cloud/{0}/querying'.format(vm_['name']),
args={'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('The new VM instance_id is %s', instance_id)
params = {'Action': 'DescribeInstances',
'InstanceId.1': instance_id}
provider = get_provider(vm_)
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
data, requesturl = aws.query(params, # pylint: disable=unbalanced-tuple-unpacking
location=location,
provider=provider,
opts=__opts__,
return_url=True,
sigver='4')
log.debug('The query returned: %s', data)
if isinstance(data, dict) and 'error' in data:
log.warning(
'There was an error in the query. %s attempts '
'remaining: %s', attempts, data['error']
)
elif isinstance(data, list) and not data:
log.warning(
'Query returned an empty list. %s attempts '
'remaining.', attempts
)
else:
break
aws.sleep_exponential_backoff(attempts)
attempts += 1
continue
else:
raise SaltCloudSystemExit(
'An error occurred while creating VM: {0}'.format(data['error'])
)
def __query_ip_address(params, url): # pylint: disable=W0613
data = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if not data:
log.error(
'There was an error while querying EC2. Empty response'
)
# Trigger a failure in the wait for IP function
return False
if isinstance(data, dict) and 'error' in data:
log.warning('There was an error in the query. %s', data['error'])
# Trigger a failure in the wait for IP function
return False
log.debug('Returned query data: %s', data)
if ssh_interface(vm_) == 'public_ips':
if 'ipAddress' in data[0]['instancesSet']['item']:
return data
else:
log.error(
'Public IP not detected.'
)
if ssh_interface(vm_) == 'private_ips':
if 'privateIpAddress' in data[0]['instancesSet']['item']:
return data
else:
log.error(
'Private IP not detected.'
)
try:
data = salt.utils.cloud.wait_for_ip(
__query_ip_address,
update_args=(params, requesturl),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value(
'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if 'reactor' in vm_ and vm_['reactor'] is True:
__utils__['cloud.fire_event'](
'event',
'instance queried',
'salt/cloud/{0}/query_reactor'.format(vm_['name']),
args={'data': data},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return data
def wait_for_instance(
vm_=None,
data=None,
ip_address=None,
display_ssh_output=True,
call=None,
):
'''
Wait for an instance upon creation from the EC2 API, to become available
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The wait_for_instance action must be called with -a or --action.'
)
if vm_ is None:
vm_ = {}
if data is None:
data = {}
ssh_gateway_config = vm_.get(
'gateway', get_ssh_gateway_config(vm_)
)
__utils__['cloud.fire_event'](
'event',
'waiting for ssh',
'salt/cloud/{0}/waiting_for_ssh'.format(vm_['name']),
args={'ip_address': ip_address},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
ssh_connect_timeout = config.get_cloud_config_value(
'ssh_connect_timeout', vm_, __opts__, 900 # 15 minutes
)
ssh_port = config.get_cloud_config_value(
'ssh_port', vm_, __opts__, 22
)
if config.get_cloud_config_value('win_installer', vm_, __opts__):
username = config.get_cloud_config_value(
'win_username', vm_, __opts__, default='Administrator'
)
win_passwd = config.get_cloud_config_value(
'win_password', vm_, __opts__, default=''
)
win_deploy_auth_retries = config.get_cloud_config_value(
'win_deploy_auth_retries', vm_, __opts__, default=10
)
win_deploy_auth_retry_delay = config.get_cloud_config_value(
'win_deploy_auth_retry_delay', vm_, __opts__, default=1
)
use_winrm = config.get_cloud_config_value(
'use_winrm', vm_, __opts__, default=False
)
winrm_verify_ssl = config.get_cloud_config_value(
'winrm_verify_ssl', vm_, __opts__, default=True
)
if win_passwd and win_passwd == 'auto':
log.debug('Waiting for auto-generated Windows EC2 password')
while True:
password_data = get_password_data(
name=vm_['name'],
kwargs={
'key_file': vm_['private_key'],
},
call='action',
)
win_passwd = password_data.get('password', None)
if win_passwd is None:
log.debug(password_data)
# This wait is so high, because the password is unlikely to
# be generated for at least 4 minutes
time.sleep(60)
else:
logging_data = password_data
logging_data['password'] = 'XXX-REDACTED-XXX'
logging_data['passwordData'] = 'XXX-REDACTED-XXX'
log.debug(logging_data)
vm_['win_password'] = win_passwd
break
# SMB used whether psexec or winrm
if not salt.utils.cloud.wait_for_port(ip_address,
port=445,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to connect to remote windows host'
)
# If not using winrm keep same psexec behavior
if not use_winrm:
log.debug('Trying to authenticate via SMB using psexec')
if not salt.utils.cloud.validate_windows_cred(ip_address,
username,
win_passwd,
retries=win_deploy_auth_retries,
retry_delay=win_deploy_auth_retry_delay):
raise SaltCloudSystemExit(
'Failed to authenticate against remote windows host (smb)'
)
# If using winrm
else:
# Default HTTPS port can be changed in cloud configuration
winrm_port = config.get_cloud_config_value(
'winrm_port', vm_, __opts__, default=5986
)
# Wait for winrm port to be available
if not salt.utils.cloud.wait_for_port(ip_address,
port=winrm_port,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to connect to remote windows host (winrm)'
)
log.debug('Trying to authenticate via Winrm using pywinrm')
if not salt.utils.cloud.wait_for_winrm(ip_address,
winrm_port,
username,
win_passwd,
timeout=ssh_connect_timeout,
verify=winrm_verify_ssl):
raise SaltCloudSystemExit(
'Failed to authenticate against remote windows host'
)
elif salt.utils.cloud.wait_for_port(ip_address,
port=ssh_port,
timeout=ssh_connect_timeout,
gateway=ssh_gateway_config
):
# If a known_hosts_file is configured, this instance will not be
# accessible until it has a host key. Since this is provided on
# supported instances by cloud-init, and viewable to us only from the
# console output (which may take several minutes to become available,
# we have some more waiting to do here.
known_hosts_file = config.get_cloud_config_value(
'known_hosts_file', vm_, __opts__, default=None
)
if known_hosts_file:
console = {}
while 'output_decoded' not in console:
console = get_console_output(
instance_id=vm_['instance_id'],
call='action',
location=get_location(vm_)
)
pprint.pprint(console)
time.sleep(5)
output = salt.utils.stringutils.to_unicode(console['output_decoded'])
comps = output.split('-----BEGIN SSH HOST KEY KEYS-----')
if len(comps) < 2:
# Fail; there are no host keys
return False
comps = comps[1].split('-----END SSH HOST KEY KEYS-----')
keys = ''
for line in comps[0].splitlines():
if not line:
continue
keys += '\n{0} {1}'.format(ip_address, line)
with salt.utils.files.fopen(known_hosts_file, 'a') as fp_:
fp_.write(salt.utils.stringutils.to_str(keys))
fp_.close()
for user in vm_['usernames']:
if salt.utils.cloud.wait_for_passwd(
host=ip_address,
port=ssh_port,
username=user,
ssh_timeout=config.get_cloud_config_value(
'wait_for_passwd_timeout', vm_, __opts__, default=1 * 60
),
key_filename=vm_['key_filename'],
display_ssh_output=display_ssh_output,
gateway=ssh_gateway_config,
maxtries=config.get_cloud_config_value(
'wait_for_passwd_maxtries', vm_, __opts__, default=15
),
known_hosts_file=config.get_cloud_config_value(
'known_hosts_file', vm_, __opts__,
default='/dev/null'
),
):
__opts__['ssh_username'] = user
vm_['ssh_username'] = user
break
else:
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
else:
raise SaltCloudSystemExit(
'Failed to connect to remote ssh'
)
if 'reactor' in vm_ and vm_['reactor'] is True:
__utils__['cloud.fire_event'](
'event',
'ssh is available',
'salt/cloud/{0}/ssh_ready_reactor'.format(vm_['name']),
args={'ip_address': ip_address},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return vm_
def _validate_key_path_and_mode(key_filename):
if key_filename is None:
raise SaltCloudSystemExit(
'The required \'private_key\' configuration setting is missing from the '
'\'ec2\' driver.'
)
if not os.path.exists(key_filename):
raise SaltCloudSystemExit(
'The EC2 key file \'{0}\' does not exist.\n'.format(
key_filename
)
)
key_mode = stat.S_IMODE(os.stat(key_filename).st_mode)
if key_mode not in (0o400, 0o600):
raise SaltCloudSystemExit(
'The EC2 key file \'{0}\' needs to be set to mode 0400 or 0600.\n'.format(
key_filename
)
)
return True
def create(vm_=None, call=None):
'''
Create a single VM from a data dict
'''
if call:
raise SaltCloudSystemExit(
'You cannot create an instance with -a or -f.'
)
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'ec2',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
# Check for private_key and keyfile name for bootstrapping new instances
deploy = config.get_cloud_config_value(
'deploy', vm_, __opts__, default=True
)
win_password = config.get_cloud_config_value(
'win_password', vm_, __opts__, default=''
)
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
if deploy:
# The private_key and keyname settings are only needed for bootstrapping
# new instances when deploy is True
_validate_key_path_and_mode(key_filename)
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](
vm_['name'], vm_['profile'], 'ec2', vm_['driver']
)
vm_['key_filename'] = key_filename
# wait_for_instance requires private_key
vm_['private_key'] = key_filename
# Get SSH Gateway config early to verify the private_key,
# if used, exists or not. We don't want to deploy an instance
# and not be able to access it via the gateway.
vm_['gateway'] = get_ssh_gateway_config(vm_)
location = get_location(vm_)
vm_['location'] = location
log.info('Creating Cloud VM %s in %s', vm_['name'], location)
vm_['usernames'] = salt.utils.cloud.ssh_usernames(
vm_,
__opts__,
default_users=(
'ec2-user', # Amazon Linux, Fedora, RHEL; FreeBSD
'centos', # CentOS AMIs from AWS Marketplace
'ubuntu', # Ubuntu
'admin', # Debian GNU/Linux
'bitnami', # BitNami AMIs
'root' # Last resort, default user on RHEL 5, SUSE
)
)
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
if keyname(vm_) is None:
raise SaltCloudSystemExit(
'The required \'keyname\' configuration setting is missing from the '
'\'ec2\' driver.'
)
data, vm_ = request_instance(vm_, location)
# If data is a str, it's an error
if isinstance(data, six.string_types):
log.error('Error requesting instance: %s', data)
return {}
# Pull the instance ID, valid for both spot and normal instances
# Multiple instances may have been spun up, get all their IDs
vm_['instance_id_list'] = []
for instance in data:
vm_['instance_id_list'].append(instance['instanceId'])
vm_['instance_id'] = vm_['instance_id_list'].pop()
if vm_['instance_id_list']:
# Multiple instances were spun up, get one now, and queue the rest
queue_instances(vm_['instance_id_list'])
# Wait for vital information, such as IP addresses, to be available
# for the new instance
data = query_instance(vm_)
# Now that the instance is available, tag it appropriately. Should
# mitigate race conditions with tags
tags = config.get_cloud_config_value('tag',
vm_,
__opts__,
{},
search_global=False)
if not isinstance(tags, dict):
raise SaltCloudConfigError(
'\'tag\' should be a dict.'
)
for value in six.itervalues(tags):
if not isinstance(value, six.string_types):
raise SaltCloudConfigError(
'\'tag\' values must be strings. Try quoting the values. '
'e.g. "2013-09-19T20:09:46Z".'
)
tags['Name'] = vm_['name']
__utils__['cloud.fire_event'](
'event',
'setting tags',
'salt/cloud/{0}/tagging'.format(vm_['name']),
args={'tags': tags},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
salt.utils.cloud.wait_for_fun(
set_tags,
timeout=30,
name=vm_['name'],
tags=tags,
instance_id=vm_['instance_id'],
call='action',
location=location
)
# Once instance tags are set, tag the spot request if configured
if 'spot_config' in vm_ and 'tag' in vm_['spot_config']:
if not isinstance(vm_['spot_config']['tag'], dict):
raise SaltCloudConfigError(
'\'tag\' should be a dict.'
)
for value in six.itervalues(vm_['spot_config']['tag']):
if not isinstance(value, str):
raise SaltCloudConfigError(
'\'tag\' values must be strings. Try quoting the values. '
'e.g. "2013-09-19T20:09:46Z".'
)
spot_request_tags = {}
if 'spotRequestId' not in vm_:
raise SaltCloudConfigError('Failed to find spotRequestId')
sir_id = vm_['spotRequestId']
spot_request_tags['Name'] = vm_['name']
for k, v in six.iteritems(vm_['spot_config']['tag']):
spot_request_tags[k] = v
__utils__['cloud.fire_event'](
'event',
'setting tags',
'salt/cloud/spot_request_{0}/tagging'.format(sir_id),
args={'tags': spot_request_tags},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
salt.utils.cloud.wait_for_fun(
set_tags,
timeout=30,
name=vm_['name'],
tags=spot_request_tags,
instance_id=sir_id,
call='action',
location=location
)
network_interfaces = config.get_cloud_config_value(
'network_interfaces',
vm_,
__opts__,
search_global=False
)
if network_interfaces:
_update_enis(network_interfaces, data, vm_)
# At this point, the node is created and tagged, and now needs to be
# bootstrapped, once the necessary port is available.
log.info('Created node %s', vm_['name'])
instance = data[0]['instancesSet']['item']
# Wait for the necessary port to become available to bootstrap
if ssh_interface(vm_) == 'private_ips':
ip_address = instance['privateIpAddress']
log.info('Salt node data. Private_ip: %s', ip_address)
else:
ip_address = instance['ipAddress']
log.info('Salt node data. Public_ip: %s', ip_address)
vm_['ssh_host'] = ip_address
if salt.utils.cloud.get_salt_interface(vm_, __opts__) == 'private_ips':
salt_ip_address = instance['privateIpAddress']
log.info('Salt interface set to: %s', salt_ip_address)
else:
salt_ip_address = instance['ipAddress']
log.debug('Salt interface set to: %s', salt_ip_address)
vm_['salt_host'] = salt_ip_address
if deploy:
display_ssh_output = config.get_cloud_config_value(
'display_ssh_output', vm_, __opts__, default=True
)
vm_ = wait_for_instance(
vm_, data, ip_address, display_ssh_output
)
# The instance is booted and accessible, let's Salt it!
ret = instance.copy()
# Get ANY defined volumes settings, merging data, in the following order
# 1. VM config
# 2. Profile config
# 3. Global configuration
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args={'volumes': volumes},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'zone': ret['placement']['availabilityZone'],
'instance_id': ret['instanceId'],
'del_all_vols_on_destroy': vm_.get('del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
# Associate instance with a ssm document, if present
ssm_document = config.get_cloud_config_value(
'ssm_document', vm_, __opts__, None, search_global=False
)
if ssm_document:
log.debug('Associating with ssm document: %s', ssm_document)
assoc = ssm_create_association(
vm_['name'],
{'ssm_document': ssm_document},
instance_id=vm_['instance_id'],
call='action'
)
if isinstance(assoc, dict) and assoc.get('error', None):
log.error(
'Failed to associate instance %s with ssm document %s',
vm_['instance_id'], ssm_document
)
return {}
for key, value in six.iteritems(__utils__['cloud.bootstrap'](vm_, __opts__)):
ret.setdefault(key, value)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(instance)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': vm_['instance_id'],
}
if volumes:
event_data['volumes'] = volumes
if ssm_document:
event_data['ssm_document'] = ssm_document
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# Ensure that the latest node data is returned
node = _get_node(instance_id=vm_['instance_id'])
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
ret.update(node)
# Add any block device tags specified
ex_blockdevicetags = {}
blockdevicemappings_holder = block_device_mappings(vm_)
if blockdevicemappings_holder:
for _bd in blockdevicemappings_holder:
if 'tag' in _bd:
ex_blockdevicetags[_bd['DeviceName']] = _bd['tag']
block_device_volume_id_map = {}
if ex_blockdevicetags:
for _device, _map in six.iteritems(ret['blockDeviceMapping']):
bd_items = []
if isinstance(_map, dict):
bd_items.append(_map)
else:
for mapitem in _map:
bd_items.append(mapitem)
for blockitem in bd_items:
if blockitem['deviceName'] in ex_blockdevicetags and 'Name' not in ex_blockdevicetags[blockitem['deviceName']]:
ex_blockdevicetags[blockitem['deviceName']]['Name'] = vm_['name']
if blockitem['deviceName'] in ex_blockdevicetags:
block_device_volume_id_map[blockitem[ret['rootDeviceType']]['volumeId']] = ex_blockdevicetags[blockitem['deviceName']]
if block_device_volume_id_map:
for volid, tags in six.iteritems(block_device_volume_id_map):
__utils__['cloud.fire_event'](
'event',
'setting tags',
'salt/cloud/block_volume_{0}/tagging'.format(str(volid)),
args={'tags': tags},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.wait_for_fun'](
set_tags,
timeout=30,
name=vm_['name'],
tags=tags,
resource_id=volid,
call='action',
location=location
)
return ret
def queue_instances(instances):
'''
Queue a set of instances to be provisioned later. Expects a list.
Currently this only queries node data, and then places it in the cloud
cache (if configured). If the salt-cloud-reactor is being used, these
instances will be automatically provisioned using that.
For more information about the salt-cloud-reactor, see:
https://github.com/saltstack-formulas/salt-cloud-reactor
'''
for instance_id in instances:
node = _get_node(instance_id=instance_id)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if 'instance_id' not in kwargs:
kwargs['instance_id'] = _get_node(name)['instanceId']
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
ret = []
for volume in volumes:
created = False
volume_name = '{0} on {1}'.format(volume['device'], name)
volume_dict = {
'volume_name': volume_name,
'zone': kwargs['zone']
}
if 'volume_id' in volume:
volume_dict['volume_id'] = volume['volume_id']
elif 'snapshot' in volume:
volume_dict['snapshot'] = volume['snapshot']
elif 'size' in volume:
volume_dict['size'] = volume['size']
else:
raise SaltCloudConfigError(
'Cannot create volume. Please define one of \'volume_id\', '
'\'snapshot\', or \'size\''
)
if 'tags' in volume:
volume_dict['tags'] = volume['tags']
if 'type' in volume:
volume_dict['type'] = volume['type']
if 'iops' in volume:
volume_dict['iops'] = volume['iops']
if 'encrypted' in volume:
volume_dict['encrypted'] = volume['encrypted']
if 'kmskeyid' in volume:
volume_dict['kmskeyid'] = volume['kmskeyid']
if 'volume_id' not in volume_dict:
created_volume = create_volume(volume_dict, call='function', wait_to_finish=wait_to_finish)
created = True
if 'volumeId' in created_volume:
volume_dict['volume_id'] = created_volume['volumeId']
attach = attach_volume(
name,
{'volume_id': volume_dict['volume_id'],
'device': volume['device']},
instance_id=kwargs['instance_id'],
call='action'
)
# Update the delvol parameter for this volume
delvols_on_destroy = kwargs.get('del_all_vols_on_destroy', None)
if attach and created and delvols_on_destroy is not None:
_toggle_delvol(instance_id=kwargs['instance_id'],
device=volume['device'],
value=delvols_on_destroy)
if attach:
msg = (
'{0} attached to {1} (aka {2}) as device {3}'.format(
volume_dict['volume_id'],
kwargs['instance_id'],
name,
volume['device']
)
)
log.info(msg)
ret.append(msg)
return ret
def stop(name, call=None):
'''
Stop a node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instance_id = _get_node(name)['instanceId']
__utils__['cloud.fire_event'](
'event',
'stopping instance',
'salt/cloud/{0}/stopping'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
params = {'Action': 'StopInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return result
def start(name, call=None):
'''
Start a node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instance_id = _get_node(name)['instanceId']
__utils__['cloud.fire_event'](
'event',
'starting instance',
'salt/cloud/{0}/starting'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
params = {'Action': 'StartInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return result
def set_tags(name=None,
tags=None,
call=None,
location=None,
instance_id=None,
resource_id=None,
kwargs=None): # pylint: disable=W0613
'''
Set tags for a resource. Normally a VM name or instance_id is passed in,
but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a set_tags mymachine tag1=somestuff tag2='Other stuff'
salt-cloud -a set_tags resource_id=vol-3267ab32 tag=somestuff
'''
if kwargs is None:
kwargs = {}
if location is None:
location = get_location()
if instance_id is None:
if 'resource_id' in kwargs:
resource_id = kwargs['resource_id']
del kwargs['resource_id']
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
del kwargs['instance_id']
if resource_id is None:
if instance_id is None:
instance_id = _get_node(name=name, instance_id=None, location=location)['instanceId']
else:
instance_id = resource_id
# This second check is a safety, in case the above still failed to produce
# a usable ID
if instance_id is None:
return {
'Error': 'A valid instance_id or resource_id was not specified.'
}
params = {'Action': 'CreateTags',
'ResourceId.1': instance_id}
log.debug('Tags to set for %s: %s', name, tags)
if kwargs and not tags:
tags = kwargs
for idx, (tag_k, tag_v) in enumerate(six.iteritems(tags)):
params['Tag.{0}.Key'.format(idx)] = tag_k
params['Tag.{0}.Value'.format(idx)] = tag_v
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
aws.query(params,
setname='tagSet',
location=location,
provider=get_provider(),
opts=__opts__,
sigver='4')
settags = get_tags(
instance_id=instance_id, call='action', location=location
)
log.debug('Setting the tags returned: %s', settags)
failed_to_set_tags = False
for tag in settags:
if tag['key'] not in tags:
# We were not setting this tag
continue
if tag.get('value') is None and tags.get(tag['key']) == '':
# This is a correctly set tag with no value
continue
if six.text_type(tags.get(tag['key'])) != six.text_type(tag['value']):
# Not set to the proper value!?
log.debug(
'Setting the tag %s returned %s instead of %s',
tag['key'], tags.get(tag['key']), tag['value']
)
failed_to_set_tags = True
break
if failed_to_set_tags:
log.warning('Failed to set tags. Remaining attempts %s', attempts)
attempts += 1
aws.sleep_exponential_backoff(attempts)
continue
return settags
raise SaltCloudSystemExit(
'Failed to set tags on {0}!'.format(name)
)
def get_tags(name=None,
instance_id=None,
call=None,
location=None,
kwargs=None,
resource_id=None): # pylint: disable=W0613
'''
Retrieve tags for a resource. Normally a VM name or instance_id is passed
in, but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a get_tags mymachine
salt-cloud -a get_tags resource_id=vol-3267ab32
'''
if location is None:
location = get_location()
if instance_id is None:
if resource_id is None:
if name:
instance_id = _get_node(name)['instanceId']
elif 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
elif 'resource_id' in kwargs:
instance_id = kwargs['resource_id']
else:
instance_id = resource_id
params = {'Action': 'DescribeTags',
'Filter.1.Name': 'resource-id',
'Filter.1.Value': instance_id}
return aws.query(params,
setname='tagSet',
location=location,
provider=get_provider(),
opts=__opts__,
sigver='4')
def del_tags(name=None,
kwargs=None,
call=None,
instance_id=None,
resource_id=None): # pylint: disable=W0613
'''
Delete tags for a resource. Normally a VM name or instance_id is passed in,
but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a del_tags mymachine tags=mytag,
salt-cloud -a del_tags mymachine tags=tag1,tag2,tag3
salt-cloud -a del_tags resource_id=vol-3267ab32 tags=tag1,tag2,tag3
'''
if kwargs is None:
kwargs = {}
if 'tags' not in kwargs:
raise SaltCloudSystemExit(
'A tag or tags must be specified using tags=list,of,tags'
)
if not name and 'resource_id' in kwargs:
instance_id = kwargs['resource_id']
del kwargs['resource_id']
if not instance_id:
instance_id = _get_node(name)['instanceId']
params = {'Action': 'DeleteTags',
'ResourceId.1': instance_id}
for idx, tag in enumerate(kwargs['tags'].split(',')):
params['Tag.{0}.Key'.format(idx)] = tag
aws.query(params,
setname='tagSet',
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if resource_id:
return get_tags(resource_id=resource_id)
else:
return get_tags(instance_id=instance_id)
def rename(name, kwargs, call=None):
'''
Properly rename a node. Pass in the new name as "new name".
CLI Example:
.. code-block:: bash
salt-cloud -a rename mymachine newname=yourmachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The rename action must be called with -a or --action.'
)
log.info('Renaming %s to %s', name, kwargs['newname'])
set_tags(name, {'Name': kwargs['newname']}, call='action')
salt.utils.cloud.rename_key(
__opts__['pki_dir'], name, kwargs['newname']
)
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
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.'
)
node_metadata = _get_node(name)
instance_id = node_metadata['instanceId']
sir_id = node_metadata.get('spotInstanceRequestId')
protected = show_term_protect(
name=name,
instance_id=instance_id,
call='action',
quiet=True
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if protected == 'true':
raise SaltCloudSystemExit(
'This instance has been protected from being destroyed. '
'Use the following command to disable protection:\n\n'
'salt-cloud -a disable_term_protect {0}'.format(
name
)
)
ret = {}
# Default behavior is to rename EC2 VMs when destroyed
# via salt-cloud, unless explicitly set to False.
rename_on_destroy = config.get_cloud_config_value('rename_on_destroy',
get_configured_provider(),
__opts__,
search_global=False)
if rename_on_destroy is not False:
newname = '{0}-DEL{1}'.format(name, uuid.uuid4().hex)
rename(name, kwargs={'newname': newname}, call='action')
log.info(
'Machine will be identified as %s until it has been '
'cleaned up.', newname
)
ret['newname'] = newname
params = {'Action': 'TerminateInstances',
'InstanceId.1': instance_id}
location = get_location()
provider = get_provider()
result = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
log.info(result)
ret.update(result[0])
# If this instance is part of a spot instance request, we
# need to cancel it as well
if sir_id is not None:
params = {'Action': 'CancelSpotInstanceRequests',
'SpotInstanceRequestId.1': sir_id}
result = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
ret['spotInstance'] = result[0]
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_del'](name)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return ret
def reboot(name, call=None):
'''
Reboot a node.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot mymachine
'''
instance_id = _get_node(name)['instanceId']
params = {'Action': 'RebootInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
setname='tagSet',
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if result == []:
log.info('Complete')
return {'Reboot': 'Complete'}
def show_image(kwargs, call=None):
'''
Show the details from EC2 concerning an AMI
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
params = {'ImageId.1': kwargs['image'],
'Action': 'DescribeImages'}
result = aws.query(params,
setname='tagSet',
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
log.info(result)
return result
def show_instance(name=None, instance_id=None, call=None, kwargs=None):
'''
Show the details from EC2 concerning an AMI.
Can be called as an action (which requires a name):
.. code-block:: bash
salt-cloud -a show_instance myinstance
...or as a function (which requires either a name or instance_id):
.. code-block:: bash
salt-cloud -f show_instance my-ec2 name=myinstance
salt-cloud -f show_instance my-ec2 instance_id=i-d34db33f
'''
if not name and call == 'action':
raise SaltCloudSystemExit(
'The show_instance action requires a name.'
)
if call == 'function':
name = kwargs.get('name', None)
instance_id = kwargs.get('instance_id', None)
if not name and not instance_id:
raise SaltCloudSystemExit(
'The show_instance function requires '
'either a name or an instance_id'
)
node = _get_node(name=name, instance_id=instance_id)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name=None, instance_id=None, location=None):
if location is None:
location = get_location()
params = {'Action': 'DescribeInstances'}
if six.text_type(name).startswith('i-') and (len(name) == 10 or len(name) == 19):
instance_id = name
if instance_id:
params['InstanceId.1'] = instance_id
else:
params['Filter.1.Name'] = 'tag:Name'
params['Filter.1.Value.1'] = name
log.trace(params)
provider = get_provider()
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
try:
instances = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
instance_info = _extract_instance_info(instances).values()
return next(iter(instance_info))
except IndexError:
attempts += 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', instance_id or name, attempts
)
aws.sleep_exponential_backoff(attempts)
return {}
def list_nodes_full(location=None, 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.'
)
return _list_nodes_full(location or get_location())
def _extract_name_tag(item):
if 'tagSet' in item and item['tagSet'] is not None:
tagset = item['tagSet']
if isinstance(tagset['item'], list):
for tag in tagset['item']:
if tag['key'] == 'Name':
return tag['value']
return item['instanceId']
return item['tagSet']['item']['value']
return item['instanceId']
def _extract_instance_info(instances):
'''
Given an instance query, return a dict of all instance data
'''
ret = {}
for instance in instances:
# items could be type dict or list (for stopped EC2 instances)
if isinstance(instance['instancesSet']['item'], list):
for item in instance['instancesSet']['item']:
name = _extract_name_tag(item)
ret[name] = item
ret[name]['name'] = name
ret[name].update(
dict(
id=item['instanceId'],
image=item['imageId'],
size=item['instanceType'],
state=item['instanceState']['name'],
private_ips=item.get('privateIpAddress', []),
public_ips=item.get('ipAddress', [])
)
)
else:
item = instance['instancesSet']['item']
name = _extract_name_tag(item)
ret[name] = item
ret[name]['name'] = name
ret[name].update(
dict(
id=item['instanceId'],
image=item['imageId'],
size=item['instanceType'],
state=item['instanceState']['name'],
private_ips=item.get('privateIpAddress', []),
public_ips=item.get('ipAddress', [])
)
)
return ret
def _list_nodes_full(location=None):
'''
Return a list of the VMs that in this location
'''
provider = __active_provider_name__ or 'ec2'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
params = {'Action': 'DescribeInstances'}
instances = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if 'error' in instances:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
instances['error']['Errors']['Error']['Message']
)
)
ret = _extract_instance_info(instances)
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_min(location=None, call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
params = {'Action': 'DescribeInstances'}
instances = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'error' in instances:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
instances['error']['Errors']['Error']['Message']
)
)
for instance in instances:
if isinstance(instance['instancesSet']['item'], list):
items = instance['instancesSet']['item']
else:
items = [instance['instancesSet']['item']]
for item in items:
state = item['instanceState']['name']
name = _extract_name_tag(item)
id = item['instanceId']
ret[name] = {'state': state, 'id': id}
return ret
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(get_location())
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]['id'],
'image': nodes[node]['image'],
'name': nodes[node]['name'],
'size': nodes[node]['size'],
'state': nodes[node]['state'],
'private_ips': nodes[node]['private_ips'],
'public_ips': nodes[node]['public_ips'],
}
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(get_location()), __opts__['query.selection'], call,
)
def show_term_protect(name=None, instance_id=None, call=None, quiet=False):
'''
Show the details from EC2 concerning an instance's termination protection state
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_term_protect action must be called with -a or --action.'
)
if not instance_id:
instance_id = _get_node(name)['instanceId']
params = {'Action': 'DescribeInstanceAttribute',
'InstanceId': instance_id,
'Attribute': 'disableApiTermination'}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
disable_protect = False
for item in result:
if 'value' in item:
disable_protect = item['value']
break
log.log(
logging.DEBUG if quiet is True else logging.INFO,
'Termination Protection is %s for %s',
disable_protect == 'true' and 'enabled' or 'disabled', name
)
return disable_protect
def show_detailed_monitoring(name=None, instance_id=None, call=None, quiet=False):
'''
Show the details from EC2 regarding cloudwatch detailed monitoring.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_detailed_monitoring action must be called with -a or --action.'
)
location = get_location()
if six.text_type(name).startswith('i-') and (len(name) == 10 or len(name) == 19):
instance_id = name
if not name and not instance_id:
raise SaltCloudSystemExit(
'The show_detailed_monitoring action must be provided with a name or instance\
ID'
)
matched = _get_node(name=name, instance_id=instance_id, location=location)
log.log(
logging.DEBUG if quiet is True else logging.INFO,
'Detailed Monitoring is %s for %s', matched['monitoring'], name
)
return matched['monitoring']
def _toggle_term_protect(name, value):
'''
Enable or Disable termination protection on a node
'''
instance_id = _get_node(name)['instanceId']
params = {'Action': 'ModifyInstanceAttribute',
'InstanceId': instance_id,
'DisableApiTermination.Value': value}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
return show_term_protect(name=name, instance_id=instance_id, call='action')
def enable_term_protect(name, call=None):
'''
Enable termination protection on a node
CLI Example:
.. code-block:: bash
salt-cloud -a enable_term_protect mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
return _toggle_term_protect(name, 'true')
def disable_term_protect(name, call=None):
'''
Disable termination protection on a node
CLI Example:
.. code-block:: bash
salt-cloud -a disable_term_protect mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
return _toggle_term_protect(name, 'false')
def disable_detailed_monitoring(name, call=None):
'''
Enable/disable detailed monitoring on a node
CLI Example:
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
instance_id = _get_node(name)['instanceId']
params = {'Action': 'UnmonitorInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
return show_detailed_monitoring(name=name, instance_id=instance_id, call='action')
def enable_detailed_monitoring(name, call=None):
'''
Enable/disable detailed monitoring on a node
CLI Example:
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
instance_id = _get_node(name)['instanceId']
params = {'Action': 'MonitorInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
return show_detailed_monitoring(name=name, instance_id=instance_id, call='action')
def show_delvol_on_destroy(name, kwargs=None, call=None):
'''
Do not delete all/specified EBS volumes upon instance termination
CLI Example:
.. code-block:: bash
salt-cloud -a show_delvol_on_destroy mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_delvol_on_destroy action must be called '
'with -a or --action.'
)
if not kwargs:
kwargs = {}
instance_id = kwargs.get('instance_id', None)
device = kwargs.get('device', None)
volume_id = kwargs.get('volume_id', None)
if instance_id is None:
instance_id = _get_node(name)['instanceId']
params = {'Action': 'DescribeInstances',
'InstanceId.1': instance_id}
data = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
blockmap = data[0]['instancesSet']['item']['blockDeviceMapping']
if not isinstance(blockmap['item'], list):
blockmap['item'] = [blockmap['item']]
items = []
for idx, item in enumerate(blockmap['item']):
device_name = item['deviceName']
if device is not None and device != device_name:
continue
if volume_id is not None and volume_id != item['ebs']['volumeId']:
continue
info = {
'device_name': device_name,
'volume_id': item['ebs']['volumeId'],
'deleteOnTermination': item['ebs']['deleteOnTermination']
}
items.append(info)
return items
def keepvol_on_destroy(name, kwargs=None, call=None):
'''
Do not delete all/specified EBS volumes upon instance termination
CLI Example:
.. code-block:: bash
salt-cloud -a keepvol_on_destroy mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The keepvol_on_destroy action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
device = kwargs.get('device', None)
volume_id = kwargs.get('volume_id', None)
return _toggle_delvol(name=name, device=device,
volume_id=volume_id, value='false')
def delvol_on_destroy(name, kwargs=None, call=None):
'''
Delete all/specified EBS volumes upon instance termination
CLI Example:
.. code-block:: bash
salt-cloud -a delvol_on_destroy mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The delvol_on_destroy action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
device = kwargs.get('device', None)
volume_id = kwargs.get('volume_id', None)
return _toggle_delvol(name=name, device=device,
volume_id=volume_id, value='true')
def _toggle_delvol(name=None, instance_id=None, device=None, volume_id=None,
value=None, requesturl=None):
if not instance_id:
instance_id = _get_node(name)['instanceId']
if requesturl:
data = aws.query(requesturl=requesturl,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
else:
params = {'Action': 'DescribeInstances',
'InstanceId.1': instance_id}
data, requesturl = aws.query(params, # pylint: disable=unbalanced-tuple-unpacking
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
blockmap = data[0]['instancesSet']['item']['blockDeviceMapping']
params = {'Action': 'ModifyInstanceAttribute',
'InstanceId': instance_id}
if not isinstance(blockmap['item'], list):
blockmap['item'] = [blockmap['item']]
for idx, item in enumerate(blockmap['item']):
device_name = item['deviceName']
if device is not None and device != device_name:
continue
if volume_id is not None and volume_id != item['ebs']['volumeId']:
continue
params['BlockDeviceMapping.{0}.DeviceName'.format(idx)] = device_name
params['BlockDeviceMapping.{0}.Ebs.DeleteOnTermination'.format(idx)] = value
aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
kwargs = {'instance_id': instance_id,
'device': device,
'volume_id': volume_id}
return show_delvol_on_destroy(name, kwargs, call='action')
def register_image(kwargs=None, call=None):
'''
Create an ami from a snapshot
CLI Example:
.. code-block:: bash
salt-cloud -f register_image my-ec2-config ami_name=my_ami description="my description"
root_device_name=/dev/xvda snapshot_id=snap-xxxxxxxx
'''
if call != 'function':
log.error(
'The create_volume function must be called with -f or --function.'
)
return False
if 'ami_name' not in kwargs:
log.error('ami_name must be specified to register an image.')
return False
block_device_mapping = kwargs.get('block_device_mapping', None)
if not block_device_mapping:
if 'snapshot_id' not in kwargs:
log.error('snapshot_id or block_device_mapping must be specified to register an image.')
return False
if 'root_device_name' not in kwargs:
log.error('root_device_name or block_device_mapping must be specified to register an image.')
return False
block_device_mapping = [{
'DeviceName': kwargs['root_device_name'],
'Ebs': {
'VolumeType': kwargs.get('volume_type', 'gp2'),
'SnapshotId': kwargs['snapshot_id'],
}
}]
if not isinstance(block_device_mapping, list):
block_device_mapping = [block_device_mapping]
params = {'Action': 'RegisterImage',
'Name': kwargs['ami_name']}
params.update(_param_from_config('BlockDeviceMapping', block_device_mapping))
if 'root_device_name' in kwargs:
params['RootDeviceName'] = kwargs['root_device_name']
if 'description' in kwargs:
params['Description'] = kwargs['description']
if 'virtualization_type' in kwargs:
params['VirtualizationType'] = kwargs['virtualization_type']
if 'architecture' in kwargs:
params['Architecture'] = kwargs['architecture']
log.debug(params)
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
r_data = {}
for d in data[0]:
for k, v in d.items():
r_data[k] = v
return r_data
def volume_create(**kwargs):
'''
Wrapper around create_volume.
Here just to ensure the compatibility with the cloud module.
'''
return create_volume(kwargs, 'function')
def create_volume(kwargs=None, call=None, wait_to_finish=False):
'''
Create a volume.
zone
The availability zone used to create the volume. Required. String.
size
The size of the volume, in GiBs. Defaults to ``10``. Integer.
snapshot
The snapshot-id from which to create the volume. Integer.
type
The volume type. This can be gp2 for General Purpose SSD, io1 for Provisioned
IOPS SSD, st1 for Throughput Optimized HDD, sc1 for Cold HDD, or standard for
Magnetic volumes. String.
iops
The number of I/O operations per second (IOPS) to provision for the volume,
with a maximum ratio of 50 IOPS/GiB. Only valid for Provisioned IOPS SSD
volumes. Integer.
This option will only be set if ``type`` is also specified as ``io1``.
encrypted
Specifies whether the volume will be encrypted. Boolean.
If ``snapshot`` is also given in the list of kwargs, then this value is ignored
since volumes that are created from encrypted snapshots are also automatically
encrypted.
tags
The tags to apply to the volume during creation. Dictionary.
call
The ``create_volume`` function must be called with ``-f`` or ``--function``.
String.
wait_to_finish
Whether or not to wait for the volume to be available. Boolean. Defaults to
``False``.
CLI Examples:
.. code-block:: bash
salt-cloud -f create_volume my-ec2-config zone=us-east-1b
salt-cloud -f create_volume my-ec2-config zone=us-east-1b tags='{"tag1": "val1", "tag2", "val2"}'
'''
if call != 'function':
log.error(
'The create_volume function must be called with -f or --function.'
)
return False
if 'zone' not in kwargs:
log.error('An availability zone must be specified to create a volume.')
return False
if 'size' not in kwargs and 'snapshot' not in kwargs:
# This number represents GiB
kwargs['size'] = '10'
params = {'Action': 'CreateVolume',
'AvailabilityZone': kwargs['zone']}
if 'size' in kwargs:
params['Size'] = kwargs['size']
if 'snapshot' in kwargs:
params['SnapshotId'] = kwargs['snapshot']
if 'type' in kwargs:
params['VolumeType'] = kwargs['type']
if 'iops' in kwargs and kwargs.get('type', 'standard') == 'io1':
params['Iops'] = kwargs['iops']
# You can't set `encrypted` if you pass a snapshot
if 'encrypted' in kwargs and 'snapshot' not in kwargs:
params['Encrypted'] = kwargs['encrypted']
if 'kmskeyid' in kwargs:
params['KmsKeyId'] = kwargs['kmskeyid']
if 'kmskeyid' in kwargs and 'encrypted' not in kwargs:
log.error(
'If a KMS Key ID is specified, encryption must be enabled'
)
return False
log.debug(params)
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
r_data = {}
for d in data[0]:
for k, v in six.iteritems(d):
r_data[k] = v
volume_id = r_data['volumeId']
# Allow tags to be set upon creation
if 'tags' in kwargs:
if isinstance(kwargs['tags'], six.string_types):
tags = salt.utils.yaml.safe_load(kwargs['tags'])
else:
tags = kwargs['tags']
if isinstance(tags, dict):
new_tags = set_tags(tags=tags,
resource_id=volume_id,
call='action',
location=get_location())
r_data['tags'] = new_tags
# Waits till volume is available
if wait_to_finish:
salt.utils.cloud.run_func_until_ret_arg(fun=describe_volumes,
kwargs={'volume_id': volume_id},
fun_call=call,
argument_being_watched='status',
required_argument_response='available')
return r_data
def __attach_vol_to_instance(params, kws, instance_id):
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if data[0]:
log.warning(
'Error attaching volume %s to instance %s. Retrying!',
kws['volume_id'], instance_id
)
return False
return data
def attach_volume(name=None, kwargs=None, instance_id=None, call=None):
'''
Attach a volume to an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The attach_volume action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
if name and not instance_id:
instance_id = _get_node(name)['instanceId']
if not name and not instance_id:
log.error('Either a name or an instance_id is required.')
return False
if 'volume_id' not in kwargs:
log.error('A volume_id is required.')
return False
if 'device' not in kwargs:
log.error('A device is required (ex. /dev/sdb1).')
return False
params = {'Action': 'AttachVolume',
'VolumeId': kwargs['volume_id'],
'InstanceId': instance_id,
'Device': kwargs['device']}
log.debug(params)
vm_ = get_configured_provider()
data = salt.utils.cloud.wait_for_ip(
__attach_vol_to_instance,
update_args=(params, kwargs, instance_id),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value(
'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
return data
def show_volume(kwargs=None, call=None):
'''
Wrapper around describe_volumes.
Here just to keep functionality.
Might be depreciated later.
'''
if not kwargs:
kwargs = {}
return describe_volumes(kwargs, call)
def detach_volume(name=None, kwargs=None, instance_id=None, call=None):
'''
Detach a volume from an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The detach_volume action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
if 'volume_id' not in kwargs:
log.error('A volume_id is required.')
return False
params = {'Action': 'DetachVolume',
'VolumeId': kwargs['volume_id']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def delete_volume(name=None, kwargs=None, instance_id=None, call=None):
'''
Delete a volume
'''
if not kwargs:
kwargs = {}
if 'volume_id' not in kwargs:
log.error('A volume_id is required.')
return False
params = {'Action': 'DeleteVolume',
'VolumeId': kwargs['volume_id']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def volume_list(**kwargs):
'''
Wrapper around describe_volumes.
Here just to ensure the compatibility with the cloud module.
'''
return describe_volumes(kwargs, 'function')
def describe_volumes(kwargs=None, call=None):
'''
Describe a volume (or volumes)
volume_id
One or more volume IDs. Multiple IDs must be separated by ",".
TODO: Add all of the filters.
'''
if call != 'function':
log.error(
'The describe_volumes function must be called with -f '
'or --function.'
)
return False
if not kwargs:
kwargs = {}
params = {'Action': 'DescribeVolumes'}
if 'volume_id' in kwargs:
volume_id = kwargs['volume_id'].split(',')
for volume_index, volume_id in enumerate(volume_id):
params['VolumeId.{0}'.format(volume_index)] = volume_id
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def create_keypair(kwargs=None, call=None):
'''
Create an SSH keypair
'''
if call != 'function':
log.error(
'The create_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
params = {'Action': 'CreateKeyPair',
'KeyName': kwargs['keyname']}
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
keys = [x for x in data[0] if 'requestId' not in x]
return (keys, data[1])
def import_keypair(kwargs=None, call=None):
'''
Import an SSH public key.
.. versionadded:: 2015.8.3
'''
if call != 'function':
log.error(
'The import_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
if 'file' not in kwargs:
log.error('A public key file is required.')
return False
params = {'Action': 'ImportKeyPair',
'KeyName': kwargs['keyname']}
public_key_file = kwargs['file']
if os.path.exists(public_key_file):
with salt.utils.files.fopen(public_key_file, 'r') as fh_:
public_key = salt.utils.stringutils.to_unicode(fh_.read())
if public_key is not None:
params['PublicKeyMaterial'] = base64.b64encode(public_key)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
params = {'Action': 'DescribeKeyPairs',
'KeyName.1': kwargs['keyname']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def delete_keypair(kwargs=None, call=None):
'''
Delete an SSH keypair
'''
if call != 'function':
log.error(
'The delete_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
params = {'Action': 'DeleteKeyPair',
'KeyName': kwargs['keyname']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def create_snapshot(kwargs=None, call=None, wait_to_finish=False):
'''
Create a snapshot.
volume_id
The ID of the Volume from which to create a snapshot.
description
The optional description of the snapshot.
CLI Exampe:
.. code-block:: bash
salt-cloud -f create_snapshot my-ec2-config volume_id=vol-351d8826
salt-cloud -f create_snapshot my-ec2-config volume_id=vol-351d8826 \\
description="My Snapshot Description"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_snapshot function must be called with -f '
'or --function.'
)
if kwargs is None:
kwargs = {}
volume_id = kwargs.get('volume_id', None)
description = kwargs.get('description', '')
if volume_id is None:
raise SaltCloudSystemExit(
'A volume_id must be specified to create a snapshot.'
)
params = {'Action': 'CreateSnapshot',
'VolumeId': volume_id,
'Description': description}
log.debug(params)
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')[0]
r_data = {}
for d in data:
for k, v in six.iteritems(d):
r_data[k] = v
if 'snapshotId' in r_data:
snapshot_id = r_data['snapshotId']
# Waits till volume is available
if wait_to_finish:
salt.utils.cloud.run_func_until_ret_arg(fun=describe_snapshots,
kwargs={'snapshot_id': snapshot_id},
fun_call=call,
argument_being_watched='status',
required_argument_response='completed')
return r_data
def delete_snapshot(kwargs=None, call=None):
'''
Delete a snapshot
'''
if call != 'function':
log.error(
'The delete_snapshot function must be called with -f '
'or --function.'
)
return False
if 'snapshot_id' not in kwargs:
log.error('A snapshot_id must be specified to delete a snapshot.')
return False
params = {'Action': 'DeleteSnapshot'}
if 'snapshot_id' in kwargs:
params['SnapshotId'] = kwargs['snapshot_id']
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def copy_snapshot(kwargs=None, call=None):
'''
Copy a snapshot
'''
if call != 'function':
log.error(
'The copy_snapshot function must be called with -f or --function.'
)
return False
if 'source_region' not in kwargs:
log.error('A source_region must be specified to copy a snapshot.')
return False
if 'source_snapshot_id' not in kwargs:
log.error('A source_snapshot_id must be specified to copy a snapshot.')
return False
if 'description' not in kwargs:
kwargs['description'] = ''
params = {'Action': 'CopySnapshot'}
if 'source_region' in kwargs:
params['SourceRegion'] = kwargs['source_region']
if 'source_snapshot_id' in kwargs:
params['SourceSnapshotId'] = kwargs['source_snapshot_id']
if 'description' in kwargs:
params['Description'] = kwargs['description']
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def describe_snapshots(kwargs=None, call=None):
'''
Describe a snapshot (or snapshots)
snapshot_id
One or more snapshot IDs. Multiple IDs must be separated by ",".
owner
Return the snapshots owned by the specified owner. Valid values
include: self, amazon, <AWS Account ID>. Multiple values must be
separated by ",".
restorable_by
One or more AWS accounts IDs that can create volumes from the snapshot.
Multiple aws account IDs must be separated by ",".
TODO: Add all of the filters.
'''
if call != 'function':
log.error(
'The describe_snapshot function must be called with -f '
'or --function.'
)
return False
params = {'Action': 'DescribeSnapshots'}
# The AWS correct way is to use non-plurals like snapshot_id INSTEAD of snapshot_ids.
if 'snapshot_ids' in kwargs:
kwargs['snapshot_id'] = kwargs['snapshot_ids']
if 'snapshot_id' in kwargs:
snapshot_ids = kwargs['snapshot_id'].split(',')
for snapshot_index, snapshot_id in enumerate(snapshot_ids):
params['SnapshotId.{0}'.format(snapshot_index)] = snapshot_id
if 'owner' in kwargs:
owners = kwargs['owner'].split(',')
for owner_index, owner in enumerate(owners):
params['Owner.{0}'.format(owner_index)] = owner
if 'restorable_by' in kwargs:
restorable_bys = kwargs['restorable_by'].split(',')
for restorable_by_index, restorable_by in enumerate(restorable_bys):
params[
'RestorableBy.{0}'.format(restorable_by_index)
] = restorable_by
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def get_console_output(
name=None,
location=None,
instance_id=None,
call=None,
kwargs=None,
):
'''
Show the console output from the instance.
By default, returns decoded data, not the Base64-encoded data that is
actually returned from the EC2 API.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The get_console_output action must be called with '
'-a or --action.'
)
if location is None:
location = get_location()
if not instance_id:
instance_id = _get_node(name)['instanceId']
if kwargs is None:
kwargs = {}
if instance_id is None:
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
del kwargs['instance_id']
params = {'Action': 'GetConsoleOutput',
'InstanceId': instance_id}
ret = {}
data = aws.query(params,
return_root=True,
location=location,
provider=get_provider(),
opts=__opts__,
sigver='4')
for item in data:
if next(six.iterkeys(item)) == 'output':
ret['output_decoded'] = binascii.a2b_base64(next(six.itervalues(item)))
else:
ret[next(six.iterkeys(item))] = next(six.itervalues(item))
return ret
def get_password_data(
name=None,
kwargs=None,
instance_id=None,
call=None,
):
'''
Return password data for a Windows instance.
By default only the encrypted password data will be returned. However, if a
key_file is passed in, then a decrypted password will also be returned.
Note that the key_file references the private key that was used to generate
the keypair associated with this instance. This private key will _not_ be
transmitted to Amazon; it is only used internally inside of Salt Cloud to
decrypt data _after_ it has been received from Amazon.
CLI Examples:
.. code-block:: bash
salt-cloud -a get_password_data mymachine
salt-cloud -a get_password_data mymachine key_file=/root/ec2key.pem
Note: PKCS1_v1_5 was added in PyCrypto 2.5
'''
if call != 'action':
raise SaltCloudSystemExit(
'The get_password_data action must be called with '
'-a or --action.'
)
if not instance_id:
instance_id = _get_node(name)['instanceId']
if kwargs is None:
kwargs = {}
if instance_id is None:
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
del kwargs['instance_id']
params = {'Action': 'GetPasswordData',
'InstanceId': instance_id}
ret = {}
data = aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
for item in data:
ret[next(six.iterkeys(item))] = next(six.itervalues(item))
if not HAS_M2 and not HAS_PYCRYPTO:
return ret
if 'key' not in kwargs:
if 'key_file' in kwargs:
with salt.utils.files.fopen(kwargs['key_file'], 'r') as kf_:
kwargs['key'] = salt.utils.stringutils.to_unicode(kf_.read())
if 'key' in kwargs:
pwdata = ret.get('passwordData', None)
if pwdata is not None:
rsa_key = kwargs['key']
pwdata = base64.b64decode(pwdata)
if HAS_M2:
key = RSA.load_key_string(rsa_key.encode('ascii'))
password = key.private_decrypt(pwdata, RSA.pkcs1_padding)
else:
dsize = Crypto.Hash.SHA.digest_size
sentinel = Crypto.Random.new().read(15 + dsize)
key_obj = Crypto.PublicKey.RSA.importKey(rsa_key)
key_obj = PKCS1_v1_5.new(key_obj)
password = key_obj.decrypt(pwdata, sentinel)
ret['password'] = salt.utils.stringutils.to_unicode(password)
return ret
def update_pricing(kwargs=None, call=None):
'''
Download most recent pricing information from AWS and convert to a local
JSON file.
CLI Examples:
.. code-block:: bash
salt-cloud -f update_pricing my-ec2-config
salt-cloud -f update_pricing my-ec2-config type=linux
.. versionadded:: 2015.8.0
'''
sources = {
'linux': 'https://a0.awsstatic.com/pricing/1/ec2/linux-od.min.js',
'rhel': 'https://a0.awsstatic.com/pricing/1/ec2/rhel-od.min.js',
'sles': 'https://a0.awsstatic.com/pricing/1/ec2/sles-od.min.js',
'mswin': 'https://a0.awsstatic.com/pricing/1/ec2/mswin-od.min.js',
'mswinsql': 'https://a0.awsstatic.com/pricing/1/ec2/mswinSQL-od.min.js',
'mswinsqlweb': 'https://a0.awsstatic.com/pricing/1/ec2/mswinSQLWeb-od.min.js',
}
if kwargs is None:
kwargs = {}
if 'type' not in kwargs:
for source in sources:
_parse_pricing(sources[source], source)
else:
_parse_pricing(sources[kwargs['type']], kwargs['type'])
def _parse_pricing(url, name):
'''
Download and parse an individual pricing file from AWS
.. versionadded:: 2015.8.0
'''
price_js = http.query(url, text=True)
items = []
current_item = ''
price_js = re.sub(JS_COMMENT_RE, '', price_js['text'])
price_js = price_js.strip().rstrip(');').lstrip('callback(')
for keyword in (
'vers',
'config',
'rate',
'valueColumns',
'currencies',
'instanceTypes',
'type',
'ECU',
'storageGB',
'name',
'vCPU',
'memoryGiB',
'storageGiB',
'USD',
):
price_js = price_js.replace(keyword, '"{0}"'.format(keyword))
for keyword in ('region', 'price', 'size'):
price_js = price_js.replace(keyword, '"{0}"'.format(keyword))
price_js = price_js.replace('"{0}"s'.format(keyword), '"{0}s"'.format(keyword))
price_js = price_js.replace('""', '"')
# Turn the data into something that's easier/faster to process
regions = {}
price_json = salt.utils.json.loads(price_js)
for region in price_json['config']['regions']:
sizes = {}
for itype in region['instanceTypes']:
for size in itype['sizes']:
sizes[size['size']] = size
regions[region['region']] = sizes
outfile = os.path.join(
__opts__['cachedir'], 'ec2-pricing-{0}.p'.format(name)
)
with salt.utils.files.fopen(outfile, 'w') as fho:
salt.utils.msgpack.dump(regions, fho)
return True
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-ec2-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: 2015.8.0
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to ec2
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'ec2':
return {'Error': 'The requested profile does not belong to EC2'}
image_id = profile.get('image', None)
image_dict = show_image({'image': image_id}, 'function')
image_info = image_dict[0]
# Find out what platform it is
if image_info.get('imageOwnerAlias', '') == 'amazon':
if image_info.get('platform', '') == 'windows':
image_description = image_info.get('description', '')
if 'sql' in image_description.lower():
if 'web' in image_description.lower():
name = 'mswinsqlweb'
else:
name = 'mswinsql'
else:
name = 'mswin'
elif image_info.get('imageLocation', '').strip().startswith('amazon/suse'):
name = 'sles'
else:
name = 'linux'
elif image_info.get('imageOwnerId', '') == '309956199498':
name = 'rhel'
else:
name = 'linux'
pricefile = os.path.join(
__opts__['cachedir'], 'ec2-pricing-{0}.p'.format(name)
)
if not os.path.isfile(pricefile):
update_pricing({'type': name}, 'function')
with salt.utils.files.fopen(pricefile, 'r') as fhi:
ec2_price = salt.utils.stringutils.to_unicode(
salt.utils.msgpack.load(fhi))
region = get_location(profile)
size = profile.get('size', None)
if size is None:
return {'Error': 'The requested profile does not contain a size'}
try:
raw = ec2_price[region][size]
except KeyError:
return {'Error': 'The size ({0}) in the requested profile does not have '
'a price associated with it for the {1} region'.format(size, region)}
ret = {}
if kwargs.get('raw', False):
ret['_raw'] = raw
ret['per_hour'] = 0
for col in raw.get('valueColumns', []):
ret['per_hour'] += decimal.Decimal(col['prices'].get('USD', 0))
ret['per_hour'] = decimal.Decimal(ret['per_hour'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = ret['per_day'] * 30
ret['per_year'] = ret['per_week'] * 52
return {profile['profile']: ret}
def ssm_create_association(name=None, kwargs=None, instance_id=None, call=None):
'''
Associates the specified SSM document with the specified instance
http://docs.aws.amazon.com/ssm/latest/APIReference/API_CreateAssociation.html
CLI Examples:
.. code-block:: bash
salt-cloud -a ssm_create_association ec2-instance-name ssm_document=ssm-document-name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The ssm_create_association action must be called with '
'-a or --action.'
)
if not kwargs:
kwargs = {}
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
if name and not instance_id:
instance_id = _get_node(name)['instanceId']
if not name and not instance_id:
log.error('Either a name or an instance_id is required.')
return False
if 'ssm_document' not in kwargs:
log.error('A ssm_document is required.')
return False
params = {'Action': 'CreateAssociation',
'InstanceId': instance_id,
'Name': kwargs['ssm_document']}
result = aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
product='ssm',
opts=__opts__,
sigver='4')
log.info(result)
return result
def ssm_describe_association(name=None, kwargs=None, instance_id=None, call=None):
'''
Describes the associations for the specified SSM document or instance.
http://docs.aws.amazon.com/ssm/latest/APIReference/API_DescribeAssociation.html
CLI Examples:
.. code-block:: bash
salt-cloud -a ssm_describe_association ec2-instance-name ssm_document=ssm-document-name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The ssm_describe_association action must be called with '
'-a or --action.'
)
if not kwargs:
kwargs = {}
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
if name and not instance_id:
instance_id = _get_node(name)['instanceId']
if not name and not instance_id:
log.error('Either a name or an instance_id is required.')
return False
if 'ssm_document' not in kwargs:
log.error('A ssm_document is required.')
return False
params = {'Action': 'DescribeAssociation',
'InstanceId': instance_id,
'Name': kwargs['ssm_document']}
result = aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
product='ssm',
opts=__opts__,
sigver='4')
log.info(result)
return result
|
saltstack/salt | salt/cloud/clouds/ec2.py | optimize_providers | python | def optimize_providers(providers):
'''
Return an optimized list of providers.
We want to reduce the duplication of querying
the same region.
If a provider is using the same credentials for the same region
the same data will be returned for each provider, thus causing
un-wanted duplicate data and API calls to EC2.
'''
tmp_providers = {}
optimized_providers = {}
for name, data in six.iteritems(providers):
if 'location' not in data:
data['location'] = DEFAULT_LOCATION
if data['location'] not in tmp_providers:
tmp_providers[data['location']] = {}
creds = (data['id'], data['key'])
if creds not in tmp_providers[data['location']]:
tmp_providers[data['location']][creds] = {'name': name,
'data': data,
}
for location, tmp_data in six.iteritems(tmp_providers):
for creds, data in six.iteritems(tmp_data):
_id, _key = creds
_name = data['name']
_data = data['data']
if _name not in optimized_providers:
optimized_providers[_name] = _data
return optimized_providers | Return an optimized list of providers.
We want to reduce the duplication of querying
the same region.
If a provider is using the same credentials for the same region
the same data will be returned for each provider, thus causing
un-wanted duplicate data and API calls to EC2. | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/ec2.py#L266-L302 | [
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] | # -*- coding: utf-8 -*-
'''
The EC2 Cloud Module
====================
The EC2 cloud module is used to interact with the Amazon Elastic Compute Cloud.
To use the EC2 cloud module, set up the cloud configuration at
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/ec2.conf``:
.. code-block:: yaml
my-ec2-config:
# EC2 API credentials: Access Key ID and Secret Access Key.
# Alternatively, to use IAM Instance Role credentials available via
# EC2 metadata set both id and key to 'use-instance-role-credentials'
id: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# If 'role_arn' is specified the above credentials are used to
# to assume to the role. By default, role_arn is set to None.
role_arn: arn:aws:iam::012345678910:role/SomeRoleName
# The ssh keyname to use
keyname: default
# The amazon security group
securitygroup: ssh_open
# The location of the private key which corresponds to the keyname
private_key: /root/default.pem
# Be default, service_url is set to amazonaws.com. If you are using this
# driver for something other than Amazon EC2, change it here:
service_url: amazonaws.com
# The endpoint that is ultimately used is usually formed using the region
# and the service_url. If you would like to override that entirely, you
# can explicitly define the endpoint:
endpoint: myendpoint.example.com:1138/services/Cloud
# SSH Gateways can be used with this provider. Gateways can be used
# when a salt-master is not on the same private network as the instance
# that is being deployed.
# Defaults to None
# Required
ssh_gateway: gateway.example.com
# Defaults to port 22
# Optional
ssh_gateway_port: 22
# Defaults to root
# Optional
ssh_gateway_username: root
# Default to nc -q0 %h %p
# Optional
ssh_gateway_command: "-W %h:%p"
# One authentication method is required. If both
# are specified, Private key wins.
# Private key defaults to None
ssh_gateway_private_key: /path/to/key.pem
# Password defaults to None
ssh_gateway_password: ExamplePasswordHere
driver: ec2
# Pass userdata to the instance to be created
userdata_file: /etc/salt/my-userdata-file
# Instance termination protection setting
# Default is disabled
termination_protection: False
:depends: requests
'''
# pylint: disable=invalid-name,function-redefined
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import stat
import time
import uuid
import pprint
import logging
# Import libs for talking to the EC2 API
import hmac
import hashlib
import binascii
import datetime
import base64
import re
import decimal
# Import Salt Libs
import salt.utils.cloud
import salt.utils.compat
import salt.utils.files
import salt.utils.hashutils
import salt.utils.json
import salt.utils.msgpack
import salt.utils.stringutils
import salt.utils.yaml
from salt._compat import ElementTree as ET
import salt.utils.http as http
import salt.utils.aws as aws
import salt.config as config
from salt.exceptions import (
SaltCloudException,
SaltCloudSystemExit,
SaltCloudConfigError,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure
)
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, zip
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse, urlencode as _urlencode
# Import 3rd-Party Libs
# Try to import PyCrypto, which may not be installed on a RAET-based system
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
import Crypto
# PKCS1_v1_5 was added in PyCrypto 2.5
from Crypto.Cipher import PKCS1_v1_5 # pylint: disable=E0611
from Crypto.Hash import SHA # pylint: disable=E0611,W0611
HAS_PYCRYPTO = True
except ImportError:
HAS_PYCRYPTO = False
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# pylint: enable=import-error,no-name-in-module,redefined-builtin
# Get logging started
log = logging.getLogger(__name__)
EC2_LOCATIONS = {
'ap-northeast-1': 'ec2_ap_northeast',
'ap-northeast-2': 'ec2_ap_northeast_2',
'ap-southeast-1': 'ec2_ap_southeast',
'ap-southeast-2': 'ec2_ap_southeast_2',
'eu-west-1': 'ec2_eu_west',
'eu-central-1': 'ec2_eu_central',
'sa-east-1': 'ec2_sa_east',
'us-east-1': 'ec2_us_east',
'us-gov-west-1': 'ec2_us_gov_west_1',
'us-west-1': 'ec2_us_west',
'us-west-2': 'ec2_us_west_oregon',
}
DEFAULT_LOCATION = 'us-east-1'
DEFAULT_EC2_API_VERSION = '2014-10-01'
EC2_RETRY_CODES = [
'RequestLimitExceeded',
'InsufficientInstanceCapacity',
'InternalError',
'Unavailable',
'InsufficientAddressCapacity',
'InsufficientReservedInstanceCapacity',
]
JS_COMMENT_RE = re.compile(r'/\*.*?\*/', re.S)
__virtualname__ = 'ec2'
# Only load in this module if the EC2 configurations are in place
def __virtual__():
'''
Set up the libcloud functions and check for EC2 configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'requests': HAS_REQUESTS,
'pycrypto or m2crypto': HAS_M2 or HAS_PYCRYPTO
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def _xml_to_dict(xmltree):
'''
Convert an XML tree into a dict
'''
if sys.version_info < (2, 7):
children_len = len(xmltree.getchildren())
else:
children_len = len(xmltree)
if children_len < 1:
name = xmltree.tag
if '}' in name:
comps = name.split('}')
name = comps[1]
return {name: xmltree.text}
xmldict = {}
for item in xmltree:
name = item.tag
if '}' in name:
comps = name.split('}')
name = comps[1]
if name not in xmldict:
if sys.version_info < (2, 7):
children_len = len(item.getchildren())
else:
children_len = len(item)
if children_len > 0:
xmldict[name] = _xml_to_dict(item)
else:
xmldict[name] = item.text
else:
if not isinstance(xmldict[name], list):
tempvar = xmldict[name]
xmldict[name] = []
xmldict[name].append(tempvar)
xmldict[name].append(_xml_to_dict(item))
return xmldict
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
def query(params=None, setname=None, requesturl=None, location=None,
return_url=False, return_root=False):
provider = get_configured_provider()
service_url = provider.get('service_url', 'amazonaws.com')
# Retrieve access credentials from meta-data, or use provided
access_key_id, secret_access_key, token = aws.creds(provider)
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
params_with_headers = params.copy()
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
if not location:
location = get_location()
if not requesturl:
endpoint = provider.get(
'endpoint',
'ec2.{0}.{1}'.format(location, service_url)
)
requesturl = 'https://{0}/'.format(endpoint)
endpoint = _urlparse(requesturl).netloc
endpoint_path = _urlparse(requesturl).path
else:
endpoint = _urlparse(requesturl).netloc
endpoint_path = _urlparse(requesturl).path
if endpoint == '':
endpoint_err = (
'Could not find a valid endpoint in the '
'requesturl: {0}. Looking for something '
'like https://some.ec2.endpoint/?args').format(requesturl)
log.error(endpoint_err)
if return_url is True:
return {'error': endpoint_err}, requesturl
return {'error': endpoint_err}
log.debug('Using EC2 endpoint: %s', endpoint)
# AWS v4 signature
method = 'GET'
region = location
service = 'ec2'
canonical_uri = _urlparse(requesturl).path
host = endpoint.strip()
# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ') # Format date as YYYYMMDD'T'HHMMSS'Z'
datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'
signed_headers = 'host;x-amz-date'
payload_hash = salt.utils.hashutils.sha256_digest('')
ec2_api_version = provider.get(
'ec2_api_version',
DEFAULT_EC2_API_VERSION
)
params_with_headers['Version'] = ec2_api_version
keys = sorted(list(params_with_headers))
values = map(params_with_headers.get, keys)
querystring = _urlencode(list(zip(keys, values)))
querystring = querystring.replace('+', '%20')
canonical_request = method + '\n' + canonical_uri + '\n' + \
querystring + '\n' + canonical_headers + '\n' + \
signed_headers + '\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amz_date + '\n' + \
credential_scope + '\n' + \
salt.utils.hashutils.sha256_digest(canonical_request)
kDate = sign(('AWS4' + provider['key']).encode('utf-8'), datestamp)
kRegion = sign(kDate, region)
kService = sign(kRegion, service)
signing_key = sign(kService, 'aws4_request')
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'),
hashlib.sha256).hexdigest()
authorization_header = algorithm + ' ' + 'Credential=' + \
provider['id'] + '/' + credential_scope + \
', ' + 'SignedHeaders=' + signed_headers + \
', ' + 'Signature=' + signature
headers = {'x-amz-date': amz_date, 'Authorization': authorization_header}
log.debug('EC2 Request: %s', requesturl)
log.trace('EC2 Request Parameters: %s', params_with_headers)
try:
result = requests.get(requesturl, headers=headers, params=params_with_headers)
log.debug(
'EC2 Response Status Code: %s',
# result.getcode()
result.status_code
)
log.trace('EC2 Response Text: %s', result.text)
result.raise_for_status()
break
except requests.exceptions.HTTPError as exc:
root = ET.fromstring(exc.response.content)
data = _xml_to_dict(root)
# check to see if we should retry the query
err_code = data.get('Errors', {}).get('Error', {}).get('Code', '')
if err_code and err_code in EC2_RETRY_CODES:
attempts += 1
log.error(
'EC2 Response Status Code and Error: [%s %s] %s; '
'Attempts remaining: %s',
exc.response.status_code, exc, data, attempts
)
aws.sleep_exponential_backoff(attempts)
continue
log.error(
'EC2 Response Status Code and Error: [%s %s] %s',
exc.response.status_code, exc, data
)
if return_url is True:
return {'error': data}, requesturl
return {'error': data}
else:
log.error(
'EC2 Response Status Code and Error: [%s %s] %s',
exc.response.status_code, exc, data
)
if return_url is True:
return {'error': data}, requesturl
return {'error': data}
response = result.text
root = ET.fromstring(response)
items = root[1]
if return_root is True:
items = root
if setname:
if sys.version_info < (2, 7):
children_len = len(root.getchildren())
else:
children_len = len(root)
for item in range(0, children_len):
comps = root[item].tag.split('}')
if comps[1] == setname:
items = root[item]
ret = []
for item in items:
ret.append(_xml_to_dict(item))
if return_url is True:
return ret, requesturl
return ret
def _wait_for_spot_instance(update_callback,
update_args=None,
update_kwargs=None,
timeout=10 * 60,
interval=30,
interval_multiplier=1,
max_failures=10):
'''
Helper function that waits for a spot instance request to become active
for a specific maximum amount of time.
:param update_callback: callback function which queries the cloud provider
for spot instance request. It must return None if
the required data, running instance included, is
not available yet.
:param update_args: Arguments to pass to update_callback
:param update_kwargs: Keyword arguments to pass to update_callback
:param timeout: The maximum amount of time(in seconds) to wait for the IP
address.
:param interval: The looping interval, i.e., the amount of time to sleep
before the next iteration.
:param interval_multiplier: Increase the interval by this multiplier after
each request; helps with throttling
:param max_failures: If update_callback returns ``False`` it's considered
query failure. This value is the amount of failures
accepted before giving up.
:returns: The update_callback returned data
:raises: SaltCloudExecutionTimeout
'''
if update_args is None:
update_args = ()
if update_kwargs is None:
update_kwargs = {}
duration = timeout
while True:
log.debug(
'Waiting for spot instance reservation. Giving up in '
'00:%02d:%02d', int(timeout // 60), int(timeout % 60)
)
data = update_callback(*update_args, **update_kwargs)
if data is False:
log.debug(
'update_callback has returned False which is considered a '
'failure. Remaining Failures: %s', max_failures
)
max_failures -= 1
if max_failures <= 0:
raise SaltCloudExecutionFailure(
'Too many failures occurred while waiting for '
'the spot instance reservation to become active.'
)
elif data is not None:
return data
if timeout < 0:
raise SaltCloudExecutionTimeout(
'Unable to get an active spot instance request for '
'00:{0:02d}:{1:02d}'.format(
int(duration // 60),
int(duration % 60)
)
)
time.sleep(interval)
timeout -= interval
if interval_multiplier > 1:
interval *= interval_multiplier
if interval > timeout:
interval = timeout + 1
log.info('Interval multiplier in effect; interval is '
'now %ss', interval)
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. Latest version can be found at:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
sizes = {
'Cluster Compute': {
'cc2.8xlarge': {
'id': 'cc2.8xlarge',
'cores': '16 (2 x Intel Xeon E5-2670, eight-core with '
'hyperthread)',
'disk': '3360 GiB (4 x 840 GiB)',
'ram': '60.5 GiB'
},
'cc1.4xlarge': {
'id': 'cc1.4xlarge',
'cores': '8 (2 x Intel Xeon X5570, quad-core with '
'hyperthread)',
'disk': '1690 GiB (2 x 840 GiB)',
'ram': '22.5 GiB'
},
},
'Cluster CPU': {
'cg1.4xlarge': {
'id': 'cg1.4xlarge',
'cores': '8 (2 x Intel Xeon X5570, quad-core with '
'hyperthread), plus 2 NVIDIA Tesla M2050 GPUs',
'disk': '1680 GiB (2 x 840 GiB)',
'ram': '22.5 GiB'
},
},
'Compute Optimized': {
'c4.large': {
'id': 'c4.large',
'cores': '2',
'disk': 'EBS - 500 Mbps',
'ram': '3.75 GiB'
},
'c4.xlarge': {
'id': 'c4.xlarge',
'cores': '4',
'disk': 'EBS - 750 Mbps',
'ram': '7.5 GiB'
},
'c4.2xlarge': {
'id': 'c4.2xlarge',
'cores': '8',
'disk': 'EBS - 1000 Mbps',
'ram': '15 GiB'
},
'c4.4xlarge': {
'id': 'c4.4xlarge',
'cores': '16',
'disk': 'EBS - 2000 Mbps',
'ram': '30 GiB'
},
'c4.8xlarge': {
'id': 'c4.8xlarge',
'cores': '36',
'disk': 'EBS - 4000 Mbps',
'ram': '60 GiB'
},
'c3.large': {
'id': 'c3.large',
'cores': '2',
'disk': '32 GiB (2 x 16 GiB SSD)',
'ram': '3.75 GiB'
},
'c3.xlarge': {
'id': 'c3.xlarge',
'cores': '4',
'disk': '80 GiB (2 x 40 GiB SSD)',
'ram': '7.5 GiB'
},
'c3.2xlarge': {
'id': 'c3.2xlarge',
'cores': '8',
'disk': '160 GiB (2 x 80 GiB SSD)',
'ram': '15 GiB'
},
'c3.4xlarge': {
'id': 'c3.4xlarge',
'cores': '16',
'disk': '320 GiB (2 x 160 GiB SSD)',
'ram': '30 GiB'
},
'c3.8xlarge': {
'id': 'c3.8xlarge',
'cores': '32',
'disk': '640 GiB (2 x 320 GiB SSD)',
'ram': '60 GiB'
}
},
'Dense Storage': {
'd2.xlarge': {
'id': 'd2.xlarge',
'cores': '4',
'disk': '6 TiB (3 x 2 TiB hard disk drives)',
'ram': '30.5 GiB'
},
'd2.2xlarge': {
'id': 'd2.2xlarge',
'cores': '8',
'disk': '12 TiB (6 x 2 TiB hard disk drives)',
'ram': '61 GiB'
},
'd2.4xlarge': {
'id': 'd2.4xlarge',
'cores': '16',
'disk': '24 TiB (12 x 2 TiB hard disk drives)',
'ram': '122 GiB'
},
'd2.8xlarge': {
'id': 'd2.8xlarge',
'cores': '36',
'disk': '24 TiB (24 x 2 TiB hard disk drives)',
'ram': '244 GiB'
},
},
'GPU': {
'g2.2xlarge': {
'id': 'g2.2xlarge',
'cores': '8',
'disk': '60 GiB (1 x 60 GiB SSD)',
'ram': '15 GiB'
},
'g2.8xlarge': {
'id': 'g2.8xlarge',
'cores': '32',
'disk': '240 GiB (2 x 120 GiB SSD)',
'ram': '60 GiB'
},
},
'GPU Compute': {
'p2.xlarge': {
'id': 'p2.xlarge',
'cores': '4',
'disk': 'EBS',
'ram': '61 GiB'
},
'p2.8xlarge': {
'id': 'p2.8xlarge',
'cores': '32',
'disk': 'EBS',
'ram': '488 GiB'
},
'p2.16xlarge': {
'id': 'p2.16xlarge',
'cores': '64',
'disk': 'EBS',
'ram': '732 GiB'
},
},
'High I/O': {
'i2.xlarge': {
'id': 'i2.xlarge',
'cores': '4',
'disk': 'SSD (1 x 800 GiB)',
'ram': '30.5 GiB'
},
'i2.2xlarge': {
'id': 'i2.2xlarge',
'cores': '8',
'disk': 'SSD (2 x 800 GiB)',
'ram': '61 GiB'
},
'i2.4xlarge': {
'id': 'i2.4xlarge',
'cores': '16',
'disk': 'SSD (4 x 800 GiB)',
'ram': '122 GiB'
},
'i2.8xlarge': {
'id': 'i2.8xlarge',
'cores': '32',
'disk': 'SSD (8 x 800 GiB)',
'ram': '244 GiB'
}
},
'High Memory': {
'x1.16xlarge': {
'id': 'x1.16xlarge',
'cores': '64 (with 5.45 ECUs each)',
'disk': '1920 GiB (1 x 1920 GiB)',
'ram': '976 GiB'
},
'x1.32xlarge': {
'id': 'x1.32xlarge',
'cores': '128 (with 2.73 ECUs each)',
'disk': '3840 GiB (2 x 1920 GiB)',
'ram': '1952 GiB'
},
'r4.large': {
'id': 'r4.large',
'cores': '2 (with 3.45 ECUs each)',
'disk': 'EBS',
'ram': '15.25 GiB'
},
'r4.xlarge': {
'id': 'r4.xlarge',
'cores': '4 (with 3.35 ECUs each)',
'disk': 'EBS',
'ram': '30.5 GiB'
},
'r4.2xlarge': {
'id': 'r4.2xlarge',
'cores': '8 (with 3.35 ECUs each)',
'disk': 'EBS',
'ram': '61 GiB'
},
'r4.4xlarge': {
'id': 'r4.4xlarge',
'cores': '16 (with 3.3 ECUs each)',
'disk': 'EBS',
'ram': '122 GiB'
},
'r4.8xlarge': {
'id': 'r4.8xlarge',
'cores': '32 (with 3.1 ECUs each)',
'disk': 'EBS',
'ram': '244 GiB'
},
'r4.16xlarge': {
'id': 'r4.16xlarge',
'cores': '64 (with 3.05 ECUs each)',
'disk': 'EBS',
'ram': '488 GiB'
},
'r3.large': {
'id': 'r3.large',
'cores': '2 (with 3.25 ECUs each)',
'disk': '32 GiB (1 x 32 GiB SSD)',
'ram': '15 GiB'
},
'r3.xlarge': {
'id': 'r3.xlarge',
'cores': '4 (with 3.25 ECUs each)',
'disk': '80 GiB (1 x 80 GiB SSD)',
'ram': '30.5 GiB'
},
'r3.2xlarge': {
'id': 'r3.2xlarge',
'cores': '8 (with 3.25 ECUs each)',
'disk': '160 GiB (1 x 160 GiB SSD)',
'ram': '61 GiB'
},
'r3.4xlarge': {
'id': 'r3.4xlarge',
'cores': '16 (with 3.25 ECUs each)',
'disk': '320 GiB (1 x 320 GiB SSD)',
'ram': '122 GiB'
},
'r3.8xlarge': {
'id': 'r3.8xlarge',
'cores': '32 (with 3.25 ECUs each)',
'disk': '640 GiB (2 x 320 GiB SSD)',
'ram': '244 GiB'
}
},
'High-Memory Cluster': {
'cr1.8xlarge': {
'id': 'cr1.8xlarge',
'cores': '16 (2 x Intel Xeon E5-2670, eight-core)',
'disk': '240 GiB (2 x 120 GiB SSD)',
'ram': '244 GiB'
},
},
'High Storage': {
'hs1.8xlarge': {
'id': 'hs1.8xlarge',
'cores': '16 (8 cores + 8 hyperthreads)',
'disk': '48 TiB (24 x 2 TiB hard disk drives)',
'ram': '117 GiB'
},
},
'General Purpose': {
't2.nano': {
'id': 't2.nano',
'cores': '1',
'disk': 'EBS',
'ram': '512 MiB'
},
't2.micro': {
'id': 't2.micro',
'cores': '1',
'disk': 'EBS',
'ram': '1 GiB'
},
't2.small': {
'id': 't2.small',
'cores': '1',
'disk': 'EBS',
'ram': '2 GiB'
},
't2.medium': {
'id': 't2.medium',
'cores': '2',
'disk': 'EBS',
'ram': '4 GiB'
},
't2.large': {
'id': 't2.large',
'cores': '2',
'disk': 'EBS',
'ram': '8 GiB'
},
't2.xlarge': {
'id': 't2.xlarge',
'cores': '4',
'disk': 'EBS',
'ram': '16 GiB'
},
't2.2xlarge': {
'id': 't2.2xlarge',
'cores': '8',
'disk': 'EBS',
'ram': '32 GiB'
},
'm4.large': {
'id': 'm4.large',
'cores': '2',
'disk': 'EBS - 450 Mbps',
'ram': '8 GiB'
},
'm4.xlarge': {
'id': 'm4.xlarge',
'cores': '4',
'disk': 'EBS - 750 Mbps',
'ram': '16 GiB'
},
'm4.2xlarge': {
'id': 'm4.2xlarge',
'cores': '8',
'disk': 'EBS - 1000 Mbps',
'ram': '32 GiB'
},
'm4.4xlarge': {
'id': 'm4.4xlarge',
'cores': '16',
'disk': 'EBS - 2000 Mbps',
'ram': '64 GiB'
},
'm4.10xlarge': {
'id': 'm4.10xlarge',
'cores': '40',
'disk': 'EBS - 4000 Mbps',
'ram': '160 GiB'
},
'm4.16xlarge': {
'id': 'm4.16xlarge',
'cores': '64',
'disk': 'EBS - 10000 Mbps',
'ram': '256 GiB'
},
'm3.medium': {
'id': 'm3.medium',
'cores': '1',
'disk': 'SSD (1 x 4)',
'ram': '3.75 GiB'
},
'm3.large': {
'id': 'm3.large',
'cores': '2',
'disk': 'SSD (1 x 32)',
'ram': '7.5 GiB'
},
'm3.xlarge': {
'id': 'm3.xlarge',
'cores': '4',
'disk': 'SSD (2 x 40)',
'ram': '15 GiB'
},
'm3.2xlarge': {
'id': 'm3.2xlarge',
'cores': '8',
'disk': 'SSD (2 x 80)',
'ram': '30 GiB'
},
}
}
return sizes
def avail_images(kwargs=None, 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'
)
if not isinstance(kwargs, dict):
kwargs = {}
if 'owner' in kwargs:
owner = kwargs['owner']
else:
provider = get_configured_provider()
owner = config.get_cloud_config_value(
'owner', provider, __opts__, default='amazon'
)
ret = {}
params = {'Action': 'DescribeImages',
'Owner': owner}
images = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
for image in images:
ret[image['imageId']] = image
return ret
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def keyname(vm_):
'''
Return the keyname
'''
return config.get_cloud_config_value(
'keyname', vm_, __opts__, search_global=False
)
def securitygroup(vm_):
'''
Return the security group
'''
return config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
def iam_profile(vm_):
'''
Return the IAM profile.
The IAM instance profile to associate with the instances.
This is either the Amazon Resource Name (ARN) of the instance profile
or the name of the role.
Type: String
Default: None
Required: No
Example: arn:aws:iam::111111111111:instance-profile/s3access
Example: s3access
'''
return config.get_cloud_config_value(
'iam_profile', vm_, __opts__, search_global=False
)
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
ret = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, default='public_ips',
search_global=False
)
if ret not in ('public_ips', 'private_ips'):
log.warning(
'Invalid ssh_interface: %s. '
'Allowed options are ("public_ips", "private_ips"). '
'Defaulting to "public_ips".', ret
)
ret = 'public_ips'
return ret
def get_ssh_gateway_config(vm_):
'''
Return the ssh_gateway configuration.
'''
ssh_gateway = config.get_cloud_config_value(
'ssh_gateway', vm_, __opts__, default=None,
search_global=False
)
# Check to see if a SSH Gateway will be used.
if not isinstance(ssh_gateway, six.string_types):
return None
# Create dictionary of configuration items
# ssh_gateway
ssh_gateway_config = {'ssh_gateway': ssh_gateway}
# ssh_gateway_port
ssh_gateway_config['ssh_gateway_port'] = config.get_cloud_config_value(
'ssh_gateway_port', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_username
ssh_gateway_config['ssh_gateway_user'] = config.get_cloud_config_value(
'ssh_gateway_username', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_private_key
ssh_gateway_config['ssh_gateway_key'] = config.get_cloud_config_value(
'ssh_gateway_private_key', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_password
ssh_gateway_config['ssh_gateway_password'] = config.get_cloud_config_value(
'ssh_gateway_password', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_command
ssh_gateway_config['ssh_gateway_command'] = config.get_cloud_config_value(
'ssh_gateway_command', vm_, __opts__, default=None,
search_global=False
)
# Check if private key exists
key_filename = ssh_gateway_config['ssh_gateway_key']
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_gateway_private_key \'{0}\' does not exist'
.format(key_filename)
)
elif (
key_filename is None and
not ssh_gateway_config['ssh_gateway_password']
):
raise SaltCloudConfigError(
'No authentication method. Please define: '
' ssh_gateway_password or ssh_gateway_private_key'
)
return ssh_gateway_config
def get_location(vm_=None):
'''
Return the EC2 region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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 = {}
params = {'Action': 'DescribeRegions'}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
for region in result:
ret[region['regionName']] = {
'name': region['regionName'],
'endpoint': region['regionEndpoint'],
}
return ret
def get_availability_zone(vm_):
'''
Return the availability zone to use
'''
avz = config.get_cloud_config_value(
'availability_zone', vm_, __opts__, search_global=False
)
if avz is None:
return None
zones = _list_availability_zones(vm_)
# Validate user-specified AZ
if avz not in zones:
raise SaltCloudException(
'The specified availability zone isn\'t valid in this region: '
'{0}\n'.format(
avz
)
)
# check specified AZ is available
elif zones[avz] != 'available':
raise SaltCloudException(
'The specified availability zone isn\'t currently available: '
'{0}\n'.format(
avz
)
)
return avz
def get_tenancy(vm_):
'''
Returns the Tenancy to use.
Can be "dedicated" or "default". Cannot be present for spot instances.
'''
return config.get_cloud_config_value(
'tenancy', vm_, __opts__, search_global=False
)
def get_imageid(vm_):
'''
Returns the ImageId to use
'''
image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if image.startswith('ami-'):
return image
# a poor man's cache
if not hasattr(get_imageid, 'images'):
get_imageid.images = {}
elif image in get_imageid.images:
return get_imageid.images[image]
params = {'Action': 'DescribeImages',
'Filter.0.Name': 'name',
'Filter.0.Value.0': image}
# Query AWS, sort by 'creationDate' and get the last imageId
_t = lambda x: datetime.datetime.strptime(x['creationDate'], '%Y-%m-%dT%H:%M:%S.%fZ')
image_id = sorted(aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'),
lambda i, j: salt.utils.compat.cmp(_t(i), _t(j))
)[-1]['imageId']
get_imageid.images[image] = image_id
return image_id
def _get_subnetname_id(subnetname):
'''
Returns the SubnetId of a SubnetName to use
'''
params = {'Action': 'DescribeSubnets'}
for subnet in aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'):
tags = subnet.get('tagSet', {}).get('item', {})
if not isinstance(tags, list):
tags = [tags]
for tag in tags:
if tag['key'] == 'Name' and tag['value'] == subnetname:
log.debug(
'AWS Subnet ID of %s is %s',
subnetname, subnet['subnetId']
)
return subnet['subnetId']
return None
def get_subnetid(vm_):
'''
Returns the SubnetId to use
'''
subnetid = config.get_cloud_config_value(
'subnetid', vm_, __opts__, search_global=False
)
if subnetid:
return subnetid
subnetname = config.get_cloud_config_value(
'subnetname', vm_, __opts__, search_global=False
)
if subnetname:
return _get_subnetname_id(subnetname)
return None
def _get_securitygroupname_id(securitygroupname_list):
'''
Returns the SecurityGroupId of a SecurityGroupName to use
'''
securitygroupid_set = set()
if not isinstance(securitygroupname_list, list):
securitygroupname_list = [securitygroupname_list]
params = {'Action': 'DescribeSecurityGroups'}
for sg in aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'):
if sg['groupName'] in securitygroupname_list:
log.debug(
'AWS SecurityGroup ID of %s is %s',
sg['groupName'], sg['groupId']
)
securitygroupid_set.add(sg['groupId'])
return list(securitygroupid_set)
def securitygroupid(vm_):
'''
Returns the SecurityGroupId
'''
securitygroupid_set = set()
securitygroupid_list = config.get_cloud_config_value(
'securitygroupid',
vm_,
__opts__,
search_global=False
)
# If the list is None, then the set will remain empty
# If the list is already a set then calling 'set' on it is a no-op
# If the list is a string, then calling 'set' generates a one-element set
# If the list is anything else, stacktrace
if securitygroupid_list:
securitygroupid_set = securitygroupid_set.union(set(securitygroupid_list))
securitygroupname_list = config.get_cloud_config_value(
'securitygroupname', vm_, __opts__, search_global=False
)
if securitygroupname_list:
if not isinstance(securitygroupname_list, list):
securitygroupname_list = [securitygroupname_list]
params = {'Action': 'DescribeSecurityGroups'}
for sg in aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'):
if sg['groupName'] in securitygroupname_list:
log.debug(
'AWS SecurityGroup ID of %s is %s',
sg['groupName'], sg['groupId']
)
securitygroupid_set.add(sg['groupId'])
return list(securitygroupid_set)
def get_placementgroup(vm_):
'''
Returns the PlacementGroup to use
'''
return config.get_cloud_config_value(
'placementgroup', vm_, __opts__, search_global=False
)
def get_spot_config(vm_):
'''
Returns the spot instance configuration for the provided vm
'''
return config.get_cloud_config_value(
'spot_config', vm_, __opts__, search_global=False
)
def get_provider(vm_=None):
'''
Extract the provider name from vm
'''
if vm_ is None:
provider = __active_provider_name__ or 'ec2'
else:
provider = vm_.get('provider', 'ec2')
if ':' in provider:
prov_comps = provider.split(':')
provider = prov_comps[0]
return provider
def _list_availability_zones(vm_=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeAvailabilityZones',
'Filter.0.Name': 'region-name',
'Filter.0.Value.0': get_location(vm_)}
result = aws.query(params,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
for zone in result:
ret[zone['zoneName']] = zone['zoneState']
return ret
def block_device_mappings(vm_):
'''
Return the block device mapping:
.. code-block:: python
[{'DeviceName': '/dev/sdb', 'VirtualName': 'ephemeral0'},
{'DeviceName': '/dev/sdc', 'VirtualName': 'ephemeral1'}]
'''
return config.get_cloud_config_value(
'block_device_mappings', vm_, __opts__, search_global=True
)
def _request_eip(interface, vm_):
'''
Request and return Elastic IP
'''
params = {'Action': 'AllocateAddress'}
params['Domain'] = interface.setdefault('domain', 'vpc')
eips = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
for eip in eips:
if 'allocationId' in eip:
return eip['allocationId']
return None
def _create_eni_if_necessary(interface, vm_):
'''
Create an Elastic Interface if necessary and return a Network Interface Specification
'''
if 'NetworkInterfaceId' in interface and interface['NetworkInterfaceId'] is not None:
return {'DeviceIndex': interface['DeviceIndex'],
'NetworkInterfaceId': interface['NetworkInterfaceId']}
params = {'Action': 'DescribeSubnets'}
subnet_query = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'SecurityGroupId' not in interface and 'securitygroupname' in interface:
interface['SecurityGroupId'] = _get_securitygroupname_id(interface['securitygroupname'])
if 'SubnetId' not in interface and 'subnetname' in interface:
interface['SubnetId'] = _get_subnetname_id(interface['subnetname'])
subnet_id = _get_subnet_id_for_interface(subnet_query, interface)
if not subnet_id:
raise SaltCloudConfigError(
'No such subnet <{0}>'.format(interface.get('SubnetId'))
)
params = {'SubnetId': subnet_id}
for k in 'Description', 'PrivateIpAddress', 'SecondaryPrivateIpAddressCount':
if k in interface:
params[k] = interface[k]
for k in 'PrivateIpAddresses', 'SecurityGroupId':
if k in interface:
params.update(_param_from_config(k, interface[k]))
if 'AssociatePublicIpAddress' in interface:
# Associating a public address in a VPC only works when the interface is not
# created beforehand, but as a part of the machine creation request.
for k in ('DeviceIndex', 'AssociatePublicIpAddress', 'NetworkInterfaceId'):
if k in interface:
params[k] = interface[k]
params['DeleteOnTermination'] = interface.get('delete_interface_on_terminate', True)
return params
params['Action'] = 'CreateNetworkInterface'
result = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
eni_desc = result[1]
if not eni_desc or not eni_desc.get('networkInterfaceId'):
raise SaltCloudException('Failed to create interface: {0}'.format(result))
eni_id = eni_desc.get('networkInterfaceId')
log.debug(
'Created network interface %s inst %s',
eni_id, interface['DeviceIndex']
)
associate_public_ip = interface.get('AssociatePublicIpAddress', False)
if isinstance(associate_public_ip, six.string_types):
# Assume id of EIP as value
_associate_eip_with_interface(eni_id, associate_public_ip, vm_=vm_)
if interface.get('associate_eip'):
_associate_eip_with_interface(eni_id, interface.get('associate_eip'), vm_=vm_)
elif interface.get('allocate_new_eip'):
_new_eip = _request_eip(interface, vm_)
_associate_eip_with_interface(eni_id, _new_eip, vm_=vm_)
elif interface.get('allocate_new_eips'):
addr_list = _list_interface_private_addrs(eni_desc)
eip_list = []
for idx, addr in enumerate(addr_list):
eip_list.append(_request_eip(interface, vm_))
for idx, addr in enumerate(addr_list):
_associate_eip_with_interface(eni_id, eip_list[idx], addr, vm_=vm_)
if 'Name' in interface:
tag_params = {'Action': 'CreateTags',
'ResourceId.0': eni_id,
'Tag.0.Key': 'Name',
'Tag.0.Value': interface['Name']}
tag_response = aws.query(tag_params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'error' in tag_response:
log.error('Failed to set name of interface {0}')
return {'DeviceIndex': interface['DeviceIndex'],
'NetworkInterfaceId': eni_id}
def _get_subnet_id_for_interface(subnet_query, interface):
for subnet_query_result in subnet_query:
if 'item' in subnet_query_result:
if isinstance(subnet_query_result['item'], dict):
subnet_id = _get_subnet_from_subnet_query(subnet_query_result['item'],
interface)
if subnet_id is not None:
return subnet_id
else:
for subnet in subnet_query_result['item']:
subnet_id = _get_subnet_from_subnet_query(subnet, interface)
if subnet_id is not None:
return subnet_id
def _get_subnet_from_subnet_query(subnet_query, interface):
if 'subnetId' in subnet_query:
if interface.get('SubnetId'):
if subnet_query['subnetId'] == interface['SubnetId']:
return subnet_query['subnetId']
else:
return subnet_query['subnetId']
def _list_interface_private_addrs(eni_desc):
'''
Returns a list of all of the private IP addresses attached to a
network interface. The 'primary' address will be listed first.
'''
primary = eni_desc.get('privateIpAddress')
if not primary:
return None
addresses = [primary]
lst = eni_desc.get('privateIpAddressesSet', {}).get('item', [])
if not isinstance(lst, list):
return addresses
for entry in lst:
if entry.get('primary') == 'true':
continue
if entry.get('privateIpAddress'):
addresses.append(entry.get('privateIpAddress'))
return addresses
def _modify_eni_properties(eni_id, properties=None, vm_=None):
'''
Change properties of the interface
with id eni_id to the values in properties dict
'''
if not isinstance(properties, dict):
raise SaltCloudException(
'ENI properties must be a dictionary'
)
params = {'Action': 'ModifyNetworkInterfaceAttribute',
'NetworkInterfaceId': eni_id}
for k, v in six.iteritems(properties):
params[k] = v
result = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if isinstance(result, dict) and result.get('error'):
raise SaltCloudException(
'Could not change interface <{0}> attributes <\'{1}\'>'.format(
eni_id, properties
)
)
else:
return result
def _associate_eip_with_interface(eni_id, eip_id, private_ip=None, vm_=None):
'''
Accept the id of a network interface, and the id of an elastic ip
address, and associate the two of them, such that traffic sent to the
elastic ip address will be forwarded (NATted) to this network interface.
Optionally specify the private (10.x.x.x) IP address that traffic should
be NATted to - useful if you have multiple IP addresses assigned to an
interface.
'''
params = {'Action': 'AssociateAddress',
'NetworkInterfaceId': eni_id,
'AllocationId': eip_id}
if private_ip:
params['PrivateIpAddress'] = private_ip
result = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if not result[2].get('associationId'):
raise SaltCloudException(
'Could not associate elastic ip address '
'<{0}> with network interface <{1}>'.format(
eip_id, eni_id
)
)
log.debug(
'Associated ElasticIP address %s with interface %s',
eip_id, eni_id
)
return result[2].get('associationId')
def _update_enis(interfaces, instance, vm_=None):
config_enis = {}
instance_enis = []
for interface in interfaces:
if 'DeviceIndex' in interface:
if interface['DeviceIndex'] in config_enis:
log.error(
'Duplicate DeviceIndex in profile. Cannot update ENIs.'
)
return None
config_enis[six.text_type(interface['DeviceIndex'])] = interface
query_enis = instance[0]['instancesSet']['item']['networkInterfaceSet']['item']
if isinstance(query_enis, list):
for query_eni in query_enis:
instance_enis.append((query_eni['networkInterfaceId'], query_eni['attachment']))
else:
instance_enis.append((query_enis['networkInterfaceId'], query_enis['attachment']))
for eni_id, eni_data in instance_enis:
delete_on_terminate = True
if 'DeleteOnTermination' in config_enis[eni_data['deviceIndex']]:
delete_on_terminate = config_enis[eni_data['deviceIndex']]['DeleteOnTermination']
elif 'delete_interface_on_terminate' in config_enis[eni_data['deviceIndex']]:
delete_on_terminate = config_enis[eni_data['deviceIndex']]['delete_interface_on_terminate']
params_attachment = {'Attachment.AttachmentId': eni_data['attachmentId'],
'Attachment.DeleteOnTermination': delete_on_terminate}
set_eni_attachment_attributes = _modify_eni_properties(eni_id, params_attachment, vm_=vm_)
if 'SourceDestCheck' in config_enis[eni_data['deviceIndex']]:
params_sourcedest = {'SourceDestCheck.Value': config_enis[eni_data['deviceIndex']]['SourceDestCheck']}
set_eni_sourcedest_property = _modify_eni_properties(eni_id, params_sourcedest, vm_=vm_)
return None
def _param_from_config(key, data):
'''
Return EC2 API parameters based on the given config data.
Examples:
1. List of dictionaries
>>> data = [
... {'DeviceIndex': 0, 'SubnetId': 'subid0',
... 'AssociatePublicIpAddress': True},
... {'DeviceIndex': 1,
... 'SubnetId': 'subid1',
... 'PrivateIpAddress': '192.168.1.128'}
... ]
>>> _param_from_config('NetworkInterface', data)
... {'NetworkInterface.0.SubnetId': 'subid0',
... 'NetworkInterface.0.DeviceIndex': 0,
... 'NetworkInterface.1.SubnetId': 'subid1',
... 'NetworkInterface.1.PrivateIpAddress': '192.168.1.128',
... 'NetworkInterface.0.AssociatePublicIpAddress': 'true',
... 'NetworkInterface.1.DeviceIndex': 1}
2. List of nested dictionaries
>>> data = [
... {'DeviceName': '/dev/sdf',
... 'Ebs': {
... 'SnapshotId': 'dummy0',
... 'VolumeSize': 200,
... 'VolumeType': 'standard'}},
... {'DeviceName': '/dev/sdg',
... 'Ebs': {
... 'SnapshotId': 'dummy1',
... 'VolumeSize': 100,
... 'VolumeType': 'standard'}}
... ]
>>> _param_from_config('BlockDeviceMapping', data)
... {'BlockDeviceMapping.0.Ebs.VolumeType': 'standard',
... 'BlockDeviceMapping.1.Ebs.SnapshotId': 'dummy1',
... 'BlockDeviceMapping.0.Ebs.VolumeSize': 200,
... 'BlockDeviceMapping.0.Ebs.SnapshotId': 'dummy0',
... 'BlockDeviceMapping.1.Ebs.VolumeType': 'standard',
... 'BlockDeviceMapping.1.DeviceName': '/dev/sdg',
... 'BlockDeviceMapping.1.Ebs.VolumeSize': 100,
... 'BlockDeviceMapping.0.DeviceName': '/dev/sdf'}
3. Dictionary of dictionaries
>>> data = { 'Arn': 'dummyarn', 'Name': 'Tester' }
>>> _param_from_config('IamInstanceProfile', data)
{'IamInstanceProfile.Arn': 'dummyarn', 'IamInstanceProfile.Name': 'Tester'}
'''
param = {}
if isinstance(data, dict):
for k, v in six.iteritems(data):
param.update(_param_from_config('{0}.{1}'.format(key, k), v))
elif isinstance(data, list) or isinstance(data, tuple):
for idx, conf_item in enumerate(data):
prefix = '{0}.{1}'.format(key, idx)
param.update(_param_from_config(prefix, conf_item))
else:
if isinstance(data, bool):
# convert boolean True/False to 'true'/'false'
param.update({key: six.text_type(data).lower()})
else:
param.update({key: data})
return param
def request_instance(vm_=None, call=None):
'''
Put together all of the information necessary to request an instance on EC2,
and then fire off the request the instance.
Returns data about the instance
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
location = vm_.get('location', get_location(vm_))
# do we launch a regular vm or a spot instance?
# see http://goo.gl/hYZ13f for more information on EC2 API
spot_config = get_spot_config(vm_)
if spot_config is not None:
if 'spot_price' not in spot_config:
raise SaltCloudSystemExit(
'Spot instance config for {0} requires a spot_price '
'attribute.'.format(vm_['name'])
)
params = {'Action': 'RequestSpotInstances',
'InstanceCount': '1',
'Type': spot_config['type']
if 'type' in spot_config else 'one-time',
'SpotPrice': spot_config['spot_price']}
# All of the necessary launch parameters for a VM when using
# spot instances are the same except for the prefix below
# being tacked on.
spot_prefix = 'LaunchSpecification.'
# regular EC2 instance
else:
# WARNING! EXPERIMENTAL!
# This allows more than one instance to be spun up in a single call.
# The first instance will be called by the name provided, but all other
# instances will be nameless (or more specifically, they will use the
# InstanceId as the name). This interface is expected to change, so
# use at your own risk.
min_instance = config.get_cloud_config_value(
'min_instance', vm_, __opts__, search_global=False, default=1
)
max_instance = config.get_cloud_config_value(
'max_instance', vm_, __opts__, search_global=False, default=1
)
params = {'Action': 'RunInstances',
'MinCount': min_instance,
'MaxCount': max_instance}
# Normal instances should have no prefix.
spot_prefix = ''
image_id = get_imageid(vm_)
params[spot_prefix + 'ImageId'] = image_id
userdata = None
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is None:
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
else:
log.trace('userdata_file: %s', userdata_file)
if os.path.exists(userdata_file):
with salt.utils.files.fopen(userdata_file, 'r') as fh_:
userdata = salt.utils.stringutils.to_unicode(fh_.read())
userdata = salt.utils.cloud.userdata_template(__opts__, vm_, userdata)
if userdata is not None:
try:
params[spot_prefix + 'UserData'] = base64.b64encode(
salt.utils.stringutils.to_bytes(userdata)
)
except Exception as exc:
log.exception('Failed to encode userdata: %s', exc)
vm_size = config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
)
params[spot_prefix + 'InstanceType'] = vm_size
ex_keyname = keyname(vm_)
if ex_keyname:
params[spot_prefix + 'KeyName'] = ex_keyname
ex_securitygroup = securitygroup(vm_)
if ex_securitygroup:
if not isinstance(ex_securitygroup, list):
params[spot_prefix + 'SecurityGroup.1'] = ex_securitygroup
else:
for counter, sg_ in enumerate(ex_securitygroup):
params[spot_prefix + 'SecurityGroup.{0}'.format(counter)] = sg_
ex_iam_profile = iam_profile(vm_)
if ex_iam_profile:
try:
if ex_iam_profile.startswith('arn:aws:iam:'):
params[
spot_prefix + 'IamInstanceProfile.Arn'
] = ex_iam_profile
else:
params[
spot_prefix + 'IamInstanceProfile.Name'
] = ex_iam_profile
except AttributeError:
raise SaltCloudConfigError(
'\'iam_profile\' should be a string value.'
)
az_ = get_availability_zone(vm_)
if az_ is not None:
params[spot_prefix + 'Placement.AvailabilityZone'] = az_
tenancy_ = get_tenancy(vm_)
if tenancy_ is not None:
if spot_config is not None:
raise SaltCloudConfigError(
'Spot instance config for {0} does not support '
'specifying tenancy.'.format(vm_['name'])
)
params['Placement.Tenancy'] = tenancy_
subnetid_ = get_subnetid(vm_)
if subnetid_ is not None:
params[spot_prefix + 'SubnetId'] = subnetid_
ex_securitygroupid = securitygroupid(vm_)
if ex_securitygroupid:
if not isinstance(ex_securitygroupid, list):
params[spot_prefix + 'SecurityGroupId.1'] = ex_securitygroupid
else:
for counter, sg_ in enumerate(ex_securitygroupid):
params[
spot_prefix + 'SecurityGroupId.{0}'.format(counter)
] = sg_
placementgroup_ = get_placementgroup(vm_)
if placementgroup_ is not None:
params[spot_prefix + 'Placement.GroupName'] = placementgroup_
blockdevicemappings_holder = block_device_mappings(vm_)
if blockdevicemappings_holder:
for _bd in blockdevicemappings_holder:
if 'tag' in _bd:
_bd.pop('tag')
ex_blockdevicemappings = blockdevicemappings_holder
if ex_blockdevicemappings:
params.update(_param_from_config(spot_prefix + 'BlockDeviceMapping',
ex_blockdevicemappings))
network_interfaces = config.get_cloud_config_value(
'network_interfaces',
vm_,
__opts__,
search_global=False
)
if network_interfaces:
eni_devices = []
for interface in network_interfaces:
log.debug('Create network interface: %s', interface)
_new_eni = _create_eni_if_necessary(interface, vm_)
eni_devices.append(_new_eni)
params.update(_param_from_config(spot_prefix + 'NetworkInterface',
eni_devices))
set_ebs_optimized = config.get_cloud_config_value(
'ebs_optimized', vm_, __opts__, search_global=False
)
if set_ebs_optimized is not None:
if not isinstance(set_ebs_optimized, bool):
raise SaltCloudConfigError(
'\'ebs_optimized\' should be a boolean value.'
)
params[spot_prefix + 'EbsOptimized'] = set_ebs_optimized
set_del_root_vol_on_destroy = config.get_cloud_config_value(
'del_root_vol_on_destroy', vm_, __opts__, search_global=False
)
set_termination_protection = config.get_cloud_config_value(
'termination_protection', vm_, __opts__, search_global=False
)
if set_termination_protection is not None:
if not isinstance(set_termination_protection, bool):
raise SaltCloudConfigError(
'\'termination_protection\' should be a boolean value.'
)
params.update(_param_from_config(spot_prefix + 'DisableApiTermination',
set_termination_protection))
if set_del_root_vol_on_destroy and not isinstance(set_del_root_vol_on_destroy, bool):
raise SaltCloudConfigError(
'\'del_root_vol_on_destroy\' should be a boolean value.'
)
vm_['set_del_root_vol_on_destroy'] = set_del_root_vol_on_destroy
if set_del_root_vol_on_destroy:
# first make sure to look up the root device name
# as Ubuntu and CentOS (and most likely other OSs)
# use different device identifiers
log.info('Attempting to look up root device name for image id %s on '
'VM %s', image_id, vm_['name'])
rd_params = {
'Action': 'DescribeImages',
'ImageId.1': image_id
}
try:
rd_data = aws.query(rd_params,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'error' in rd_data:
return rd_data['error']
log.debug('EC2 Response: \'%s\'', rd_data)
except Exception as exc:
log.error(
'Error getting root device name for image id %s for '
'VM %s: \n%s', image_id, vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
raise
# make sure we have a response
if not rd_data:
err_msg = 'There was an error querying EC2 for the root device ' \
'of image id {0}. Empty response.'.format(image_id)
raise SaltCloudSystemExit(err_msg)
# pull the root device name from the result and use it when
# launching the new VM
rd_name = None
rd_type = None
if 'blockDeviceMapping' in rd_data[0]:
# Some ami instances do not have a root volume. Ignore such cases
if rd_data[0]['blockDeviceMapping'] is not None:
item = rd_data[0]['blockDeviceMapping']['item']
if isinstance(item, list):
item = item[0]
rd_name = item['deviceName']
# Grab the volume type
rd_type = item['ebs'].get('volumeType', None)
log.info('Found root device name: %s', rd_name)
if rd_name is not None:
if ex_blockdevicemappings:
dev_list = [
dev['DeviceName'] for dev in ex_blockdevicemappings
]
else:
dev_list = []
if rd_name in dev_list:
# Device already listed, just grab the index
dev_index = dev_list.index(rd_name)
else:
dev_index = len(dev_list)
# Add the device name in since it wasn't already there
params[
'{0}BlockDeviceMapping.{1}.DeviceName'.format(
spot_prefix, dev_index
)
] = rd_name
# Set the termination value
termination_key = '{0}BlockDeviceMapping.{1}.Ebs.DeleteOnTermination'.format(spot_prefix, dev_index)
params[termination_key] = six.text_type(set_del_root_vol_on_destroy).lower()
# Use default volume type if not specified
if ex_blockdevicemappings and dev_index < len(ex_blockdevicemappings) and \
'Ebs.VolumeType' not in ex_blockdevicemappings[dev_index]:
type_key = '{0}BlockDeviceMapping.{1}.Ebs.VolumeType'.format(spot_prefix, dev_index)
params[type_key] = rd_type
set_del_all_vols_on_destroy = config.get_cloud_config_value(
'del_all_vols_on_destroy', vm_, __opts__, search_global=False, default=False
)
if set_del_all_vols_on_destroy and not isinstance(set_del_all_vols_on_destroy, bool):
raise SaltCloudConfigError(
'\'del_all_vols_on_destroy\' should be a boolean value.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={
'kwargs': __utils__['cloud.filter_event'](
'requesting', params, list(params)
),
'location': location,
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
provider = get_provider(vm_)
try:
data = aws.query(params,
'instancesSet',
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if 'error' in data:
return data['error']
except Exception as exc:
log.error(
'Error creating %s on EC2 when trying to run the initial '
'deployment: \n%s', vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
raise
# if we're using spot instances, we need to wait for the spot request
# to become active before we continue
if spot_config:
sir_id = data[0]['spotInstanceRequestId']
vm_['spotRequestId'] = sir_id
def __query_spot_instance_request(sir_id, location):
params = {'Action': 'DescribeSpotInstanceRequests',
'SpotInstanceRequestId.1': sir_id}
data = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if not data:
log.error(
'There was an error while querying EC2. Empty response'
)
# Trigger a failure in the wait for spot instance method
return False
if isinstance(data, dict) and 'error' in data:
log.warning('There was an error in the query. %s', data['error'])
# Trigger a failure in the wait for spot instance method
return False
log.debug('Returned query data: %s', data)
state = data[0].get('state')
if state == 'active':
return data
if state == 'open':
# Still waiting for an active state
log.info('Spot instance status: %s', data[0]['status']['message'])
return None
if state in ['cancelled', 'failed', 'closed']:
# Request will never be active, fail
log.error('Spot instance request resulted in state \'{0}\'. '
'Nothing else we can do here.')
return False
__utils__['cloud.fire_event'](
'event',
'waiting for spot instance',
'salt/cloud/{0}/waiting_for_spot'.format(vm_['name']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = _wait_for_spot_instance(
__query_spot_instance_request,
update_args=(sir_id, location),
timeout=config.get_cloud_config_value(
'wait_for_spot_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_spot_interval', vm_, __opts__, default=30),
interval_multiplier=config.get_cloud_config_value(
'wait_for_spot_interval_multiplier',
vm_,
__opts__,
default=1),
max_failures=config.get_cloud_config_value(
'wait_for_spot_max_failures',
vm_,
__opts__,
default=10),
)
log.debug('wait_for_spot_instance data %s', data)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# Cancel the existing spot instance request
params = {'Action': 'CancelSpotInstanceRequests',
'SpotInstanceRequestId.1': sir_id}
data = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
log.debug('Canceled spot instance request %s. Data '
'returned: %s', sir_id, data)
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
return data, vm_
def query_instance(vm_=None, call=None):
'''
Query an instance upon creation from the EC2 API
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The query_instance action must be called with -a or --action.'
)
instance_id = vm_['instance_id']
location = vm_.get('location', get_location(vm_))
__utils__['cloud.fire_event'](
'event',
'querying instance',
'salt/cloud/{0}/querying'.format(vm_['name']),
args={'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('The new VM instance_id is %s', instance_id)
params = {'Action': 'DescribeInstances',
'InstanceId.1': instance_id}
provider = get_provider(vm_)
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
data, requesturl = aws.query(params, # pylint: disable=unbalanced-tuple-unpacking
location=location,
provider=provider,
opts=__opts__,
return_url=True,
sigver='4')
log.debug('The query returned: %s', data)
if isinstance(data, dict) and 'error' in data:
log.warning(
'There was an error in the query. %s attempts '
'remaining: %s', attempts, data['error']
)
elif isinstance(data, list) and not data:
log.warning(
'Query returned an empty list. %s attempts '
'remaining.', attempts
)
else:
break
aws.sleep_exponential_backoff(attempts)
attempts += 1
continue
else:
raise SaltCloudSystemExit(
'An error occurred while creating VM: {0}'.format(data['error'])
)
def __query_ip_address(params, url): # pylint: disable=W0613
data = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if not data:
log.error(
'There was an error while querying EC2. Empty response'
)
# Trigger a failure in the wait for IP function
return False
if isinstance(data, dict) and 'error' in data:
log.warning('There was an error in the query. %s', data['error'])
# Trigger a failure in the wait for IP function
return False
log.debug('Returned query data: %s', data)
if ssh_interface(vm_) == 'public_ips':
if 'ipAddress' in data[0]['instancesSet']['item']:
return data
else:
log.error(
'Public IP not detected.'
)
if ssh_interface(vm_) == 'private_ips':
if 'privateIpAddress' in data[0]['instancesSet']['item']:
return data
else:
log.error(
'Private IP not detected.'
)
try:
data = salt.utils.cloud.wait_for_ip(
__query_ip_address,
update_args=(params, requesturl),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value(
'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if 'reactor' in vm_ and vm_['reactor'] is True:
__utils__['cloud.fire_event'](
'event',
'instance queried',
'salt/cloud/{0}/query_reactor'.format(vm_['name']),
args={'data': data},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return data
def wait_for_instance(
vm_=None,
data=None,
ip_address=None,
display_ssh_output=True,
call=None,
):
'''
Wait for an instance upon creation from the EC2 API, to become available
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The wait_for_instance action must be called with -a or --action.'
)
if vm_ is None:
vm_ = {}
if data is None:
data = {}
ssh_gateway_config = vm_.get(
'gateway', get_ssh_gateway_config(vm_)
)
__utils__['cloud.fire_event'](
'event',
'waiting for ssh',
'salt/cloud/{0}/waiting_for_ssh'.format(vm_['name']),
args={'ip_address': ip_address},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
ssh_connect_timeout = config.get_cloud_config_value(
'ssh_connect_timeout', vm_, __opts__, 900 # 15 minutes
)
ssh_port = config.get_cloud_config_value(
'ssh_port', vm_, __opts__, 22
)
if config.get_cloud_config_value('win_installer', vm_, __opts__):
username = config.get_cloud_config_value(
'win_username', vm_, __opts__, default='Administrator'
)
win_passwd = config.get_cloud_config_value(
'win_password', vm_, __opts__, default=''
)
win_deploy_auth_retries = config.get_cloud_config_value(
'win_deploy_auth_retries', vm_, __opts__, default=10
)
win_deploy_auth_retry_delay = config.get_cloud_config_value(
'win_deploy_auth_retry_delay', vm_, __opts__, default=1
)
use_winrm = config.get_cloud_config_value(
'use_winrm', vm_, __opts__, default=False
)
winrm_verify_ssl = config.get_cloud_config_value(
'winrm_verify_ssl', vm_, __opts__, default=True
)
if win_passwd and win_passwd == 'auto':
log.debug('Waiting for auto-generated Windows EC2 password')
while True:
password_data = get_password_data(
name=vm_['name'],
kwargs={
'key_file': vm_['private_key'],
},
call='action',
)
win_passwd = password_data.get('password', None)
if win_passwd is None:
log.debug(password_data)
# This wait is so high, because the password is unlikely to
# be generated for at least 4 minutes
time.sleep(60)
else:
logging_data = password_data
logging_data['password'] = 'XXX-REDACTED-XXX'
logging_data['passwordData'] = 'XXX-REDACTED-XXX'
log.debug(logging_data)
vm_['win_password'] = win_passwd
break
# SMB used whether psexec or winrm
if not salt.utils.cloud.wait_for_port(ip_address,
port=445,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to connect to remote windows host'
)
# If not using winrm keep same psexec behavior
if not use_winrm:
log.debug('Trying to authenticate via SMB using psexec')
if not salt.utils.cloud.validate_windows_cred(ip_address,
username,
win_passwd,
retries=win_deploy_auth_retries,
retry_delay=win_deploy_auth_retry_delay):
raise SaltCloudSystemExit(
'Failed to authenticate against remote windows host (smb)'
)
# If using winrm
else:
# Default HTTPS port can be changed in cloud configuration
winrm_port = config.get_cloud_config_value(
'winrm_port', vm_, __opts__, default=5986
)
# Wait for winrm port to be available
if not salt.utils.cloud.wait_for_port(ip_address,
port=winrm_port,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to connect to remote windows host (winrm)'
)
log.debug('Trying to authenticate via Winrm using pywinrm')
if not salt.utils.cloud.wait_for_winrm(ip_address,
winrm_port,
username,
win_passwd,
timeout=ssh_connect_timeout,
verify=winrm_verify_ssl):
raise SaltCloudSystemExit(
'Failed to authenticate against remote windows host'
)
elif salt.utils.cloud.wait_for_port(ip_address,
port=ssh_port,
timeout=ssh_connect_timeout,
gateway=ssh_gateway_config
):
# If a known_hosts_file is configured, this instance will not be
# accessible until it has a host key. Since this is provided on
# supported instances by cloud-init, and viewable to us only from the
# console output (which may take several minutes to become available,
# we have some more waiting to do here.
known_hosts_file = config.get_cloud_config_value(
'known_hosts_file', vm_, __opts__, default=None
)
if known_hosts_file:
console = {}
while 'output_decoded' not in console:
console = get_console_output(
instance_id=vm_['instance_id'],
call='action',
location=get_location(vm_)
)
pprint.pprint(console)
time.sleep(5)
output = salt.utils.stringutils.to_unicode(console['output_decoded'])
comps = output.split('-----BEGIN SSH HOST KEY KEYS-----')
if len(comps) < 2:
# Fail; there are no host keys
return False
comps = comps[1].split('-----END SSH HOST KEY KEYS-----')
keys = ''
for line in comps[0].splitlines():
if not line:
continue
keys += '\n{0} {1}'.format(ip_address, line)
with salt.utils.files.fopen(known_hosts_file, 'a') as fp_:
fp_.write(salt.utils.stringutils.to_str(keys))
fp_.close()
for user in vm_['usernames']:
if salt.utils.cloud.wait_for_passwd(
host=ip_address,
port=ssh_port,
username=user,
ssh_timeout=config.get_cloud_config_value(
'wait_for_passwd_timeout', vm_, __opts__, default=1 * 60
),
key_filename=vm_['key_filename'],
display_ssh_output=display_ssh_output,
gateway=ssh_gateway_config,
maxtries=config.get_cloud_config_value(
'wait_for_passwd_maxtries', vm_, __opts__, default=15
),
known_hosts_file=config.get_cloud_config_value(
'known_hosts_file', vm_, __opts__,
default='/dev/null'
),
):
__opts__['ssh_username'] = user
vm_['ssh_username'] = user
break
else:
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
else:
raise SaltCloudSystemExit(
'Failed to connect to remote ssh'
)
if 'reactor' in vm_ and vm_['reactor'] is True:
__utils__['cloud.fire_event'](
'event',
'ssh is available',
'salt/cloud/{0}/ssh_ready_reactor'.format(vm_['name']),
args={'ip_address': ip_address},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return vm_
def _validate_key_path_and_mode(key_filename):
if key_filename is None:
raise SaltCloudSystemExit(
'The required \'private_key\' configuration setting is missing from the '
'\'ec2\' driver.'
)
if not os.path.exists(key_filename):
raise SaltCloudSystemExit(
'The EC2 key file \'{0}\' does not exist.\n'.format(
key_filename
)
)
key_mode = stat.S_IMODE(os.stat(key_filename).st_mode)
if key_mode not in (0o400, 0o600):
raise SaltCloudSystemExit(
'The EC2 key file \'{0}\' needs to be set to mode 0400 or 0600.\n'.format(
key_filename
)
)
return True
def create(vm_=None, call=None):
'''
Create a single VM from a data dict
'''
if call:
raise SaltCloudSystemExit(
'You cannot create an instance with -a or -f.'
)
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'ec2',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
# Check for private_key and keyfile name for bootstrapping new instances
deploy = config.get_cloud_config_value(
'deploy', vm_, __opts__, default=True
)
win_password = config.get_cloud_config_value(
'win_password', vm_, __opts__, default=''
)
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
if deploy:
# The private_key and keyname settings are only needed for bootstrapping
# new instances when deploy is True
_validate_key_path_and_mode(key_filename)
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](
vm_['name'], vm_['profile'], 'ec2', vm_['driver']
)
vm_['key_filename'] = key_filename
# wait_for_instance requires private_key
vm_['private_key'] = key_filename
# Get SSH Gateway config early to verify the private_key,
# if used, exists or not. We don't want to deploy an instance
# and not be able to access it via the gateway.
vm_['gateway'] = get_ssh_gateway_config(vm_)
location = get_location(vm_)
vm_['location'] = location
log.info('Creating Cloud VM %s in %s', vm_['name'], location)
vm_['usernames'] = salt.utils.cloud.ssh_usernames(
vm_,
__opts__,
default_users=(
'ec2-user', # Amazon Linux, Fedora, RHEL; FreeBSD
'centos', # CentOS AMIs from AWS Marketplace
'ubuntu', # Ubuntu
'admin', # Debian GNU/Linux
'bitnami', # BitNami AMIs
'root' # Last resort, default user on RHEL 5, SUSE
)
)
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
if keyname(vm_) is None:
raise SaltCloudSystemExit(
'The required \'keyname\' configuration setting is missing from the '
'\'ec2\' driver.'
)
data, vm_ = request_instance(vm_, location)
# If data is a str, it's an error
if isinstance(data, six.string_types):
log.error('Error requesting instance: %s', data)
return {}
# Pull the instance ID, valid for both spot and normal instances
# Multiple instances may have been spun up, get all their IDs
vm_['instance_id_list'] = []
for instance in data:
vm_['instance_id_list'].append(instance['instanceId'])
vm_['instance_id'] = vm_['instance_id_list'].pop()
if vm_['instance_id_list']:
# Multiple instances were spun up, get one now, and queue the rest
queue_instances(vm_['instance_id_list'])
# Wait for vital information, such as IP addresses, to be available
# for the new instance
data = query_instance(vm_)
# Now that the instance is available, tag it appropriately. Should
# mitigate race conditions with tags
tags = config.get_cloud_config_value('tag',
vm_,
__opts__,
{},
search_global=False)
if not isinstance(tags, dict):
raise SaltCloudConfigError(
'\'tag\' should be a dict.'
)
for value in six.itervalues(tags):
if not isinstance(value, six.string_types):
raise SaltCloudConfigError(
'\'tag\' values must be strings. Try quoting the values. '
'e.g. "2013-09-19T20:09:46Z".'
)
tags['Name'] = vm_['name']
__utils__['cloud.fire_event'](
'event',
'setting tags',
'salt/cloud/{0}/tagging'.format(vm_['name']),
args={'tags': tags},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
salt.utils.cloud.wait_for_fun(
set_tags,
timeout=30,
name=vm_['name'],
tags=tags,
instance_id=vm_['instance_id'],
call='action',
location=location
)
# Once instance tags are set, tag the spot request if configured
if 'spot_config' in vm_ and 'tag' in vm_['spot_config']:
if not isinstance(vm_['spot_config']['tag'], dict):
raise SaltCloudConfigError(
'\'tag\' should be a dict.'
)
for value in six.itervalues(vm_['spot_config']['tag']):
if not isinstance(value, str):
raise SaltCloudConfigError(
'\'tag\' values must be strings. Try quoting the values. '
'e.g. "2013-09-19T20:09:46Z".'
)
spot_request_tags = {}
if 'spotRequestId' not in vm_:
raise SaltCloudConfigError('Failed to find spotRequestId')
sir_id = vm_['spotRequestId']
spot_request_tags['Name'] = vm_['name']
for k, v in six.iteritems(vm_['spot_config']['tag']):
spot_request_tags[k] = v
__utils__['cloud.fire_event'](
'event',
'setting tags',
'salt/cloud/spot_request_{0}/tagging'.format(sir_id),
args={'tags': spot_request_tags},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
salt.utils.cloud.wait_for_fun(
set_tags,
timeout=30,
name=vm_['name'],
tags=spot_request_tags,
instance_id=sir_id,
call='action',
location=location
)
network_interfaces = config.get_cloud_config_value(
'network_interfaces',
vm_,
__opts__,
search_global=False
)
if network_interfaces:
_update_enis(network_interfaces, data, vm_)
# At this point, the node is created and tagged, and now needs to be
# bootstrapped, once the necessary port is available.
log.info('Created node %s', vm_['name'])
instance = data[0]['instancesSet']['item']
# Wait for the necessary port to become available to bootstrap
if ssh_interface(vm_) == 'private_ips':
ip_address = instance['privateIpAddress']
log.info('Salt node data. Private_ip: %s', ip_address)
else:
ip_address = instance['ipAddress']
log.info('Salt node data. Public_ip: %s', ip_address)
vm_['ssh_host'] = ip_address
if salt.utils.cloud.get_salt_interface(vm_, __opts__) == 'private_ips':
salt_ip_address = instance['privateIpAddress']
log.info('Salt interface set to: %s', salt_ip_address)
else:
salt_ip_address = instance['ipAddress']
log.debug('Salt interface set to: %s', salt_ip_address)
vm_['salt_host'] = salt_ip_address
if deploy:
display_ssh_output = config.get_cloud_config_value(
'display_ssh_output', vm_, __opts__, default=True
)
vm_ = wait_for_instance(
vm_, data, ip_address, display_ssh_output
)
# The instance is booted and accessible, let's Salt it!
ret = instance.copy()
# Get ANY defined volumes settings, merging data, in the following order
# 1. VM config
# 2. Profile config
# 3. Global configuration
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args={'volumes': volumes},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'zone': ret['placement']['availabilityZone'],
'instance_id': ret['instanceId'],
'del_all_vols_on_destroy': vm_.get('del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
# Associate instance with a ssm document, if present
ssm_document = config.get_cloud_config_value(
'ssm_document', vm_, __opts__, None, search_global=False
)
if ssm_document:
log.debug('Associating with ssm document: %s', ssm_document)
assoc = ssm_create_association(
vm_['name'],
{'ssm_document': ssm_document},
instance_id=vm_['instance_id'],
call='action'
)
if isinstance(assoc, dict) and assoc.get('error', None):
log.error(
'Failed to associate instance %s with ssm document %s',
vm_['instance_id'], ssm_document
)
return {}
for key, value in six.iteritems(__utils__['cloud.bootstrap'](vm_, __opts__)):
ret.setdefault(key, value)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(instance)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': vm_['instance_id'],
}
if volumes:
event_data['volumes'] = volumes
if ssm_document:
event_data['ssm_document'] = ssm_document
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# Ensure that the latest node data is returned
node = _get_node(instance_id=vm_['instance_id'])
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
ret.update(node)
# Add any block device tags specified
ex_blockdevicetags = {}
blockdevicemappings_holder = block_device_mappings(vm_)
if blockdevicemappings_holder:
for _bd in blockdevicemappings_holder:
if 'tag' in _bd:
ex_blockdevicetags[_bd['DeviceName']] = _bd['tag']
block_device_volume_id_map = {}
if ex_blockdevicetags:
for _device, _map in six.iteritems(ret['blockDeviceMapping']):
bd_items = []
if isinstance(_map, dict):
bd_items.append(_map)
else:
for mapitem in _map:
bd_items.append(mapitem)
for blockitem in bd_items:
if blockitem['deviceName'] in ex_blockdevicetags and 'Name' not in ex_blockdevicetags[blockitem['deviceName']]:
ex_blockdevicetags[blockitem['deviceName']]['Name'] = vm_['name']
if blockitem['deviceName'] in ex_blockdevicetags:
block_device_volume_id_map[blockitem[ret['rootDeviceType']]['volumeId']] = ex_blockdevicetags[blockitem['deviceName']]
if block_device_volume_id_map:
for volid, tags in six.iteritems(block_device_volume_id_map):
__utils__['cloud.fire_event'](
'event',
'setting tags',
'salt/cloud/block_volume_{0}/tagging'.format(str(volid)),
args={'tags': tags},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.wait_for_fun'](
set_tags,
timeout=30,
name=vm_['name'],
tags=tags,
resource_id=volid,
call='action',
location=location
)
return ret
def queue_instances(instances):
'''
Queue a set of instances to be provisioned later. Expects a list.
Currently this only queries node data, and then places it in the cloud
cache (if configured). If the salt-cloud-reactor is being used, these
instances will be automatically provisioned using that.
For more information about the salt-cloud-reactor, see:
https://github.com/saltstack-formulas/salt-cloud-reactor
'''
for instance_id in instances:
node = _get_node(instance_id=instance_id)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if 'instance_id' not in kwargs:
kwargs['instance_id'] = _get_node(name)['instanceId']
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
ret = []
for volume in volumes:
created = False
volume_name = '{0} on {1}'.format(volume['device'], name)
volume_dict = {
'volume_name': volume_name,
'zone': kwargs['zone']
}
if 'volume_id' in volume:
volume_dict['volume_id'] = volume['volume_id']
elif 'snapshot' in volume:
volume_dict['snapshot'] = volume['snapshot']
elif 'size' in volume:
volume_dict['size'] = volume['size']
else:
raise SaltCloudConfigError(
'Cannot create volume. Please define one of \'volume_id\', '
'\'snapshot\', or \'size\''
)
if 'tags' in volume:
volume_dict['tags'] = volume['tags']
if 'type' in volume:
volume_dict['type'] = volume['type']
if 'iops' in volume:
volume_dict['iops'] = volume['iops']
if 'encrypted' in volume:
volume_dict['encrypted'] = volume['encrypted']
if 'kmskeyid' in volume:
volume_dict['kmskeyid'] = volume['kmskeyid']
if 'volume_id' not in volume_dict:
created_volume = create_volume(volume_dict, call='function', wait_to_finish=wait_to_finish)
created = True
if 'volumeId' in created_volume:
volume_dict['volume_id'] = created_volume['volumeId']
attach = attach_volume(
name,
{'volume_id': volume_dict['volume_id'],
'device': volume['device']},
instance_id=kwargs['instance_id'],
call='action'
)
# Update the delvol parameter for this volume
delvols_on_destroy = kwargs.get('del_all_vols_on_destroy', None)
if attach and created and delvols_on_destroy is not None:
_toggle_delvol(instance_id=kwargs['instance_id'],
device=volume['device'],
value=delvols_on_destroy)
if attach:
msg = (
'{0} attached to {1} (aka {2}) as device {3}'.format(
volume_dict['volume_id'],
kwargs['instance_id'],
name,
volume['device']
)
)
log.info(msg)
ret.append(msg)
return ret
def stop(name, call=None):
'''
Stop a node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instance_id = _get_node(name)['instanceId']
__utils__['cloud.fire_event'](
'event',
'stopping instance',
'salt/cloud/{0}/stopping'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
params = {'Action': 'StopInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return result
def start(name, call=None):
'''
Start a node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instance_id = _get_node(name)['instanceId']
__utils__['cloud.fire_event'](
'event',
'starting instance',
'salt/cloud/{0}/starting'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
params = {'Action': 'StartInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return result
def set_tags(name=None,
tags=None,
call=None,
location=None,
instance_id=None,
resource_id=None,
kwargs=None): # pylint: disable=W0613
'''
Set tags for a resource. Normally a VM name or instance_id is passed in,
but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a set_tags mymachine tag1=somestuff tag2='Other stuff'
salt-cloud -a set_tags resource_id=vol-3267ab32 tag=somestuff
'''
if kwargs is None:
kwargs = {}
if location is None:
location = get_location()
if instance_id is None:
if 'resource_id' in kwargs:
resource_id = kwargs['resource_id']
del kwargs['resource_id']
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
del kwargs['instance_id']
if resource_id is None:
if instance_id is None:
instance_id = _get_node(name=name, instance_id=None, location=location)['instanceId']
else:
instance_id = resource_id
# This second check is a safety, in case the above still failed to produce
# a usable ID
if instance_id is None:
return {
'Error': 'A valid instance_id or resource_id was not specified.'
}
params = {'Action': 'CreateTags',
'ResourceId.1': instance_id}
log.debug('Tags to set for %s: %s', name, tags)
if kwargs and not tags:
tags = kwargs
for idx, (tag_k, tag_v) in enumerate(six.iteritems(tags)):
params['Tag.{0}.Key'.format(idx)] = tag_k
params['Tag.{0}.Value'.format(idx)] = tag_v
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
aws.query(params,
setname='tagSet',
location=location,
provider=get_provider(),
opts=__opts__,
sigver='4')
settags = get_tags(
instance_id=instance_id, call='action', location=location
)
log.debug('Setting the tags returned: %s', settags)
failed_to_set_tags = False
for tag in settags:
if tag['key'] not in tags:
# We were not setting this tag
continue
if tag.get('value') is None and tags.get(tag['key']) == '':
# This is a correctly set tag with no value
continue
if six.text_type(tags.get(tag['key'])) != six.text_type(tag['value']):
# Not set to the proper value!?
log.debug(
'Setting the tag %s returned %s instead of %s',
tag['key'], tags.get(tag['key']), tag['value']
)
failed_to_set_tags = True
break
if failed_to_set_tags:
log.warning('Failed to set tags. Remaining attempts %s', attempts)
attempts += 1
aws.sleep_exponential_backoff(attempts)
continue
return settags
raise SaltCloudSystemExit(
'Failed to set tags on {0}!'.format(name)
)
def get_tags(name=None,
instance_id=None,
call=None,
location=None,
kwargs=None,
resource_id=None): # pylint: disable=W0613
'''
Retrieve tags for a resource. Normally a VM name or instance_id is passed
in, but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a get_tags mymachine
salt-cloud -a get_tags resource_id=vol-3267ab32
'''
if location is None:
location = get_location()
if instance_id is None:
if resource_id is None:
if name:
instance_id = _get_node(name)['instanceId']
elif 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
elif 'resource_id' in kwargs:
instance_id = kwargs['resource_id']
else:
instance_id = resource_id
params = {'Action': 'DescribeTags',
'Filter.1.Name': 'resource-id',
'Filter.1.Value': instance_id}
return aws.query(params,
setname='tagSet',
location=location,
provider=get_provider(),
opts=__opts__,
sigver='4')
def del_tags(name=None,
kwargs=None,
call=None,
instance_id=None,
resource_id=None): # pylint: disable=W0613
'''
Delete tags for a resource. Normally a VM name or instance_id is passed in,
but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a del_tags mymachine tags=mytag,
salt-cloud -a del_tags mymachine tags=tag1,tag2,tag3
salt-cloud -a del_tags resource_id=vol-3267ab32 tags=tag1,tag2,tag3
'''
if kwargs is None:
kwargs = {}
if 'tags' not in kwargs:
raise SaltCloudSystemExit(
'A tag or tags must be specified using tags=list,of,tags'
)
if not name and 'resource_id' in kwargs:
instance_id = kwargs['resource_id']
del kwargs['resource_id']
if not instance_id:
instance_id = _get_node(name)['instanceId']
params = {'Action': 'DeleteTags',
'ResourceId.1': instance_id}
for idx, tag in enumerate(kwargs['tags'].split(',')):
params['Tag.{0}.Key'.format(idx)] = tag
aws.query(params,
setname='tagSet',
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if resource_id:
return get_tags(resource_id=resource_id)
else:
return get_tags(instance_id=instance_id)
def rename(name, kwargs, call=None):
'''
Properly rename a node. Pass in the new name as "new name".
CLI Example:
.. code-block:: bash
salt-cloud -a rename mymachine newname=yourmachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The rename action must be called with -a or --action.'
)
log.info('Renaming %s to %s', name, kwargs['newname'])
set_tags(name, {'Name': kwargs['newname']}, call='action')
salt.utils.cloud.rename_key(
__opts__['pki_dir'], name, kwargs['newname']
)
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
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.'
)
node_metadata = _get_node(name)
instance_id = node_metadata['instanceId']
sir_id = node_metadata.get('spotInstanceRequestId')
protected = show_term_protect(
name=name,
instance_id=instance_id,
call='action',
quiet=True
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if protected == 'true':
raise SaltCloudSystemExit(
'This instance has been protected from being destroyed. '
'Use the following command to disable protection:\n\n'
'salt-cloud -a disable_term_protect {0}'.format(
name
)
)
ret = {}
# Default behavior is to rename EC2 VMs when destroyed
# via salt-cloud, unless explicitly set to False.
rename_on_destroy = config.get_cloud_config_value('rename_on_destroy',
get_configured_provider(),
__opts__,
search_global=False)
if rename_on_destroy is not False:
newname = '{0}-DEL{1}'.format(name, uuid.uuid4().hex)
rename(name, kwargs={'newname': newname}, call='action')
log.info(
'Machine will be identified as %s until it has been '
'cleaned up.', newname
)
ret['newname'] = newname
params = {'Action': 'TerminateInstances',
'InstanceId.1': instance_id}
location = get_location()
provider = get_provider()
result = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
log.info(result)
ret.update(result[0])
# If this instance is part of a spot instance request, we
# need to cancel it as well
if sir_id is not None:
params = {'Action': 'CancelSpotInstanceRequests',
'SpotInstanceRequestId.1': sir_id}
result = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
ret['spotInstance'] = result[0]
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_del'](name)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return ret
def reboot(name, call=None):
'''
Reboot a node.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot mymachine
'''
instance_id = _get_node(name)['instanceId']
params = {'Action': 'RebootInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
setname='tagSet',
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if result == []:
log.info('Complete')
return {'Reboot': 'Complete'}
def show_image(kwargs, call=None):
'''
Show the details from EC2 concerning an AMI
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
params = {'ImageId.1': kwargs['image'],
'Action': 'DescribeImages'}
result = aws.query(params,
setname='tagSet',
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
log.info(result)
return result
def show_instance(name=None, instance_id=None, call=None, kwargs=None):
'''
Show the details from EC2 concerning an AMI.
Can be called as an action (which requires a name):
.. code-block:: bash
salt-cloud -a show_instance myinstance
...or as a function (which requires either a name or instance_id):
.. code-block:: bash
salt-cloud -f show_instance my-ec2 name=myinstance
salt-cloud -f show_instance my-ec2 instance_id=i-d34db33f
'''
if not name and call == 'action':
raise SaltCloudSystemExit(
'The show_instance action requires a name.'
)
if call == 'function':
name = kwargs.get('name', None)
instance_id = kwargs.get('instance_id', None)
if not name and not instance_id:
raise SaltCloudSystemExit(
'The show_instance function requires '
'either a name or an instance_id'
)
node = _get_node(name=name, instance_id=instance_id)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name=None, instance_id=None, location=None):
if location is None:
location = get_location()
params = {'Action': 'DescribeInstances'}
if six.text_type(name).startswith('i-') and (len(name) == 10 or len(name) == 19):
instance_id = name
if instance_id:
params['InstanceId.1'] = instance_id
else:
params['Filter.1.Name'] = 'tag:Name'
params['Filter.1.Value.1'] = name
log.trace(params)
provider = get_provider()
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
try:
instances = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
instance_info = _extract_instance_info(instances).values()
return next(iter(instance_info))
except IndexError:
attempts += 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', instance_id or name, attempts
)
aws.sleep_exponential_backoff(attempts)
return {}
def list_nodes_full(location=None, 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.'
)
return _list_nodes_full(location or get_location())
def _extract_name_tag(item):
if 'tagSet' in item and item['tagSet'] is not None:
tagset = item['tagSet']
if isinstance(tagset['item'], list):
for tag in tagset['item']:
if tag['key'] == 'Name':
return tag['value']
return item['instanceId']
return item['tagSet']['item']['value']
return item['instanceId']
def _extract_instance_info(instances):
'''
Given an instance query, return a dict of all instance data
'''
ret = {}
for instance in instances:
# items could be type dict or list (for stopped EC2 instances)
if isinstance(instance['instancesSet']['item'], list):
for item in instance['instancesSet']['item']:
name = _extract_name_tag(item)
ret[name] = item
ret[name]['name'] = name
ret[name].update(
dict(
id=item['instanceId'],
image=item['imageId'],
size=item['instanceType'],
state=item['instanceState']['name'],
private_ips=item.get('privateIpAddress', []),
public_ips=item.get('ipAddress', [])
)
)
else:
item = instance['instancesSet']['item']
name = _extract_name_tag(item)
ret[name] = item
ret[name]['name'] = name
ret[name].update(
dict(
id=item['instanceId'],
image=item['imageId'],
size=item['instanceType'],
state=item['instanceState']['name'],
private_ips=item.get('privateIpAddress', []),
public_ips=item.get('ipAddress', [])
)
)
return ret
def _list_nodes_full(location=None):
'''
Return a list of the VMs that in this location
'''
provider = __active_provider_name__ or 'ec2'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
params = {'Action': 'DescribeInstances'}
instances = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if 'error' in instances:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
instances['error']['Errors']['Error']['Message']
)
)
ret = _extract_instance_info(instances)
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_min(location=None, call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
params = {'Action': 'DescribeInstances'}
instances = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'error' in instances:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
instances['error']['Errors']['Error']['Message']
)
)
for instance in instances:
if isinstance(instance['instancesSet']['item'], list):
items = instance['instancesSet']['item']
else:
items = [instance['instancesSet']['item']]
for item in items:
state = item['instanceState']['name']
name = _extract_name_tag(item)
id = item['instanceId']
ret[name] = {'state': state, 'id': id}
return ret
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(get_location())
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]['id'],
'image': nodes[node]['image'],
'name': nodes[node]['name'],
'size': nodes[node]['size'],
'state': nodes[node]['state'],
'private_ips': nodes[node]['private_ips'],
'public_ips': nodes[node]['public_ips'],
}
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(get_location()), __opts__['query.selection'], call,
)
def show_term_protect(name=None, instance_id=None, call=None, quiet=False):
'''
Show the details from EC2 concerning an instance's termination protection state
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_term_protect action must be called with -a or --action.'
)
if not instance_id:
instance_id = _get_node(name)['instanceId']
params = {'Action': 'DescribeInstanceAttribute',
'InstanceId': instance_id,
'Attribute': 'disableApiTermination'}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
disable_protect = False
for item in result:
if 'value' in item:
disable_protect = item['value']
break
log.log(
logging.DEBUG if quiet is True else logging.INFO,
'Termination Protection is %s for %s',
disable_protect == 'true' and 'enabled' or 'disabled', name
)
return disable_protect
def show_detailed_monitoring(name=None, instance_id=None, call=None, quiet=False):
'''
Show the details from EC2 regarding cloudwatch detailed monitoring.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_detailed_monitoring action must be called with -a or --action.'
)
location = get_location()
if six.text_type(name).startswith('i-') and (len(name) == 10 or len(name) == 19):
instance_id = name
if not name and not instance_id:
raise SaltCloudSystemExit(
'The show_detailed_monitoring action must be provided with a name or instance\
ID'
)
matched = _get_node(name=name, instance_id=instance_id, location=location)
log.log(
logging.DEBUG if quiet is True else logging.INFO,
'Detailed Monitoring is %s for %s', matched['monitoring'], name
)
return matched['monitoring']
def _toggle_term_protect(name, value):
'''
Enable or Disable termination protection on a node
'''
instance_id = _get_node(name)['instanceId']
params = {'Action': 'ModifyInstanceAttribute',
'InstanceId': instance_id,
'DisableApiTermination.Value': value}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
return show_term_protect(name=name, instance_id=instance_id, call='action')
def enable_term_protect(name, call=None):
'''
Enable termination protection on a node
CLI Example:
.. code-block:: bash
salt-cloud -a enable_term_protect mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
return _toggle_term_protect(name, 'true')
def disable_term_protect(name, call=None):
'''
Disable termination protection on a node
CLI Example:
.. code-block:: bash
salt-cloud -a disable_term_protect mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
return _toggle_term_protect(name, 'false')
def disable_detailed_monitoring(name, call=None):
'''
Enable/disable detailed monitoring on a node
CLI Example:
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
instance_id = _get_node(name)['instanceId']
params = {'Action': 'UnmonitorInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
return show_detailed_monitoring(name=name, instance_id=instance_id, call='action')
def enable_detailed_monitoring(name, call=None):
'''
Enable/disable detailed monitoring on a node
CLI Example:
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
instance_id = _get_node(name)['instanceId']
params = {'Action': 'MonitorInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
return show_detailed_monitoring(name=name, instance_id=instance_id, call='action')
def show_delvol_on_destroy(name, kwargs=None, call=None):
'''
Do not delete all/specified EBS volumes upon instance termination
CLI Example:
.. code-block:: bash
salt-cloud -a show_delvol_on_destroy mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_delvol_on_destroy action must be called '
'with -a or --action.'
)
if not kwargs:
kwargs = {}
instance_id = kwargs.get('instance_id', None)
device = kwargs.get('device', None)
volume_id = kwargs.get('volume_id', None)
if instance_id is None:
instance_id = _get_node(name)['instanceId']
params = {'Action': 'DescribeInstances',
'InstanceId.1': instance_id}
data = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
blockmap = data[0]['instancesSet']['item']['blockDeviceMapping']
if not isinstance(blockmap['item'], list):
blockmap['item'] = [blockmap['item']]
items = []
for idx, item in enumerate(blockmap['item']):
device_name = item['deviceName']
if device is not None and device != device_name:
continue
if volume_id is not None and volume_id != item['ebs']['volumeId']:
continue
info = {
'device_name': device_name,
'volume_id': item['ebs']['volumeId'],
'deleteOnTermination': item['ebs']['deleteOnTermination']
}
items.append(info)
return items
def keepvol_on_destroy(name, kwargs=None, call=None):
'''
Do not delete all/specified EBS volumes upon instance termination
CLI Example:
.. code-block:: bash
salt-cloud -a keepvol_on_destroy mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The keepvol_on_destroy action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
device = kwargs.get('device', None)
volume_id = kwargs.get('volume_id', None)
return _toggle_delvol(name=name, device=device,
volume_id=volume_id, value='false')
def delvol_on_destroy(name, kwargs=None, call=None):
'''
Delete all/specified EBS volumes upon instance termination
CLI Example:
.. code-block:: bash
salt-cloud -a delvol_on_destroy mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The delvol_on_destroy action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
device = kwargs.get('device', None)
volume_id = kwargs.get('volume_id', None)
return _toggle_delvol(name=name, device=device,
volume_id=volume_id, value='true')
def _toggle_delvol(name=None, instance_id=None, device=None, volume_id=None,
value=None, requesturl=None):
if not instance_id:
instance_id = _get_node(name)['instanceId']
if requesturl:
data = aws.query(requesturl=requesturl,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
else:
params = {'Action': 'DescribeInstances',
'InstanceId.1': instance_id}
data, requesturl = aws.query(params, # pylint: disable=unbalanced-tuple-unpacking
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
blockmap = data[0]['instancesSet']['item']['blockDeviceMapping']
params = {'Action': 'ModifyInstanceAttribute',
'InstanceId': instance_id}
if not isinstance(blockmap['item'], list):
blockmap['item'] = [blockmap['item']]
for idx, item in enumerate(blockmap['item']):
device_name = item['deviceName']
if device is not None and device != device_name:
continue
if volume_id is not None and volume_id != item['ebs']['volumeId']:
continue
params['BlockDeviceMapping.{0}.DeviceName'.format(idx)] = device_name
params['BlockDeviceMapping.{0}.Ebs.DeleteOnTermination'.format(idx)] = value
aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
kwargs = {'instance_id': instance_id,
'device': device,
'volume_id': volume_id}
return show_delvol_on_destroy(name, kwargs, call='action')
def register_image(kwargs=None, call=None):
'''
Create an ami from a snapshot
CLI Example:
.. code-block:: bash
salt-cloud -f register_image my-ec2-config ami_name=my_ami description="my description"
root_device_name=/dev/xvda snapshot_id=snap-xxxxxxxx
'''
if call != 'function':
log.error(
'The create_volume function must be called with -f or --function.'
)
return False
if 'ami_name' not in kwargs:
log.error('ami_name must be specified to register an image.')
return False
block_device_mapping = kwargs.get('block_device_mapping', None)
if not block_device_mapping:
if 'snapshot_id' not in kwargs:
log.error('snapshot_id or block_device_mapping must be specified to register an image.')
return False
if 'root_device_name' not in kwargs:
log.error('root_device_name or block_device_mapping must be specified to register an image.')
return False
block_device_mapping = [{
'DeviceName': kwargs['root_device_name'],
'Ebs': {
'VolumeType': kwargs.get('volume_type', 'gp2'),
'SnapshotId': kwargs['snapshot_id'],
}
}]
if not isinstance(block_device_mapping, list):
block_device_mapping = [block_device_mapping]
params = {'Action': 'RegisterImage',
'Name': kwargs['ami_name']}
params.update(_param_from_config('BlockDeviceMapping', block_device_mapping))
if 'root_device_name' in kwargs:
params['RootDeviceName'] = kwargs['root_device_name']
if 'description' in kwargs:
params['Description'] = kwargs['description']
if 'virtualization_type' in kwargs:
params['VirtualizationType'] = kwargs['virtualization_type']
if 'architecture' in kwargs:
params['Architecture'] = kwargs['architecture']
log.debug(params)
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
r_data = {}
for d in data[0]:
for k, v in d.items():
r_data[k] = v
return r_data
def volume_create(**kwargs):
'''
Wrapper around create_volume.
Here just to ensure the compatibility with the cloud module.
'''
return create_volume(kwargs, 'function')
def create_volume(kwargs=None, call=None, wait_to_finish=False):
'''
Create a volume.
zone
The availability zone used to create the volume. Required. String.
size
The size of the volume, in GiBs. Defaults to ``10``. Integer.
snapshot
The snapshot-id from which to create the volume. Integer.
type
The volume type. This can be gp2 for General Purpose SSD, io1 for Provisioned
IOPS SSD, st1 for Throughput Optimized HDD, sc1 for Cold HDD, or standard for
Magnetic volumes. String.
iops
The number of I/O operations per second (IOPS) to provision for the volume,
with a maximum ratio of 50 IOPS/GiB. Only valid for Provisioned IOPS SSD
volumes. Integer.
This option will only be set if ``type`` is also specified as ``io1``.
encrypted
Specifies whether the volume will be encrypted. Boolean.
If ``snapshot`` is also given in the list of kwargs, then this value is ignored
since volumes that are created from encrypted snapshots are also automatically
encrypted.
tags
The tags to apply to the volume during creation. Dictionary.
call
The ``create_volume`` function must be called with ``-f`` or ``--function``.
String.
wait_to_finish
Whether or not to wait for the volume to be available. Boolean. Defaults to
``False``.
CLI Examples:
.. code-block:: bash
salt-cloud -f create_volume my-ec2-config zone=us-east-1b
salt-cloud -f create_volume my-ec2-config zone=us-east-1b tags='{"tag1": "val1", "tag2", "val2"}'
'''
if call != 'function':
log.error(
'The create_volume function must be called with -f or --function.'
)
return False
if 'zone' not in kwargs:
log.error('An availability zone must be specified to create a volume.')
return False
if 'size' not in kwargs and 'snapshot' not in kwargs:
# This number represents GiB
kwargs['size'] = '10'
params = {'Action': 'CreateVolume',
'AvailabilityZone': kwargs['zone']}
if 'size' in kwargs:
params['Size'] = kwargs['size']
if 'snapshot' in kwargs:
params['SnapshotId'] = kwargs['snapshot']
if 'type' in kwargs:
params['VolumeType'] = kwargs['type']
if 'iops' in kwargs and kwargs.get('type', 'standard') == 'io1':
params['Iops'] = kwargs['iops']
# You can't set `encrypted` if you pass a snapshot
if 'encrypted' in kwargs and 'snapshot' not in kwargs:
params['Encrypted'] = kwargs['encrypted']
if 'kmskeyid' in kwargs:
params['KmsKeyId'] = kwargs['kmskeyid']
if 'kmskeyid' in kwargs and 'encrypted' not in kwargs:
log.error(
'If a KMS Key ID is specified, encryption must be enabled'
)
return False
log.debug(params)
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
r_data = {}
for d in data[0]:
for k, v in six.iteritems(d):
r_data[k] = v
volume_id = r_data['volumeId']
# Allow tags to be set upon creation
if 'tags' in kwargs:
if isinstance(kwargs['tags'], six.string_types):
tags = salt.utils.yaml.safe_load(kwargs['tags'])
else:
tags = kwargs['tags']
if isinstance(tags, dict):
new_tags = set_tags(tags=tags,
resource_id=volume_id,
call='action',
location=get_location())
r_data['tags'] = new_tags
# Waits till volume is available
if wait_to_finish:
salt.utils.cloud.run_func_until_ret_arg(fun=describe_volumes,
kwargs={'volume_id': volume_id},
fun_call=call,
argument_being_watched='status',
required_argument_response='available')
return r_data
def __attach_vol_to_instance(params, kws, instance_id):
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if data[0]:
log.warning(
'Error attaching volume %s to instance %s. Retrying!',
kws['volume_id'], instance_id
)
return False
return data
def attach_volume(name=None, kwargs=None, instance_id=None, call=None):
'''
Attach a volume to an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The attach_volume action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
if name and not instance_id:
instance_id = _get_node(name)['instanceId']
if not name and not instance_id:
log.error('Either a name or an instance_id is required.')
return False
if 'volume_id' not in kwargs:
log.error('A volume_id is required.')
return False
if 'device' not in kwargs:
log.error('A device is required (ex. /dev/sdb1).')
return False
params = {'Action': 'AttachVolume',
'VolumeId': kwargs['volume_id'],
'InstanceId': instance_id,
'Device': kwargs['device']}
log.debug(params)
vm_ = get_configured_provider()
data = salt.utils.cloud.wait_for_ip(
__attach_vol_to_instance,
update_args=(params, kwargs, instance_id),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value(
'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
return data
def show_volume(kwargs=None, call=None):
'''
Wrapper around describe_volumes.
Here just to keep functionality.
Might be depreciated later.
'''
if not kwargs:
kwargs = {}
return describe_volumes(kwargs, call)
def detach_volume(name=None, kwargs=None, instance_id=None, call=None):
'''
Detach a volume from an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The detach_volume action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
if 'volume_id' not in kwargs:
log.error('A volume_id is required.')
return False
params = {'Action': 'DetachVolume',
'VolumeId': kwargs['volume_id']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def delete_volume(name=None, kwargs=None, instance_id=None, call=None):
'''
Delete a volume
'''
if not kwargs:
kwargs = {}
if 'volume_id' not in kwargs:
log.error('A volume_id is required.')
return False
params = {'Action': 'DeleteVolume',
'VolumeId': kwargs['volume_id']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def volume_list(**kwargs):
'''
Wrapper around describe_volumes.
Here just to ensure the compatibility with the cloud module.
'''
return describe_volumes(kwargs, 'function')
def describe_volumes(kwargs=None, call=None):
'''
Describe a volume (or volumes)
volume_id
One or more volume IDs. Multiple IDs must be separated by ",".
TODO: Add all of the filters.
'''
if call != 'function':
log.error(
'The describe_volumes function must be called with -f '
'or --function.'
)
return False
if not kwargs:
kwargs = {}
params = {'Action': 'DescribeVolumes'}
if 'volume_id' in kwargs:
volume_id = kwargs['volume_id'].split(',')
for volume_index, volume_id in enumerate(volume_id):
params['VolumeId.{0}'.format(volume_index)] = volume_id
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def create_keypair(kwargs=None, call=None):
'''
Create an SSH keypair
'''
if call != 'function':
log.error(
'The create_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
params = {'Action': 'CreateKeyPair',
'KeyName': kwargs['keyname']}
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
keys = [x for x in data[0] if 'requestId' not in x]
return (keys, data[1])
def import_keypair(kwargs=None, call=None):
'''
Import an SSH public key.
.. versionadded:: 2015.8.3
'''
if call != 'function':
log.error(
'The import_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
if 'file' not in kwargs:
log.error('A public key file is required.')
return False
params = {'Action': 'ImportKeyPair',
'KeyName': kwargs['keyname']}
public_key_file = kwargs['file']
if os.path.exists(public_key_file):
with salt.utils.files.fopen(public_key_file, 'r') as fh_:
public_key = salt.utils.stringutils.to_unicode(fh_.read())
if public_key is not None:
params['PublicKeyMaterial'] = base64.b64encode(public_key)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
params = {'Action': 'DescribeKeyPairs',
'KeyName.1': kwargs['keyname']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def delete_keypair(kwargs=None, call=None):
'''
Delete an SSH keypair
'''
if call != 'function':
log.error(
'The delete_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
params = {'Action': 'DeleteKeyPair',
'KeyName': kwargs['keyname']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def create_snapshot(kwargs=None, call=None, wait_to_finish=False):
'''
Create a snapshot.
volume_id
The ID of the Volume from which to create a snapshot.
description
The optional description of the snapshot.
CLI Exampe:
.. code-block:: bash
salt-cloud -f create_snapshot my-ec2-config volume_id=vol-351d8826
salt-cloud -f create_snapshot my-ec2-config volume_id=vol-351d8826 \\
description="My Snapshot Description"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_snapshot function must be called with -f '
'or --function.'
)
if kwargs is None:
kwargs = {}
volume_id = kwargs.get('volume_id', None)
description = kwargs.get('description', '')
if volume_id is None:
raise SaltCloudSystemExit(
'A volume_id must be specified to create a snapshot.'
)
params = {'Action': 'CreateSnapshot',
'VolumeId': volume_id,
'Description': description}
log.debug(params)
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')[0]
r_data = {}
for d in data:
for k, v in six.iteritems(d):
r_data[k] = v
if 'snapshotId' in r_data:
snapshot_id = r_data['snapshotId']
# Waits till volume is available
if wait_to_finish:
salt.utils.cloud.run_func_until_ret_arg(fun=describe_snapshots,
kwargs={'snapshot_id': snapshot_id},
fun_call=call,
argument_being_watched='status',
required_argument_response='completed')
return r_data
def delete_snapshot(kwargs=None, call=None):
'''
Delete a snapshot
'''
if call != 'function':
log.error(
'The delete_snapshot function must be called with -f '
'or --function.'
)
return False
if 'snapshot_id' not in kwargs:
log.error('A snapshot_id must be specified to delete a snapshot.')
return False
params = {'Action': 'DeleteSnapshot'}
if 'snapshot_id' in kwargs:
params['SnapshotId'] = kwargs['snapshot_id']
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def copy_snapshot(kwargs=None, call=None):
'''
Copy a snapshot
'''
if call != 'function':
log.error(
'The copy_snapshot function must be called with -f or --function.'
)
return False
if 'source_region' not in kwargs:
log.error('A source_region must be specified to copy a snapshot.')
return False
if 'source_snapshot_id' not in kwargs:
log.error('A source_snapshot_id must be specified to copy a snapshot.')
return False
if 'description' not in kwargs:
kwargs['description'] = ''
params = {'Action': 'CopySnapshot'}
if 'source_region' in kwargs:
params['SourceRegion'] = kwargs['source_region']
if 'source_snapshot_id' in kwargs:
params['SourceSnapshotId'] = kwargs['source_snapshot_id']
if 'description' in kwargs:
params['Description'] = kwargs['description']
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def describe_snapshots(kwargs=None, call=None):
'''
Describe a snapshot (or snapshots)
snapshot_id
One or more snapshot IDs. Multiple IDs must be separated by ",".
owner
Return the snapshots owned by the specified owner. Valid values
include: self, amazon, <AWS Account ID>. Multiple values must be
separated by ",".
restorable_by
One or more AWS accounts IDs that can create volumes from the snapshot.
Multiple aws account IDs must be separated by ",".
TODO: Add all of the filters.
'''
if call != 'function':
log.error(
'The describe_snapshot function must be called with -f '
'or --function.'
)
return False
params = {'Action': 'DescribeSnapshots'}
# The AWS correct way is to use non-plurals like snapshot_id INSTEAD of snapshot_ids.
if 'snapshot_ids' in kwargs:
kwargs['snapshot_id'] = kwargs['snapshot_ids']
if 'snapshot_id' in kwargs:
snapshot_ids = kwargs['snapshot_id'].split(',')
for snapshot_index, snapshot_id in enumerate(snapshot_ids):
params['SnapshotId.{0}'.format(snapshot_index)] = snapshot_id
if 'owner' in kwargs:
owners = kwargs['owner'].split(',')
for owner_index, owner in enumerate(owners):
params['Owner.{0}'.format(owner_index)] = owner
if 'restorable_by' in kwargs:
restorable_bys = kwargs['restorable_by'].split(',')
for restorable_by_index, restorable_by in enumerate(restorable_bys):
params[
'RestorableBy.{0}'.format(restorable_by_index)
] = restorable_by
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def get_console_output(
name=None,
location=None,
instance_id=None,
call=None,
kwargs=None,
):
'''
Show the console output from the instance.
By default, returns decoded data, not the Base64-encoded data that is
actually returned from the EC2 API.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The get_console_output action must be called with '
'-a or --action.'
)
if location is None:
location = get_location()
if not instance_id:
instance_id = _get_node(name)['instanceId']
if kwargs is None:
kwargs = {}
if instance_id is None:
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
del kwargs['instance_id']
params = {'Action': 'GetConsoleOutput',
'InstanceId': instance_id}
ret = {}
data = aws.query(params,
return_root=True,
location=location,
provider=get_provider(),
opts=__opts__,
sigver='4')
for item in data:
if next(six.iterkeys(item)) == 'output':
ret['output_decoded'] = binascii.a2b_base64(next(six.itervalues(item)))
else:
ret[next(six.iterkeys(item))] = next(six.itervalues(item))
return ret
def get_password_data(
name=None,
kwargs=None,
instance_id=None,
call=None,
):
'''
Return password data for a Windows instance.
By default only the encrypted password data will be returned. However, if a
key_file is passed in, then a decrypted password will also be returned.
Note that the key_file references the private key that was used to generate
the keypair associated with this instance. This private key will _not_ be
transmitted to Amazon; it is only used internally inside of Salt Cloud to
decrypt data _after_ it has been received from Amazon.
CLI Examples:
.. code-block:: bash
salt-cloud -a get_password_data mymachine
salt-cloud -a get_password_data mymachine key_file=/root/ec2key.pem
Note: PKCS1_v1_5 was added in PyCrypto 2.5
'''
if call != 'action':
raise SaltCloudSystemExit(
'The get_password_data action must be called with '
'-a or --action.'
)
if not instance_id:
instance_id = _get_node(name)['instanceId']
if kwargs is None:
kwargs = {}
if instance_id is None:
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
del kwargs['instance_id']
params = {'Action': 'GetPasswordData',
'InstanceId': instance_id}
ret = {}
data = aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
for item in data:
ret[next(six.iterkeys(item))] = next(six.itervalues(item))
if not HAS_M2 and not HAS_PYCRYPTO:
return ret
if 'key' not in kwargs:
if 'key_file' in kwargs:
with salt.utils.files.fopen(kwargs['key_file'], 'r') as kf_:
kwargs['key'] = salt.utils.stringutils.to_unicode(kf_.read())
if 'key' in kwargs:
pwdata = ret.get('passwordData', None)
if pwdata is not None:
rsa_key = kwargs['key']
pwdata = base64.b64decode(pwdata)
if HAS_M2:
key = RSA.load_key_string(rsa_key.encode('ascii'))
password = key.private_decrypt(pwdata, RSA.pkcs1_padding)
else:
dsize = Crypto.Hash.SHA.digest_size
sentinel = Crypto.Random.new().read(15 + dsize)
key_obj = Crypto.PublicKey.RSA.importKey(rsa_key)
key_obj = PKCS1_v1_5.new(key_obj)
password = key_obj.decrypt(pwdata, sentinel)
ret['password'] = salt.utils.stringutils.to_unicode(password)
return ret
def update_pricing(kwargs=None, call=None):
'''
Download most recent pricing information from AWS and convert to a local
JSON file.
CLI Examples:
.. code-block:: bash
salt-cloud -f update_pricing my-ec2-config
salt-cloud -f update_pricing my-ec2-config type=linux
.. versionadded:: 2015.8.0
'''
sources = {
'linux': 'https://a0.awsstatic.com/pricing/1/ec2/linux-od.min.js',
'rhel': 'https://a0.awsstatic.com/pricing/1/ec2/rhel-od.min.js',
'sles': 'https://a0.awsstatic.com/pricing/1/ec2/sles-od.min.js',
'mswin': 'https://a0.awsstatic.com/pricing/1/ec2/mswin-od.min.js',
'mswinsql': 'https://a0.awsstatic.com/pricing/1/ec2/mswinSQL-od.min.js',
'mswinsqlweb': 'https://a0.awsstatic.com/pricing/1/ec2/mswinSQLWeb-od.min.js',
}
if kwargs is None:
kwargs = {}
if 'type' not in kwargs:
for source in sources:
_parse_pricing(sources[source], source)
else:
_parse_pricing(sources[kwargs['type']], kwargs['type'])
def _parse_pricing(url, name):
'''
Download and parse an individual pricing file from AWS
.. versionadded:: 2015.8.0
'''
price_js = http.query(url, text=True)
items = []
current_item = ''
price_js = re.sub(JS_COMMENT_RE, '', price_js['text'])
price_js = price_js.strip().rstrip(');').lstrip('callback(')
for keyword in (
'vers',
'config',
'rate',
'valueColumns',
'currencies',
'instanceTypes',
'type',
'ECU',
'storageGB',
'name',
'vCPU',
'memoryGiB',
'storageGiB',
'USD',
):
price_js = price_js.replace(keyword, '"{0}"'.format(keyword))
for keyword in ('region', 'price', 'size'):
price_js = price_js.replace(keyword, '"{0}"'.format(keyword))
price_js = price_js.replace('"{0}"s'.format(keyword), '"{0}s"'.format(keyword))
price_js = price_js.replace('""', '"')
# Turn the data into something that's easier/faster to process
regions = {}
price_json = salt.utils.json.loads(price_js)
for region in price_json['config']['regions']:
sizes = {}
for itype in region['instanceTypes']:
for size in itype['sizes']:
sizes[size['size']] = size
regions[region['region']] = sizes
outfile = os.path.join(
__opts__['cachedir'], 'ec2-pricing-{0}.p'.format(name)
)
with salt.utils.files.fopen(outfile, 'w') as fho:
salt.utils.msgpack.dump(regions, fho)
return True
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-ec2-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: 2015.8.0
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to ec2
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'ec2':
return {'Error': 'The requested profile does not belong to EC2'}
image_id = profile.get('image', None)
image_dict = show_image({'image': image_id}, 'function')
image_info = image_dict[0]
# Find out what platform it is
if image_info.get('imageOwnerAlias', '') == 'amazon':
if image_info.get('platform', '') == 'windows':
image_description = image_info.get('description', '')
if 'sql' in image_description.lower():
if 'web' in image_description.lower():
name = 'mswinsqlweb'
else:
name = 'mswinsql'
else:
name = 'mswin'
elif image_info.get('imageLocation', '').strip().startswith('amazon/suse'):
name = 'sles'
else:
name = 'linux'
elif image_info.get('imageOwnerId', '') == '309956199498':
name = 'rhel'
else:
name = 'linux'
pricefile = os.path.join(
__opts__['cachedir'], 'ec2-pricing-{0}.p'.format(name)
)
if not os.path.isfile(pricefile):
update_pricing({'type': name}, 'function')
with salt.utils.files.fopen(pricefile, 'r') as fhi:
ec2_price = salt.utils.stringutils.to_unicode(
salt.utils.msgpack.load(fhi))
region = get_location(profile)
size = profile.get('size', None)
if size is None:
return {'Error': 'The requested profile does not contain a size'}
try:
raw = ec2_price[region][size]
except KeyError:
return {'Error': 'The size ({0}) in the requested profile does not have '
'a price associated with it for the {1} region'.format(size, region)}
ret = {}
if kwargs.get('raw', False):
ret['_raw'] = raw
ret['per_hour'] = 0
for col in raw.get('valueColumns', []):
ret['per_hour'] += decimal.Decimal(col['prices'].get('USD', 0))
ret['per_hour'] = decimal.Decimal(ret['per_hour'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = ret['per_day'] * 30
ret['per_year'] = ret['per_week'] * 52
return {profile['profile']: ret}
def ssm_create_association(name=None, kwargs=None, instance_id=None, call=None):
'''
Associates the specified SSM document with the specified instance
http://docs.aws.amazon.com/ssm/latest/APIReference/API_CreateAssociation.html
CLI Examples:
.. code-block:: bash
salt-cloud -a ssm_create_association ec2-instance-name ssm_document=ssm-document-name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The ssm_create_association action must be called with '
'-a or --action.'
)
if not kwargs:
kwargs = {}
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
if name and not instance_id:
instance_id = _get_node(name)['instanceId']
if not name and not instance_id:
log.error('Either a name or an instance_id is required.')
return False
if 'ssm_document' not in kwargs:
log.error('A ssm_document is required.')
return False
params = {'Action': 'CreateAssociation',
'InstanceId': instance_id,
'Name': kwargs['ssm_document']}
result = aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
product='ssm',
opts=__opts__,
sigver='4')
log.info(result)
return result
def ssm_describe_association(name=None, kwargs=None, instance_id=None, call=None):
'''
Describes the associations for the specified SSM document or instance.
http://docs.aws.amazon.com/ssm/latest/APIReference/API_DescribeAssociation.html
CLI Examples:
.. code-block:: bash
salt-cloud -a ssm_describe_association ec2-instance-name ssm_document=ssm-document-name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The ssm_describe_association action must be called with '
'-a or --action.'
)
if not kwargs:
kwargs = {}
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
if name and not instance_id:
instance_id = _get_node(name)['instanceId']
if not name and not instance_id:
log.error('Either a name or an instance_id is required.')
return False
if 'ssm_document' not in kwargs:
log.error('A ssm_document is required.')
return False
params = {'Action': 'DescribeAssociation',
'InstanceId': instance_id,
'Name': kwargs['ssm_document']}
result = aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
product='ssm',
opts=__opts__,
sigver='4')
log.info(result)
return result
|
saltstack/salt | salt/cloud/clouds/ec2.py | _wait_for_spot_instance | python | def _wait_for_spot_instance(update_callback,
update_args=None,
update_kwargs=None,
timeout=10 * 60,
interval=30,
interval_multiplier=1,
max_failures=10):
'''
Helper function that waits for a spot instance request to become active
for a specific maximum amount of time.
:param update_callback: callback function which queries the cloud provider
for spot instance request. It must return None if
the required data, running instance included, is
not available yet.
:param update_args: Arguments to pass to update_callback
:param update_kwargs: Keyword arguments to pass to update_callback
:param timeout: The maximum amount of time(in seconds) to wait for the IP
address.
:param interval: The looping interval, i.e., the amount of time to sleep
before the next iteration.
:param interval_multiplier: Increase the interval by this multiplier after
each request; helps with throttling
:param max_failures: If update_callback returns ``False`` it's considered
query failure. This value is the amount of failures
accepted before giving up.
:returns: The update_callback returned data
:raises: SaltCloudExecutionTimeout
'''
if update_args is None:
update_args = ()
if update_kwargs is None:
update_kwargs = {}
duration = timeout
while True:
log.debug(
'Waiting for spot instance reservation. Giving up in '
'00:%02d:%02d', int(timeout // 60), int(timeout % 60)
)
data = update_callback(*update_args, **update_kwargs)
if data is False:
log.debug(
'update_callback has returned False which is considered a '
'failure. Remaining Failures: %s', max_failures
)
max_failures -= 1
if max_failures <= 0:
raise SaltCloudExecutionFailure(
'Too many failures occurred while waiting for '
'the spot instance reservation to become active.'
)
elif data is not None:
return data
if timeout < 0:
raise SaltCloudExecutionTimeout(
'Unable to get an active spot instance request for '
'00:{0:02d}:{1:02d}'.format(
int(duration // 60),
int(duration % 60)
)
)
time.sleep(interval)
timeout -= interval
if interval_multiplier > 1:
interval *= interval_multiplier
if interval > timeout:
interval = timeout + 1
log.info('Interval multiplier in effect; interval is '
'now %ss', interval) | Helper function that waits for a spot instance request to become active
for a specific maximum amount of time.
:param update_callback: callback function which queries the cloud provider
for spot instance request. It must return None if
the required data, running instance included, is
not available yet.
:param update_args: Arguments to pass to update_callback
:param update_kwargs: Keyword arguments to pass to update_callback
:param timeout: The maximum amount of time(in seconds) to wait for the IP
address.
:param interval: The looping interval, i.e., the amount of time to sleep
before the next iteration.
:param interval_multiplier: Increase the interval by this multiplier after
each request; helps with throttling
:param max_failures: If update_callback returns ``False`` it's considered
query failure. This value is the amount of failures
accepted before giving up.
:returns: The update_callback returned data
:raises: SaltCloudExecutionTimeout | train | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/ec2.py#L476-L548 | null | # -*- coding: utf-8 -*-
'''
The EC2 Cloud Module
====================
The EC2 cloud module is used to interact with the Amazon Elastic Compute Cloud.
To use the EC2 cloud module, set up the cloud configuration at
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/ec2.conf``:
.. code-block:: yaml
my-ec2-config:
# EC2 API credentials: Access Key ID and Secret Access Key.
# Alternatively, to use IAM Instance Role credentials available via
# EC2 metadata set both id and key to 'use-instance-role-credentials'
id: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# If 'role_arn' is specified the above credentials are used to
# to assume to the role. By default, role_arn is set to None.
role_arn: arn:aws:iam::012345678910:role/SomeRoleName
# The ssh keyname to use
keyname: default
# The amazon security group
securitygroup: ssh_open
# The location of the private key which corresponds to the keyname
private_key: /root/default.pem
# Be default, service_url is set to amazonaws.com. If you are using this
# driver for something other than Amazon EC2, change it here:
service_url: amazonaws.com
# The endpoint that is ultimately used is usually formed using the region
# and the service_url. If you would like to override that entirely, you
# can explicitly define the endpoint:
endpoint: myendpoint.example.com:1138/services/Cloud
# SSH Gateways can be used with this provider. Gateways can be used
# when a salt-master is not on the same private network as the instance
# that is being deployed.
# Defaults to None
# Required
ssh_gateway: gateway.example.com
# Defaults to port 22
# Optional
ssh_gateway_port: 22
# Defaults to root
# Optional
ssh_gateway_username: root
# Default to nc -q0 %h %p
# Optional
ssh_gateway_command: "-W %h:%p"
# One authentication method is required. If both
# are specified, Private key wins.
# Private key defaults to None
ssh_gateway_private_key: /path/to/key.pem
# Password defaults to None
ssh_gateway_password: ExamplePasswordHere
driver: ec2
# Pass userdata to the instance to be created
userdata_file: /etc/salt/my-userdata-file
# Instance termination protection setting
# Default is disabled
termination_protection: False
:depends: requests
'''
# pylint: disable=invalid-name,function-redefined
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import stat
import time
import uuid
import pprint
import logging
# Import libs for talking to the EC2 API
import hmac
import hashlib
import binascii
import datetime
import base64
import re
import decimal
# Import Salt Libs
import salt.utils.cloud
import salt.utils.compat
import salt.utils.files
import salt.utils.hashutils
import salt.utils.json
import salt.utils.msgpack
import salt.utils.stringutils
import salt.utils.yaml
from salt._compat import ElementTree as ET
import salt.utils.http as http
import salt.utils.aws as aws
import salt.config as config
from salt.exceptions import (
SaltCloudException,
SaltCloudSystemExit,
SaltCloudConfigError,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure
)
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, zip
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse, urlencode as _urlencode
# Import 3rd-Party Libs
# Try to import PyCrypto, which may not be installed on a RAET-based system
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
import Crypto
# PKCS1_v1_5 was added in PyCrypto 2.5
from Crypto.Cipher import PKCS1_v1_5 # pylint: disable=E0611
from Crypto.Hash import SHA # pylint: disable=E0611,W0611
HAS_PYCRYPTO = True
except ImportError:
HAS_PYCRYPTO = False
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# pylint: enable=import-error,no-name-in-module,redefined-builtin
# Get logging started
log = logging.getLogger(__name__)
EC2_LOCATIONS = {
'ap-northeast-1': 'ec2_ap_northeast',
'ap-northeast-2': 'ec2_ap_northeast_2',
'ap-southeast-1': 'ec2_ap_southeast',
'ap-southeast-2': 'ec2_ap_southeast_2',
'eu-west-1': 'ec2_eu_west',
'eu-central-1': 'ec2_eu_central',
'sa-east-1': 'ec2_sa_east',
'us-east-1': 'ec2_us_east',
'us-gov-west-1': 'ec2_us_gov_west_1',
'us-west-1': 'ec2_us_west',
'us-west-2': 'ec2_us_west_oregon',
}
DEFAULT_LOCATION = 'us-east-1'
DEFAULT_EC2_API_VERSION = '2014-10-01'
EC2_RETRY_CODES = [
'RequestLimitExceeded',
'InsufficientInstanceCapacity',
'InternalError',
'Unavailable',
'InsufficientAddressCapacity',
'InsufficientReservedInstanceCapacity',
]
JS_COMMENT_RE = re.compile(r'/\*.*?\*/', re.S)
__virtualname__ = 'ec2'
# Only load in this module if the EC2 configurations are in place
def __virtual__():
'''
Set up the libcloud functions and check for EC2 configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('id', 'key')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'requests': HAS_REQUESTS,
'pycrypto or m2crypto': HAS_M2 or HAS_PYCRYPTO
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def _xml_to_dict(xmltree):
'''
Convert an XML tree into a dict
'''
if sys.version_info < (2, 7):
children_len = len(xmltree.getchildren())
else:
children_len = len(xmltree)
if children_len < 1:
name = xmltree.tag
if '}' in name:
comps = name.split('}')
name = comps[1]
return {name: xmltree.text}
xmldict = {}
for item in xmltree:
name = item.tag
if '}' in name:
comps = name.split('}')
name = comps[1]
if name not in xmldict:
if sys.version_info < (2, 7):
children_len = len(item.getchildren())
else:
children_len = len(item)
if children_len > 0:
xmldict[name] = _xml_to_dict(item)
else:
xmldict[name] = item.text
else:
if not isinstance(xmldict[name], list):
tempvar = xmldict[name]
xmldict[name] = []
xmldict[name].append(tempvar)
xmldict[name].append(_xml_to_dict(item))
return xmldict
def optimize_providers(providers):
'''
Return an optimized list of providers.
We want to reduce the duplication of querying
the same region.
If a provider is using the same credentials for the same region
the same data will be returned for each provider, thus causing
un-wanted duplicate data and API calls to EC2.
'''
tmp_providers = {}
optimized_providers = {}
for name, data in six.iteritems(providers):
if 'location' not in data:
data['location'] = DEFAULT_LOCATION
if data['location'] not in tmp_providers:
tmp_providers[data['location']] = {}
creds = (data['id'], data['key'])
if creds not in tmp_providers[data['location']]:
tmp_providers[data['location']][creds] = {'name': name,
'data': data,
}
for location, tmp_data in six.iteritems(tmp_providers):
for creds, data in six.iteritems(tmp_data):
_id, _key = creds
_name = data['name']
_data = data['data']
if _name not in optimized_providers:
optimized_providers[_name] = _data
return optimized_providers
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
def query(params=None, setname=None, requesturl=None, location=None,
return_url=False, return_root=False):
provider = get_configured_provider()
service_url = provider.get('service_url', 'amazonaws.com')
# Retrieve access credentials from meta-data, or use provided
access_key_id, secret_access_key, token = aws.creds(provider)
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
params_with_headers = params.copy()
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
if not location:
location = get_location()
if not requesturl:
endpoint = provider.get(
'endpoint',
'ec2.{0}.{1}'.format(location, service_url)
)
requesturl = 'https://{0}/'.format(endpoint)
endpoint = _urlparse(requesturl).netloc
endpoint_path = _urlparse(requesturl).path
else:
endpoint = _urlparse(requesturl).netloc
endpoint_path = _urlparse(requesturl).path
if endpoint == '':
endpoint_err = (
'Could not find a valid endpoint in the '
'requesturl: {0}. Looking for something '
'like https://some.ec2.endpoint/?args').format(requesturl)
log.error(endpoint_err)
if return_url is True:
return {'error': endpoint_err}, requesturl
return {'error': endpoint_err}
log.debug('Using EC2 endpoint: %s', endpoint)
# AWS v4 signature
method = 'GET'
region = location
service = 'ec2'
canonical_uri = _urlparse(requesturl).path
host = endpoint.strip()
# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ') # Format date as YYYYMMDD'T'HHMMSS'Z'
datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'
signed_headers = 'host;x-amz-date'
payload_hash = salt.utils.hashutils.sha256_digest('')
ec2_api_version = provider.get(
'ec2_api_version',
DEFAULT_EC2_API_VERSION
)
params_with_headers['Version'] = ec2_api_version
keys = sorted(list(params_with_headers))
values = map(params_with_headers.get, keys)
querystring = _urlencode(list(zip(keys, values)))
querystring = querystring.replace('+', '%20')
canonical_request = method + '\n' + canonical_uri + '\n' + \
querystring + '\n' + canonical_headers + '\n' + \
signed_headers + '\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amz_date + '\n' + \
credential_scope + '\n' + \
salt.utils.hashutils.sha256_digest(canonical_request)
kDate = sign(('AWS4' + provider['key']).encode('utf-8'), datestamp)
kRegion = sign(kDate, region)
kService = sign(kRegion, service)
signing_key = sign(kService, 'aws4_request')
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'),
hashlib.sha256).hexdigest()
authorization_header = algorithm + ' ' + 'Credential=' + \
provider['id'] + '/' + credential_scope + \
', ' + 'SignedHeaders=' + signed_headers + \
', ' + 'Signature=' + signature
headers = {'x-amz-date': amz_date, 'Authorization': authorization_header}
log.debug('EC2 Request: %s', requesturl)
log.trace('EC2 Request Parameters: %s', params_with_headers)
try:
result = requests.get(requesturl, headers=headers, params=params_with_headers)
log.debug(
'EC2 Response Status Code: %s',
# result.getcode()
result.status_code
)
log.trace('EC2 Response Text: %s', result.text)
result.raise_for_status()
break
except requests.exceptions.HTTPError as exc:
root = ET.fromstring(exc.response.content)
data = _xml_to_dict(root)
# check to see if we should retry the query
err_code = data.get('Errors', {}).get('Error', {}).get('Code', '')
if err_code and err_code in EC2_RETRY_CODES:
attempts += 1
log.error(
'EC2 Response Status Code and Error: [%s %s] %s; '
'Attempts remaining: %s',
exc.response.status_code, exc, data, attempts
)
aws.sleep_exponential_backoff(attempts)
continue
log.error(
'EC2 Response Status Code and Error: [%s %s] %s',
exc.response.status_code, exc, data
)
if return_url is True:
return {'error': data}, requesturl
return {'error': data}
else:
log.error(
'EC2 Response Status Code and Error: [%s %s] %s',
exc.response.status_code, exc, data
)
if return_url is True:
return {'error': data}, requesturl
return {'error': data}
response = result.text
root = ET.fromstring(response)
items = root[1]
if return_root is True:
items = root
if setname:
if sys.version_info < (2, 7):
children_len = len(root.getchildren())
else:
children_len = len(root)
for item in range(0, children_len):
comps = root[item].tag.split('}')
if comps[1] == setname:
items = root[item]
ret = []
for item in items:
ret.append(_xml_to_dict(item))
if return_url is True:
return ret, requesturl
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. Latest version can be found at:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
sizes = {
'Cluster Compute': {
'cc2.8xlarge': {
'id': 'cc2.8xlarge',
'cores': '16 (2 x Intel Xeon E5-2670, eight-core with '
'hyperthread)',
'disk': '3360 GiB (4 x 840 GiB)',
'ram': '60.5 GiB'
},
'cc1.4xlarge': {
'id': 'cc1.4xlarge',
'cores': '8 (2 x Intel Xeon X5570, quad-core with '
'hyperthread)',
'disk': '1690 GiB (2 x 840 GiB)',
'ram': '22.5 GiB'
},
},
'Cluster CPU': {
'cg1.4xlarge': {
'id': 'cg1.4xlarge',
'cores': '8 (2 x Intel Xeon X5570, quad-core with '
'hyperthread), plus 2 NVIDIA Tesla M2050 GPUs',
'disk': '1680 GiB (2 x 840 GiB)',
'ram': '22.5 GiB'
},
},
'Compute Optimized': {
'c4.large': {
'id': 'c4.large',
'cores': '2',
'disk': 'EBS - 500 Mbps',
'ram': '3.75 GiB'
},
'c4.xlarge': {
'id': 'c4.xlarge',
'cores': '4',
'disk': 'EBS - 750 Mbps',
'ram': '7.5 GiB'
},
'c4.2xlarge': {
'id': 'c4.2xlarge',
'cores': '8',
'disk': 'EBS - 1000 Mbps',
'ram': '15 GiB'
},
'c4.4xlarge': {
'id': 'c4.4xlarge',
'cores': '16',
'disk': 'EBS - 2000 Mbps',
'ram': '30 GiB'
},
'c4.8xlarge': {
'id': 'c4.8xlarge',
'cores': '36',
'disk': 'EBS - 4000 Mbps',
'ram': '60 GiB'
},
'c3.large': {
'id': 'c3.large',
'cores': '2',
'disk': '32 GiB (2 x 16 GiB SSD)',
'ram': '3.75 GiB'
},
'c3.xlarge': {
'id': 'c3.xlarge',
'cores': '4',
'disk': '80 GiB (2 x 40 GiB SSD)',
'ram': '7.5 GiB'
},
'c3.2xlarge': {
'id': 'c3.2xlarge',
'cores': '8',
'disk': '160 GiB (2 x 80 GiB SSD)',
'ram': '15 GiB'
},
'c3.4xlarge': {
'id': 'c3.4xlarge',
'cores': '16',
'disk': '320 GiB (2 x 160 GiB SSD)',
'ram': '30 GiB'
},
'c3.8xlarge': {
'id': 'c3.8xlarge',
'cores': '32',
'disk': '640 GiB (2 x 320 GiB SSD)',
'ram': '60 GiB'
}
},
'Dense Storage': {
'd2.xlarge': {
'id': 'd2.xlarge',
'cores': '4',
'disk': '6 TiB (3 x 2 TiB hard disk drives)',
'ram': '30.5 GiB'
},
'd2.2xlarge': {
'id': 'd2.2xlarge',
'cores': '8',
'disk': '12 TiB (6 x 2 TiB hard disk drives)',
'ram': '61 GiB'
},
'd2.4xlarge': {
'id': 'd2.4xlarge',
'cores': '16',
'disk': '24 TiB (12 x 2 TiB hard disk drives)',
'ram': '122 GiB'
},
'd2.8xlarge': {
'id': 'd2.8xlarge',
'cores': '36',
'disk': '24 TiB (24 x 2 TiB hard disk drives)',
'ram': '244 GiB'
},
},
'GPU': {
'g2.2xlarge': {
'id': 'g2.2xlarge',
'cores': '8',
'disk': '60 GiB (1 x 60 GiB SSD)',
'ram': '15 GiB'
},
'g2.8xlarge': {
'id': 'g2.8xlarge',
'cores': '32',
'disk': '240 GiB (2 x 120 GiB SSD)',
'ram': '60 GiB'
},
},
'GPU Compute': {
'p2.xlarge': {
'id': 'p2.xlarge',
'cores': '4',
'disk': 'EBS',
'ram': '61 GiB'
},
'p2.8xlarge': {
'id': 'p2.8xlarge',
'cores': '32',
'disk': 'EBS',
'ram': '488 GiB'
},
'p2.16xlarge': {
'id': 'p2.16xlarge',
'cores': '64',
'disk': 'EBS',
'ram': '732 GiB'
},
},
'High I/O': {
'i2.xlarge': {
'id': 'i2.xlarge',
'cores': '4',
'disk': 'SSD (1 x 800 GiB)',
'ram': '30.5 GiB'
},
'i2.2xlarge': {
'id': 'i2.2xlarge',
'cores': '8',
'disk': 'SSD (2 x 800 GiB)',
'ram': '61 GiB'
},
'i2.4xlarge': {
'id': 'i2.4xlarge',
'cores': '16',
'disk': 'SSD (4 x 800 GiB)',
'ram': '122 GiB'
},
'i2.8xlarge': {
'id': 'i2.8xlarge',
'cores': '32',
'disk': 'SSD (8 x 800 GiB)',
'ram': '244 GiB'
}
},
'High Memory': {
'x1.16xlarge': {
'id': 'x1.16xlarge',
'cores': '64 (with 5.45 ECUs each)',
'disk': '1920 GiB (1 x 1920 GiB)',
'ram': '976 GiB'
},
'x1.32xlarge': {
'id': 'x1.32xlarge',
'cores': '128 (with 2.73 ECUs each)',
'disk': '3840 GiB (2 x 1920 GiB)',
'ram': '1952 GiB'
},
'r4.large': {
'id': 'r4.large',
'cores': '2 (with 3.45 ECUs each)',
'disk': 'EBS',
'ram': '15.25 GiB'
},
'r4.xlarge': {
'id': 'r4.xlarge',
'cores': '4 (with 3.35 ECUs each)',
'disk': 'EBS',
'ram': '30.5 GiB'
},
'r4.2xlarge': {
'id': 'r4.2xlarge',
'cores': '8 (with 3.35 ECUs each)',
'disk': 'EBS',
'ram': '61 GiB'
},
'r4.4xlarge': {
'id': 'r4.4xlarge',
'cores': '16 (with 3.3 ECUs each)',
'disk': 'EBS',
'ram': '122 GiB'
},
'r4.8xlarge': {
'id': 'r4.8xlarge',
'cores': '32 (with 3.1 ECUs each)',
'disk': 'EBS',
'ram': '244 GiB'
},
'r4.16xlarge': {
'id': 'r4.16xlarge',
'cores': '64 (with 3.05 ECUs each)',
'disk': 'EBS',
'ram': '488 GiB'
},
'r3.large': {
'id': 'r3.large',
'cores': '2 (with 3.25 ECUs each)',
'disk': '32 GiB (1 x 32 GiB SSD)',
'ram': '15 GiB'
},
'r3.xlarge': {
'id': 'r3.xlarge',
'cores': '4 (with 3.25 ECUs each)',
'disk': '80 GiB (1 x 80 GiB SSD)',
'ram': '30.5 GiB'
},
'r3.2xlarge': {
'id': 'r3.2xlarge',
'cores': '8 (with 3.25 ECUs each)',
'disk': '160 GiB (1 x 160 GiB SSD)',
'ram': '61 GiB'
},
'r3.4xlarge': {
'id': 'r3.4xlarge',
'cores': '16 (with 3.25 ECUs each)',
'disk': '320 GiB (1 x 320 GiB SSD)',
'ram': '122 GiB'
},
'r3.8xlarge': {
'id': 'r3.8xlarge',
'cores': '32 (with 3.25 ECUs each)',
'disk': '640 GiB (2 x 320 GiB SSD)',
'ram': '244 GiB'
}
},
'High-Memory Cluster': {
'cr1.8xlarge': {
'id': 'cr1.8xlarge',
'cores': '16 (2 x Intel Xeon E5-2670, eight-core)',
'disk': '240 GiB (2 x 120 GiB SSD)',
'ram': '244 GiB'
},
},
'High Storage': {
'hs1.8xlarge': {
'id': 'hs1.8xlarge',
'cores': '16 (8 cores + 8 hyperthreads)',
'disk': '48 TiB (24 x 2 TiB hard disk drives)',
'ram': '117 GiB'
},
},
'General Purpose': {
't2.nano': {
'id': 't2.nano',
'cores': '1',
'disk': 'EBS',
'ram': '512 MiB'
},
't2.micro': {
'id': 't2.micro',
'cores': '1',
'disk': 'EBS',
'ram': '1 GiB'
},
't2.small': {
'id': 't2.small',
'cores': '1',
'disk': 'EBS',
'ram': '2 GiB'
},
't2.medium': {
'id': 't2.medium',
'cores': '2',
'disk': 'EBS',
'ram': '4 GiB'
},
't2.large': {
'id': 't2.large',
'cores': '2',
'disk': 'EBS',
'ram': '8 GiB'
},
't2.xlarge': {
'id': 't2.xlarge',
'cores': '4',
'disk': 'EBS',
'ram': '16 GiB'
},
't2.2xlarge': {
'id': 't2.2xlarge',
'cores': '8',
'disk': 'EBS',
'ram': '32 GiB'
},
'm4.large': {
'id': 'm4.large',
'cores': '2',
'disk': 'EBS - 450 Mbps',
'ram': '8 GiB'
},
'm4.xlarge': {
'id': 'm4.xlarge',
'cores': '4',
'disk': 'EBS - 750 Mbps',
'ram': '16 GiB'
},
'm4.2xlarge': {
'id': 'm4.2xlarge',
'cores': '8',
'disk': 'EBS - 1000 Mbps',
'ram': '32 GiB'
},
'm4.4xlarge': {
'id': 'm4.4xlarge',
'cores': '16',
'disk': 'EBS - 2000 Mbps',
'ram': '64 GiB'
},
'm4.10xlarge': {
'id': 'm4.10xlarge',
'cores': '40',
'disk': 'EBS - 4000 Mbps',
'ram': '160 GiB'
},
'm4.16xlarge': {
'id': 'm4.16xlarge',
'cores': '64',
'disk': 'EBS - 10000 Mbps',
'ram': '256 GiB'
},
'm3.medium': {
'id': 'm3.medium',
'cores': '1',
'disk': 'SSD (1 x 4)',
'ram': '3.75 GiB'
},
'm3.large': {
'id': 'm3.large',
'cores': '2',
'disk': 'SSD (1 x 32)',
'ram': '7.5 GiB'
},
'm3.xlarge': {
'id': 'm3.xlarge',
'cores': '4',
'disk': 'SSD (2 x 40)',
'ram': '15 GiB'
},
'm3.2xlarge': {
'id': 'm3.2xlarge',
'cores': '8',
'disk': 'SSD (2 x 80)',
'ram': '30 GiB'
},
}
}
return sizes
def avail_images(kwargs=None, 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'
)
if not isinstance(kwargs, dict):
kwargs = {}
if 'owner' in kwargs:
owner = kwargs['owner']
else:
provider = get_configured_provider()
owner = config.get_cloud_config_value(
'owner', provider, __opts__, default='amazon'
)
ret = {}
params = {'Action': 'DescribeImages',
'Owner': owner}
images = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
for image in images:
ret[image['imageId']] = image
return ret
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def keyname(vm_):
'''
Return the keyname
'''
return config.get_cloud_config_value(
'keyname', vm_, __opts__, search_global=False
)
def securitygroup(vm_):
'''
Return the security group
'''
return config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
def iam_profile(vm_):
'''
Return the IAM profile.
The IAM instance profile to associate with the instances.
This is either the Amazon Resource Name (ARN) of the instance profile
or the name of the role.
Type: String
Default: None
Required: No
Example: arn:aws:iam::111111111111:instance-profile/s3access
Example: s3access
'''
return config.get_cloud_config_value(
'iam_profile', vm_, __opts__, search_global=False
)
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
ret = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, default='public_ips',
search_global=False
)
if ret not in ('public_ips', 'private_ips'):
log.warning(
'Invalid ssh_interface: %s. '
'Allowed options are ("public_ips", "private_ips"). '
'Defaulting to "public_ips".', ret
)
ret = 'public_ips'
return ret
def get_ssh_gateway_config(vm_):
'''
Return the ssh_gateway configuration.
'''
ssh_gateway = config.get_cloud_config_value(
'ssh_gateway', vm_, __opts__, default=None,
search_global=False
)
# Check to see if a SSH Gateway will be used.
if not isinstance(ssh_gateway, six.string_types):
return None
# Create dictionary of configuration items
# ssh_gateway
ssh_gateway_config = {'ssh_gateway': ssh_gateway}
# ssh_gateway_port
ssh_gateway_config['ssh_gateway_port'] = config.get_cloud_config_value(
'ssh_gateway_port', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_username
ssh_gateway_config['ssh_gateway_user'] = config.get_cloud_config_value(
'ssh_gateway_username', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_private_key
ssh_gateway_config['ssh_gateway_key'] = config.get_cloud_config_value(
'ssh_gateway_private_key', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_password
ssh_gateway_config['ssh_gateway_password'] = config.get_cloud_config_value(
'ssh_gateway_password', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_command
ssh_gateway_config['ssh_gateway_command'] = config.get_cloud_config_value(
'ssh_gateway_command', vm_, __opts__, default=None,
search_global=False
)
# Check if private key exists
key_filename = ssh_gateway_config['ssh_gateway_key']
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_gateway_private_key \'{0}\' does not exist'
.format(key_filename)
)
elif (
key_filename is None and
not ssh_gateway_config['ssh_gateway_password']
):
raise SaltCloudConfigError(
'No authentication method. Please define: '
' ssh_gateway_password or ssh_gateway_private_key'
)
return ssh_gateway_config
def get_location(vm_=None):
'''
Return the EC2 region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
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 = {}
params = {'Action': 'DescribeRegions'}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
for region in result:
ret[region['regionName']] = {
'name': region['regionName'],
'endpoint': region['regionEndpoint'],
}
return ret
def get_availability_zone(vm_):
'''
Return the availability zone to use
'''
avz = config.get_cloud_config_value(
'availability_zone', vm_, __opts__, search_global=False
)
if avz is None:
return None
zones = _list_availability_zones(vm_)
# Validate user-specified AZ
if avz not in zones:
raise SaltCloudException(
'The specified availability zone isn\'t valid in this region: '
'{0}\n'.format(
avz
)
)
# check specified AZ is available
elif zones[avz] != 'available':
raise SaltCloudException(
'The specified availability zone isn\'t currently available: '
'{0}\n'.format(
avz
)
)
return avz
def get_tenancy(vm_):
'''
Returns the Tenancy to use.
Can be "dedicated" or "default". Cannot be present for spot instances.
'''
return config.get_cloud_config_value(
'tenancy', vm_, __opts__, search_global=False
)
def get_imageid(vm_):
'''
Returns the ImageId to use
'''
image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if image.startswith('ami-'):
return image
# a poor man's cache
if not hasattr(get_imageid, 'images'):
get_imageid.images = {}
elif image in get_imageid.images:
return get_imageid.images[image]
params = {'Action': 'DescribeImages',
'Filter.0.Name': 'name',
'Filter.0.Value.0': image}
# Query AWS, sort by 'creationDate' and get the last imageId
_t = lambda x: datetime.datetime.strptime(x['creationDate'], '%Y-%m-%dT%H:%M:%S.%fZ')
image_id = sorted(aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'),
lambda i, j: salt.utils.compat.cmp(_t(i), _t(j))
)[-1]['imageId']
get_imageid.images[image] = image_id
return image_id
def _get_subnetname_id(subnetname):
'''
Returns the SubnetId of a SubnetName to use
'''
params = {'Action': 'DescribeSubnets'}
for subnet in aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'):
tags = subnet.get('tagSet', {}).get('item', {})
if not isinstance(tags, list):
tags = [tags]
for tag in tags:
if tag['key'] == 'Name' and tag['value'] == subnetname:
log.debug(
'AWS Subnet ID of %s is %s',
subnetname, subnet['subnetId']
)
return subnet['subnetId']
return None
def get_subnetid(vm_):
'''
Returns the SubnetId to use
'''
subnetid = config.get_cloud_config_value(
'subnetid', vm_, __opts__, search_global=False
)
if subnetid:
return subnetid
subnetname = config.get_cloud_config_value(
'subnetname', vm_, __opts__, search_global=False
)
if subnetname:
return _get_subnetname_id(subnetname)
return None
def _get_securitygroupname_id(securitygroupname_list):
'''
Returns the SecurityGroupId of a SecurityGroupName to use
'''
securitygroupid_set = set()
if not isinstance(securitygroupname_list, list):
securitygroupname_list = [securitygroupname_list]
params = {'Action': 'DescribeSecurityGroups'}
for sg in aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'):
if sg['groupName'] in securitygroupname_list:
log.debug(
'AWS SecurityGroup ID of %s is %s',
sg['groupName'], sg['groupId']
)
securitygroupid_set.add(sg['groupId'])
return list(securitygroupid_set)
def securitygroupid(vm_):
'''
Returns the SecurityGroupId
'''
securitygroupid_set = set()
securitygroupid_list = config.get_cloud_config_value(
'securitygroupid',
vm_,
__opts__,
search_global=False
)
# If the list is None, then the set will remain empty
# If the list is already a set then calling 'set' on it is a no-op
# If the list is a string, then calling 'set' generates a one-element set
# If the list is anything else, stacktrace
if securitygroupid_list:
securitygroupid_set = securitygroupid_set.union(set(securitygroupid_list))
securitygroupname_list = config.get_cloud_config_value(
'securitygroupname', vm_, __opts__, search_global=False
)
if securitygroupname_list:
if not isinstance(securitygroupname_list, list):
securitygroupname_list = [securitygroupname_list]
params = {'Action': 'DescribeSecurityGroups'}
for sg in aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'):
if sg['groupName'] in securitygroupname_list:
log.debug(
'AWS SecurityGroup ID of %s is %s',
sg['groupName'], sg['groupId']
)
securitygroupid_set.add(sg['groupId'])
return list(securitygroupid_set)
def get_placementgroup(vm_):
'''
Returns the PlacementGroup to use
'''
return config.get_cloud_config_value(
'placementgroup', vm_, __opts__, search_global=False
)
def get_spot_config(vm_):
'''
Returns the spot instance configuration for the provided vm
'''
return config.get_cloud_config_value(
'spot_config', vm_, __opts__, search_global=False
)
def get_provider(vm_=None):
'''
Extract the provider name from vm
'''
if vm_ is None:
provider = __active_provider_name__ or 'ec2'
else:
provider = vm_.get('provider', 'ec2')
if ':' in provider:
prov_comps = provider.split(':')
provider = prov_comps[0]
return provider
def _list_availability_zones(vm_=None):
'''
List all availability zones in the current region
'''
ret = {}
params = {'Action': 'DescribeAvailabilityZones',
'Filter.0.Name': 'region-name',
'Filter.0.Value.0': get_location(vm_)}
result = aws.query(params,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
for zone in result:
ret[zone['zoneName']] = zone['zoneState']
return ret
def block_device_mappings(vm_):
'''
Return the block device mapping:
.. code-block:: python
[{'DeviceName': '/dev/sdb', 'VirtualName': 'ephemeral0'},
{'DeviceName': '/dev/sdc', 'VirtualName': 'ephemeral1'}]
'''
return config.get_cloud_config_value(
'block_device_mappings', vm_, __opts__, search_global=True
)
def _request_eip(interface, vm_):
'''
Request and return Elastic IP
'''
params = {'Action': 'AllocateAddress'}
params['Domain'] = interface.setdefault('domain', 'vpc')
eips = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
for eip in eips:
if 'allocationId' in eip:
return eip['allocationId']
return None
def _create_eni_if_necessary(interface, vm_):
'''
Create an Elastic Interface if necessary and return a Network Interface Specification
'''
if 'NetworkInterfaceId' in interface and interface['NetworkInterfaceId'] is not None:
return {'DeviceIndex': interface['DeviceIndex'],
'NetworkInterfaceId': interface['NetworkInterfaceId']}
params = {'Action': 'DescribeSubnets'}
subnet_query = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'SecurityGroupId' not in interface and 'securitygroupname' in interface:
interface['SecurityGroupId'] = _get_securitygroupname_id(interface['securitygroupname'])
if 'SubnetId' not in interface and 'subnetname' in interface:
interface['SubnetId'] = _get_subnetname_id(interface['subnetname'])
subnet_id = _get_subnet_id_for_interface(subnet_query, interface)
if not subnet_id:
raise SaltCloudConfigError(
'No such subnet <{0}>'.format(interface.get('SubnetId'))
)
params = {'SubnetId': subnet_id}
for k in 'Description', 'PrivateIpAddress', 'SecondaryPrivateIpAddressCount':
if k in interface:
params[k] = interface[k]
for k in 'PrivateIpAddresses', 'SecurityGroupId':
if k in interface:
params.update(_param_from_config(k, interface[k]))
if 'AssociatePublicIpAddress' in interface:
# Associating a public address in a VPC only works when the interface is not
# created beforehand, but as a part of the machine creation request.
for k in ('DeviceIndex', 'AssociatePublicIpAddress', 'NetworkInterfaceId'):
if k in interface:
params[k] = interface[k]
params['DeleteOnTermination'] = interface.get('delete_interface_on_terminate', True)
return params
params['Action'] = 'CreateNetworkInterface'
result = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
eni_desc = result[1]
if not eni_desc or not eni_desc.get('networkInterfaceId'):
raise SaltCloudException('Failed to create interface: {0}'.format(result))
eni_id = eni_desc.get('networkInterfaceId')
log.debug(
'Created network interface %s inst %s',
eni_id, interface['DeviceIndex']
)
associate_public_ip = interface.get('AssociatePublicIpAddress', False)
if isinstance(associate_public_ip, six.string_types):
# Assume id of EIP as value
_associate_eip_with_interface(eni_id, associate_public_ip, vm_=vm_)
if interface.get('associate_eip'):
_associate_eip_with_interface(eni_id, interface.get('associate_eip'), vm_=vm_)
elif interface.get('allocate_new_eip'):
_new_eip = _request_eip(interface, vm_)
_associate_eip_with_interface(eni_id, _new_eip, vm_=vm_)
elif interface.get('allocate_new_eips'):
addr_list = _list_interface_private_addrs(eni_desc)
eip_list = []
for idx, addr in enumerate(addr_list):
eip_list.append(_request_eip(interface, vm_))
for idx, addr in enumerate(addr_list):
_associate_eip_with_interface(eni_id, eip_list[idx], addr, vm_=vm_)
if 'Name' in interface:
tag_params = {'Action': 'CreateTags',
'ResourceId.0': eni_id,
'Tag.0.Key': 'Name',
'Tag.0.Value': interface['Name']}
tag_response = aws.query(tag_params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'error' in tag_response:
log.error('Failed to set name of interface {0}')
return {'DeviceIndex': interface['DeviceIndex'],
'NetworkInterfaceId': eni_id}
def _get_subnet_id_for_interface(subnet_query, interface):
for subnet_query_result in subnet_query:
if 'item' in subnet_query_result:
if isinstance(subnet_query_result['item'], dict):
subnet_id = _get_subnet_from_subnet_query(subnet_query_result['item'],
interface)
if subnet_id is not None:
return subnet_id
else:
for subnet in subnet_query_result['item']:
subnet_id = _get_subnet_from_subnet_query(subnet, interface)
if subnet_id is not None:
return subnet_id
def _get_subnet_from_subnet_query(subnet_query, interface):
if 'subnetId' in subnet_query:
if interface.get('SubnetId'):
if subnet_query['subnetId'] == interface['SubnetId']:
return subnet_query['subnetId']
else:
return subnet_query['subnetId']
def _list_interface_private_addrs(eni_desc):
'''
Returns a list of all of the private IP addresses attached to a
network interface. The 'primary' address will be listed first.
'''
primary = eni_desc.get('privateIpAddress')
if not primary:
return None
addresses = [primary]
lst = eni_desc.get('privateIpAddressesSet', {}).get('item', [])
if not isinstance(lst, list):
return addresses
for entry in lst:
if entry.get('primary') == 'true':
continue
if entry.get('privateIpAddress'):
addresses.append(entry.get('privateIpAddress'))
return addresses
def _modify_eni_properties(eni_id, properties=None, vm_=None):
'''
Change properties of the interface
with id eni_id to the values in properties dict
'''
if not isinstance(properties, dict):
raise SaltCloudException(
'ENI properties must be a dictionary'
)
params = {'Action': 'ModifyNetworkInterfaceAttribute',
'NetworkInterfaceId': eni_id}
for k, v in six.iteritems(properties):
params[k] = v
result = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if isinstance(result, dict) and result.get('error'):
raise SaltCloudException(
'Could not change interface <{0}> attributes <\'{1}\'>'.format(
eni_id, properties
)
)
else:
return result
def _associate_eip_with_interface(eni_id, eip_id, private_ip=None, vm_=None):
'''
Accept the id of a network interface, and the id of an elastic ip
address, and associate the two of them, such that traffic sent to the
elastic ip address will be forwarded (NATted) to this network interface.
Optionally specify the private (10.x.x.x) IP address that traffic should
be NATted to - useful if you have multiple IP addresses assigned to an
interface.
'''
params = {'Action': 'AssociateAddress',
'NetworkInterfaceId': eni_id,
'AllocationId': eip_id}
if private_ip:
params['PrivateIpAddress'] = private_ip
result = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if not result[2].get('associationId'):
raise SaltCloudException(
'Could not associate elastic ip address '
'<{0}> with network interface <{1}>'.format(
eip_id, eni_id
)
)
log.debug(
'Associated ElasticIP address %s with interface %s',
eip_id, eni_id
)
return result[2].get('associationId')
def _update_enis(interfaces, instance, vm_=None):
config_enis = {}
instance_enis = []
for interface in interfaces:
if 'DeviceIndex' in interface:
if interface['DeviceIndex'] in config_enis:
log.error(
'Duplicate DeviceIndex in profile. Cannot update ENIs.'
)
return None
config_enis[six.text_type(interface['DeviceIndex'])] = interface
query_enis = instance[0]['instancesSet']['item']['networkInterfaceSet']['item']
if isinstance(query_enis, list):
for query_eni in query_enis:
instance_enis.append((query_eni['networkInterfaceId'], query_eni['attachment']))
else:
instance_enis.append((query_enis['networkInterfaceId'], query_enis['attachment']))
for eni_id, eni_data in instance_enis:
delete_on_terminate = True
if 'DeleteOnTermination' in config_enis[eni_data['deviceIndex']]:
delete_on_terminate = config_enis[eni_data['deviceIndex']]['DeleteOnTermination']
elif 'delete_interface_on_terminate' in config_enis[eni_data['deviceIndex']]:
delete_on_terminate = config_enis[eni_data['deviceIndex']]['delete_interface_on_terminate']
params_attachment = {'Attachment.AttachmentId': eni_data['attachmentId'],
'Attachment.DeleteOnTermination': delete_on_terminate}
set_eni_attachment_attributes = _modify_eni_properties(eni_id, params_attachment, vm_=vm_)
if 'SourceDestCheck' in config_enis[eni_data['deviceIndex']]:
params_sourcedest = {'SourceDestCheck.Value': config_enis[eni_data['deviceIndex']]['SourceDestCheck']}
set_eni_sourcedest_property = _modify_eni_properties(eni_id, params_sourcedest, vm_=vm_)
return None
def _param_from_config(key, data):
'''
Return EC2 API parameters based on the given config data.
Examples:
1. List of dictionaries
>>> data = [
... {'DeviceIndex': 0, 'SubnetId': 'subid0',
... 'AssociatePublicIpAddress': True},
... {'DeviceIndex': 1,
... 'SubnetId': 'subid1',
... 'PrivateIpAddress': '192.168.1.128'}
... ]
>>> _param_from_config('NetworkInterface', data)
... {'NetworkInterface.0.SubnetId': 'subid0',
... 'NetworkInterface.0.DeviceIndex': 0,
... 'NetworkInterface.1.SubnetId': 'subid1',
... 'NetworkInterface.1.PrivateIpAddress': '192.168.1.128',
... 'NetworkInterface.0.AssociatePublicIpAddress': 'true',
... 'NetworkInterface.1.DeviceIndex': 1}
2. List of nested dictionaries
>>> data = [
... {'DeviceName': '/dev/sdf',
... 'Ebs': {
... 'SnapshotId': 'dummy0',
... 'VolumeSize': 200,
... 'VolumeType': 'standard'}},
... {'DeviceName': '/dev/sdg',
... 'Ebs': {
... 'SnapshotId': 'dummy1',
... 'VolumeSize': 100,
... 'VolumeType': 'standard'}}
... ]
>>> _param_from_config('BlockDeviceMapping', data)
... {'BlockDeviceMapping.0.Ebs.VolumeType': 'standard',
... 'BlockDeviceMapping.1.Ebs.SnapshotId': 'dummy1',
... 'BlockDeviceMapping.0.Ebs.VolumeSize': 200,
... 'BlockDeviceMapping.0.Ebs.SnapshotId': 'dummy0',
... 'BlockDeviceMapping.1.Ebs.VolumeType': 'standard',
... 'BlockDeviceMapping.1.DeviceName': '/dev/sdg',
... 'BlockDeviceMapping.1.Ebs.VolumeSize': 100,
... 'BlockDeviceMapping.0.DeviceName': '/dev/sdf'}
3. Dictionary of dictionaries
>>> data = { 'Arn': 'dummyarn', 'Name': 'Tester' }
>>> _param_from_config('IamInstanceProfile', data)
{'IamInstanceProfile.Arn': 'dummyarn', 'IamInstanceProfile.Name': 'Tester'}
'''
param = {}
if isinstance(data, dict):
for k, v in six.iteritems(data):
param.update(_param_from_config('{0}.{1}'.format(key, k), v))
elif isinstance(data, list) or isinstance(data, tuple):
for idx, conf_item in enumerate(data):
prefix = '{0}.{1}'.format(key, idx)
param.update(_param_from_config(prefix, conf_item))
else:
if isinstance(data, bool):
# convert boolean True/False to 'true'/'false'
param.update({key: six.text_type(data).lower()})
else:
param.update({key: data})
return param
def request_instance(vm_=None, call=None):
'''
Put together all of the information necessary to request an instance on EC2,
and then fire off the request the instance.
Returns data about the instance
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
location = vm_.get('location', get_location(vm_))
# do we launch a regular vm or a spot instance?
# see http://goo.gl/hYZ13f for more information on EC2 API
spot_config = get_spot_config(vm_)
if spot_config is not None:
if 'spot_price' not in spot_config:
raise SaltCloudSystemExit(
'Spot instance config for {0} requires a spot_price '
'attribute.'.format(vm_['name'])
)
params = {'Action': 'RequestSpotInstances',
'InstanceCount': '1',
'Type': spot_config['type']
if 'type' in spot_config else 'one-time',
'SpotPrice': spot_config['spot_price']}
# All of the necessary launch parameters for a VM when using
# spot instances are the same except for the prefix below
# being tacked on.
spot_prefix = 'LaunchSpecification.'
# regular EC2 instance
else:
# WARNING! EXPERIMENTAL!
# This allows more than one instance to be spun up in a single call.
# The first instance will be called by the name provided, but all other
# instances will be nameless (or more specifically, they will use the
# InstanceId as the name). This interface is expected to change, so
# use at your own risk.
min_instance = config.get_cloud_config_value(
'min_instance', vm_, __opts__, search_global=False, default=1
)
max_instance = config.get_cloud_config_value(
'max_instance', vm_, __opts__, search_global=False, default=1
)
params = {'Action': 'RunInstances',
'MinCount': min_instance,
'MaxCount': max_instance}
# Normal instances should have no prefix.
spot_prefix = ''
image_id = get_imageid(vm_)
params[spot_prefix + 'ImageId'] = image_id
userdata = None
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is None:
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
else:
log.trace('userdata_file: %s', userdata_file)
if os.path.exists(userdata_file):
with salt.utils.files.fopen(userdata_file, 'r') as fh_:
userdata = salt.utils.stringutils.to_unicode(fh_.read())
userdata = salt.utils.cloud.userdata_template(__opts__, vm_, userdata)
if userdata is not None:
try:
params[spot_prefix + 'UserData'] = base64.b64encode(
salt.utils.stringutils.to_bytes(userdata)
)
except Exception as exc:
log.exception('Failed to encode userdata: %s', exc)
vm_size = config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
)
params[spot_prefix + 'InstanceType'] = vm_size
ex_keyname = keyname(vm_)
if ex_keyname:
params[spot_prefix + 'KeyName'] = ex_keyname
ex_securitygroup = securitygroup(vm_)
if ex_securitygroup:
if not isinstance(ex_securitygroup, list):
params[spot_prefix + 'SecurityGroup.1'] = ex_securitygroup
else:
for counter, sg_ in enumerate(ex_securitygroup):
params[spot_prefix + 'SecurityGroup.{0}'.format(counter)] = sg_
ex_iam_profile = iam_profile(vm_)
if ex_iam_profile:
try:
if ex_iam_profile.startswith('arn:aws:iam:'):
params[
spot_prefix + 'IamInstanceProfile.Arn'
] = ex_iam_profile
else:
params[
spot_prefix + 'IamInstanceProfile.Name'
] = ex_iam_profile
except AttributeError:
raise SaltCloudConfigError(
'\'iam_profile\' should be a string value.'
)
az_ = get_availability_zone(vm_)
if az_ is not None:
params[spot_prefix + 'Placement.AvailabilityZone'] = az_
tenancy_ = get_tenancy(vm_)
if tenancy_ is not None:
if spot_config is not None:
raise SaltCloudConfigError(
'Spot instance config for {0} does not support '
'specifying tenancy.'.format(vm_['name'])
)
params['Placement.Tenancy'] = tenancy_
subnetid_ = get_subnetid(vm_)
if subnetid_ is not None:
params[spot_prefix + 'SubnetId'] = subnetid_
ex_securitygroupid = securitygroupid(vm_)
if ex_securitygroupid:
if not isinstance(ex_securitygroupid, list):
params[spot_prefix + 'SecurityGroupId.1'] = ex_securitygroupid
else:
for counter, sg_ in enumerate(ex_securitygroupid):
params[
spot_prefix + 'SecurityGroupId.{0}'.format(counter)
] = sg_
placementgroup_ = get_placementgroup(vm_)
if placementgroup_ is not None:
params[spot_prefix + 'Placement.GroupName'] = placementgroup_
blockdevicemappings_holder = block_device_mappings(vm_)
if blockdevicemappings_holder:
for _bd in blockdevicemappings_holder:
if 'tag' in _bd:
_bd.pop('tag')
ex_blockdevicemappings = blockdevicemappings_holder
if ex_blockdevicemappings:
params.update(_param_from_config(spot_prefix + 'BlockDeviceMapping',
ex_blockdevicemappings))
network_interfaces = config.get_cloud_config_value(
'network_interfaces',
vm_,
__opts__,
search_global=False
)
if network_interfaces:
eni_devices = []
for interface in network_interfaces:
log.debug('Create network interface: %s', interface)
_new_eni = _create_eni_if_necessary(interface, vm_)
eni_devices.append(_new_eni)
params.update(_param_from_config(spot_prefix + 'NetworkInterface',
eni_devices))
set_ebs_optimized = config.get_cloud_config_value(
'ebs_optimized', vm_, __opts__, search_global=False
)
if set_ebs_optimized is not None:
if not isinstance(set_ebs_optimized, bool):
raise SaltCloudConfigError(
'\'ebs_optimized\' should be a boolean value.'
)
params[spot_prefix + 'EbsOptimized'] = set_ebs_optimized
set_del_root_vol_on_destroy = config.get_cloud_config_value(
'del_root_vol_on_destroy', vm_, __opts__, search_global=False
)
set_termination_protection = config.get_cloud_config_value(
'termination_protection', vm_, __opts__, search_global=False
)
if set_termination_protection is not None:
if not isinstance(set_termination_protection, bool):
raise SaltCloudConfigError(
'\'termination_protection\' should be a boolean value.'
)
params.update(_param_from_config(spot_prefix + 'DisableApiTermination',
set_termination_protection))
if set_del_root_vol_on_destroy and not isinstance(set_del_root_vol_on_destroy, bool):
raise SaltCloudConfigError(
'\'del_root_vol_on_destroy\' should be a boolean value.'
)
vm_['set_del_root_vol_on_destroy'] = set_del_root_vol_on_destroy
if set_del_root_vol_on_destroy:
# first make sure to look up the root device name
# as Ubuntu and CentOS (and most likely other OSs)
# use different device identifiers
log.info('Attempting to look up root device name for image id %s on '
'VM %s', image_id, vm_['name'])
rd_params = {
'Action': 'DescribeImages',
'ImageId.1': image_id
}
try:
rd_data = aws.query(rd_params,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'error' in rd_data:
return rd_data['error']
log.debug('EC2 Response: \'%s\'', rd_data)
except Exception as exc:
log.error(
'Error getting root device name for image id %s for '
'VM %s: \n%s', image_id, vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
raise
# make sure we have a response
if not rd_data:
err_msg = 'There was an error querying EC2 for the root device ' \
'of image id {0}. Empty response.'.format(image_id)
raise SaltCloudSystemExit(err_msg)
# pull the root device name from the result and use it when
# launching the new VM
rd_name = None
rd_type = None
if 'blockDeviceMapping' in rd_data[0]:
# Some ami instances do not have a root volume. Ignore such cases
if rd_data[0]['blockDeviceMapping'] is not None:
item = rd_data[0]['blockDeviceMapping']['item']
if isinstance(item, list):
item = item[0]
rd_name = item['deviceName']
# Grab the volume type
rd_type = item['ebs'].get('volumeType', None)
log.info('Found root device name: %s', rd_name)
if rd_name is not None:
if ex_blockdevicemappings:
dev_list = [
dev['DeviceName'] for dev in ex_blockdevicemappings
]
else:
dev_list = []
if rd_name in dev_list:
# Device already listed, just grab the index
dev_index = dev_list.index(rd_name)
else:
dev_index = len(dev_list)
# Add the device name in since it wasn't already there
params[
'{0}BlockDeviceMapping.{1}.DeviceName'.format(
spot_prefix, dev_index
)
] = rd_name
# Set the termination value
termination_key = '{0}BlockDeviceMapping.{1}.Ebs.DeleteOnTermination'.format(spot_prefix, dev_index)
params[termination_key] = six.text_type(set_del_root_vol_on_destroy).lower()
# Use default volume type if not specified
if ex_blockdevicemappings and dev_index < len(ex_blockdevicemappings) and \
'Ebs.VolumeType' not in ex_blockdevicemappings[dev_index]:
type_key = '{0}BlockDeviceMapping.{1}.Ebs.VolumeType'.format(spot_prefix, dev_index)
params[type_key] = rd_type
set_del_all_vols_on_destroy = config.get_cloud_config_value(
'del_all_vols_on_destroy', vm_, __opts__, search_global=False, default=False
)
if set_del_all_vols_on_destroy and not isinstance(set_del_all_vols_on_destroy, bool):
raise SaltCloudConfigError(
'\'del_all_vols_on_destroy\' should be a boolean value.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={
'kwargs': __utils__['cloud.filter_event'](
'requesting', params, list(params)
),
'location': location,
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
provider = get_provider(vm_)
try:
data = aws.query(params,
'instancesSet',
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if 'error' in data:
return data['error']
except Exception as exc:
log.error(
'Error creating %s on EC2 when trying to run the initial '
'deployment: \n%s', vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
raise
# if we're using spot instances, we need to wait for the spot request
# to become active before we continue
if spot_config:
sir_id = data[0]['spotInstanceRequestId']
vm_['spotRequestId'] = sir_id
def __query_spot_instance_request(sir_id, location):
params = {'Action': 'DescribeSpotInstanceRequests',
'SpotInstanceRequestId.1': sir_id}
data = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if not data:
log.error(
'There was an error while querying EC2. Empty response'
)
# Trigger a failure in the wait for spot instance method
return False
if isinstance(data, dict) and 'error' in data:
log.warning('There was an error in the query. %s', data['error'])
# Trigger a failure in the wait for spot instance method
return False
log.debug('Returned query data: %s', data)
state = data[0].get('state')
if state == 'active':
return data
if state == 'open':
# Still waiting for an active state
log.info('Spot instance status: %s', data[0]['status']['message'])
return None
if state in ['cancelled', 'failed', 'closed']:
# Request will never be active, fail
log.error('Spot instance request resulted in state \'{0}\'. '
'Nothing else we can do here.')
return False
__utils__['cloud.fire_event'](
'event',
'waiting for spot instance',
'salt/cloud/{0}/waiting_for_spot'.format(vm_['name']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
data = _wait_for_spot_instance(
__query_spot_instance_request,
update_args=(sir_id, location),
timeout=config.get_cloud_config_value(
'wait_for_spot_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_spot_interval', vm_, __opts__, default=30),
interval_multiplier=config.get_cloud_config_value(
'wait_for_spot_interval_multiplier',
vm_,
__opts__,
default=1),
max_failures=config.get_cloud_config_value(
'wait_for_spot_max_failures',
vm_,
__opts__,
default=10),
)
log.debug('wait_for_spot_instance data %s', data)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# Cancel the existing spot instance request
params = {'Action': 'CancelSpotInstanceRequests',
'SpotInstanceRequestId.1': sir_id}
data = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
log.debug('Canceled spot instance request %s. Data '
'returned: %s', sir_id, data)
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
return data, vm_
def query_instance(vm_=None, call=None):
'''
Query an instance upon creation from the EC2 API
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The query_instance action must be called with -a or --action.'
)
instance_id = vm_['instance_id']
location = vm_.get('location', get_location(vm_))
__utils__['cloud.fire_event'](
'event',
'querying instance',
'salt/cloud/{0}/querying'.format(vm_['name']),
args={'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('The new VM instance_id is %s', instance_id)
params = {'Action': 'DescribeInstances',
'InstanceId.1': instance_id}
provider = get_provider(vm_)
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
data, requesturl = aws.query(params, # pylint: disable=unbalanced-tuple-unpacking
location=location,
provider=provider,
opts=__opts__,
return_url=True,
sigver='4')
log.debug('The query returned: %s', data)
if isinstance(data, dict) and 'error' in data:
log.warning(
'There was an error in the query. %s attempts '
'remaining: %s', attempts, data['error']
)
elif isinstance(data, list) and not data:
log.warning(
'Query returned an empty list. %s attempts '
'remaining.', attempts
)
else:
break
aws.sleep_exponential_backoff(attempts)
attempts += 1
continue
else:
raise SaltCloudSystemExit(
'An error occurred while creating VM: {0}'.format(data['error'])
)
def __query_ip_address(params, url): # pylint: disable=W0613
data = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if not data:
log.error(
'There was an error while querying EC2. Empty response'
)
# Trigger a failure in the wait for IP function
return False
if isinstance(data, dict) and 'error' in data:
log.warning('There was an error in the query. %s', data['error'])
# Trigger a failure in the wait for IP function
return False
log.debug('Returned query data: %s', data)
if ssh_interface(vm_) == 'public_ips':
if 'ipAddress' in data[0]['instancesSet']['item']:
return data
else:
log.error(
'Public IP not detected.'
)
if ssh_interface(vm_) == 'private_ips':
if 'privateIpAddress' in data[0]['instancesSet']['item']:
return data
else:
log.error(
'Private IP not detected.'
)
try:
data = salt.utils.cloud.wait_for_ip(
__query_ip_address,
update_args=(params, requesturl),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value(
'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if 'reactor' in vm_ and vm_['reactor'] is True:
__utils__['cloud.fire_event'](
'event',
'instance queried',
'salt/cloud/{0}/query_reactor'.format(vm_['name']),
args={'data': data},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return data
def wait_for_instance(
vm_=None,
data=None,
ip_address=None,
display_ssh_output=True,
call=None,
):
'''
Wait for an instance upon creation from the EC2 API, to become available
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The wait_for_instance action must be called with -a or --action.'
)
if vm_ is None:
vm_ = {}
if data is None:
data = {}
ssh_gateway_config = vm_.get(
'gateway', get_ssh_gateway_config(vm_)
)
__utils__['cloud.fire_event'](
'event',
'waiting for ssh',
'salt/cloud/{0}/waiting_for_ssh'.format(vm_['name']),
args={'ip_address': ip_address},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
ssh_connect_timeout = config.get_cloud_config_value(
'ssh_connect_timeout', vm_, __opts__, 900 # 15 minutes
)
ssh_port = config.get_cloud_config_value(
'ssh_port', vm_, __opts__, 22
)
if config.get_cloud_config_value('win_installer', vm_, __opts__):
username = config.get_cloud_config_value(
'win_username', vm_, __opts__, default='Administrator'
)
win_passwd = config.get_cloud_config_value(
'win_password', vm_, __opts__, default=''
)
win_deploy_auth_retries = config.get_cloud_config_value(
'win_deploy_auth_retries', vm_, __opts__, default=10
)
win_deploy_auth_retry_delay = config.get_cloud_config_value(
'win_deploy_auth_retry_delay', vm_, __opts__, default=1
)
use_winrm = config.get_cloud_config_value(
'use_winrm', vm_, __opts__, default=False
)
winrm_verify_ssl = config.get_cloud_config_value(
'winrm_verify_ssl', vm_, __opts__, default=True
)
if win_passwd and win_passwd == 'auto':
log.debug('Waiting for auto-generated Windows EC2 password')
while True:
password_data = get_password_data(
name=vm_['name'],
kwargs={
'key_file': vm_['private_key'],
},
call='action',
)
win_passwd = password_data.get('password', None)
if win_passwd is None:
log.debug(password_data)
# This wait is so high, because the password is unlikely to
# be generated for at least 4 minutes
time.sleep(60)
else:
logging_data = password_data
logging_data['password'] = 'XXX-REDACTED-XXX'
logging_data['passwordData'] = 'XXX-REDACTED-XXX'
log.debug(logging_data)
vm_['win_password'] = win_passwd
break
# SMB used whether psexec or winrm
if not salt.utils.cloud.wait_for_port(ip_address,
port=445,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to connect to remote windows host'
)
# If not using winrm keep same psexec behavior
if not use_winrm:
log.debug('Trying to authenticate via SMB using psexec')
if not salt.utils.cloud.validate_windows_cred(ip_address,
username,
win_passwd,
retries=win_deploy_auth_retries,
retry_delay=win_deploy_auth_retry_delay):
raise SaltCloudSystemExit(
'Failed to authenticate against remote windows host (smb)'
)
# If using winrm
else:
# Default HTTPS port can be changed in cloud configuration
winrm_port = config.get_cloud_config_value(
'winrm_port', vm_, __opts__, default=5986
)
# Wait for winrm port to be available
if not salt.utils.cloud.wait_for_port(ip_address,
port=winrm_port,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to connect to remote windows host (winrm)'
)
log.debug('Trying to authenticate via Winrm using pywinrm')
if not salt.utils.cloud.wait_for_winrm(ip_address,
winrm_port,
username,
win_passwd,
timeout=ssh_connect_timeout,
verify=winrm_verify_ssl):
raise SaltCloudSystemExit(
'Failed to authenticate against remote windows host'
)
elif salt.utils.cloud.wait_for_port(ip_address,
port=ssh_port,
timeout=ssh_connect_timeout,
gateway=ssh_gateway_config
):
# If a known_hosts_file is configured, this instance will not be
# accessible until it has a host key. Since this is provided on
# supported instances by cloud-init, and viewable to us only from the
# console output (which may take several minutes to become available,
# we have some more waiting to do here.
known_hosts_file = config.get_cloud_config_value(
'known_hosts_file', vm_, __opts__, default=None
)
if known_hosts_file:
console = {}
while 'output_decoded' not in console:
console = get_console_output(
instance_id=vm_['instance_id'],
call='action',
location=get_location(vm_)
)
pprint.pprint(console)
time.sleep(5)
output = salt.utils.stringutils.to_unicode(console['output_decoded'])
comps = output.split('-----BEGIN SSH HOST KEY KEYS-----')
if len(comps) < 2:
# Fail; there are no host keys
return False
comps = comps[1].split('-----END SSH HOST KEY KEYS-----')
keys = ''
for line in comps[0].splitlines():
if not line:
continue
keys += '\n{0} {1}'.format(ip_address, line)
with salt.utils.files.fopen(known_hosts_file, 'a') as fp_:
fp_.write(salt.utils.stringutils.to_str(keys))
fp_.close()
for user in vm_['usernames']:
if salt.utils.cloud.wait_for_passwd(
host=ip_address,
port=ssh_port,
username=user,
ssh_timeout=config.get_cloud_config_value(
'wait_for_passwd_timeout', vm_, __opts__, default=1 * 60
),
key_filename=vm_['key_filename'],
display_ssh_output=display_ssh_output,
gateway=ssh_gateway_config,
maxtries=config.get_cloud_config_value(
'wait_for_passwd_maxtries', vm_, __opts__, default=15
),
known_hosts_file=config.get_cloud_config_value(
'known_hosts_file', vm_, __opts__,
default='/dev/null'
),
):
__opts__['ssh_username'] = user
vm_['ssh_username'] = user
break
else:
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
else:
raise SaltCloudSystemExit(
'Failed to connect to remote ssh'
)
if 'reactor' in vm_ and vm_['reactor'] is True:
__utils__['cloud.fire_event'](
'event',
'ssh is available',
'salt/cloud/{0}/ssh_ready_reactor'.format(vm_['name']),
args={'ip_address': ip_address},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return vm_
def _validate_key_path_and_mode(key_filename):
if key_filename is None:
raise SaltCloudSystemExit(
'The required \'private_key\' configuration setting is missing from the '
'\'ec2\' driver.'
)
if not os.path.exists(key_filename):
raise SaltCloudSystemExit(
'The EC2 key file \'{0}\' does not exist.\n'.format(
key_filename
)
)
key_mode = stat.S_IMODE(os.stat(key_filename).st_mode)
if key_mode not in (0o400, 0o600):
raise SaltCloudSystemExit(
'The EC2 key file \'{0}\' needs to be set to mode 0400 or 0600.\n'.format(
key_filename
)
)
return True
def create(vm_=None, call=None):
'''
Create a single VM from a data dict
'''
if call:
raise SaltCloudSystemExit(
'You cannot create an instance with -a or -f.'
)
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'ec2',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
# Check for private_key and keyfile name for bootstrapping new instances
deploy = config.get_cloud_config_value(
'deploy', vm_, __opts__, default=True
)
win_password = config.get_cloud_config_value(
'win_password', vm_, __opts__, default=''
)
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
if deploy:
# The private_key and keyname settings are only needed for bootstrapping
# new instances when deploy is True
_validate_key_path_and_mode(key_filename)
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](
vm_['name'], vm_['profile'], 'ec2', vm_['driver']
)
vm_['key_filename'] = key_filename
# wait_for_instance requires private_key
vm_['private_key'] = key_filename
# Get SSH Gateway config early to verify the private_key,
# if used, exists or not. We don't want to deploy an instance
# and not be able to access it via the gateway.
vm_['gateway'] = get_ssh_gateway_config(vm_)
location = get_location(vm_)
vm_['location'] = location
log.info('Creating Cloud VM %s in %s', vm_['name'], location)
vm_['usernames'] = salt.utils.cloud.ssh_usernames(
vm_,
__opts__,
default_users=(
'ec2-user', # Amazon Linux, Fedora, RHEL; FreeBSD
'centos', # CentOS AMIs from AWS Marketplace
'ubuntu', # Ubuntu
'admin', # Debian GNU/Linux
'bitnami', # BitNami AMIs
'root' # Last resort, default user on RHEL 5, SUSE
)
)
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
salt.config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
if keyname(vm_) is None:
raise SaltCloudSystemExit(
'The required \'keyname\' configuration setting is missing from the '
'\'ec2\' driver.'
)
data, vm_ = request_instance(vm_, location)
# If data is a str, it's an error
if isinstance(data, six.string_types):
log.error('Error requesting instance: %s', data)
return {}
# Pull the instance ID, valid for both spot and normal instances
# Multiple instances may have been spun up, get all their IDs
vm_['instance_id_list'] = []
for instance in data:
vm_['instance_id_list'].append(instance['instanceId'])
vm_['instance_id'] = vm_['instance_id_list'].pop()
if vm_['instance_id_list']:
# Multiple instances were spun up, get one now, and queue the rest
queue_instances(vm_['instance_id_list'])
# Wait for vital information, such as IP addresses, to be available
# for the new instance
data = query_instance(vm_)
# Now that the instance is available, tag it appropriately. Should
# mitigate race conditions with tags
tags = config.get_cloud_config_value('tag',
vm_,
__opts__,
{},
search_global=False)
if not isinstance(tags, dict):
raise SaltCloudConfigError(
'\'tag\' should be a dict.'
)
for value in six.itervalues(tags):
if not isinstance(value, six.string_types):
raise SaltCloudConfigError(
'\'tag\' values must be strings. Try quoting the values. '
'e.g. "2013-09-19T20:09:46Z".'
)
tags['Name'] = vm_['name']
__utils__['cloud.fire_event'](
'event',
'setting tags',
'salt/cloud/{0}/tagging'.format(vm_['name']),
args={'tags': tags},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
salt.utils.cloud.wait_for_fun(
set_tags,
timeout=30,
name=vm_['name'],
tags=tags,
instance_id=vm_['instance_id'],
call='action',
location=location
)
# Once instance tags are set, tag the spot request if configured
if 'spot_config' in vm_ and 'tag' in vm_['spot_config']:
if not isinstance(vm_['spot_config']['tag'], dict):
raise SaltCloudConfigError(
'\'tag\' should be a dict.'
)
for value in six.itervalues(vm_['spot_config']['tag']):
if not isinstance(value, str):
raise SaltCloudConfigError(
'\'tag\' values must be strings. Try quoting the values. '
'e.g. "2013-09-19T20:09:46Z".'
)
spot_request_tags = {}
if 'spotRequestId' not in vm_:
raise SaltCloudConfigError('Failed to find spotRequestId')
sir_id = vm_['spotRequestId']
spot_request_tags['Name'] = vm_['name']
for k, v in six.iteritems(vm_['spot_config']['tag']):
spot_request_tags[k] = v
__utils__['cloud.fire_event'](
'event',
'setting tags',
'salt/cloud/spot_request_{0}/tagging'.format(sir_id),
args={'tags': spot_request_tags},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
salt.utils.cloud.wait_for_fun(
set_tags,
timeout=30,
name=vm_['name'],
tags=spot_request_tags,
instance_id=sir_id,
call='action',
location=location
)
network_interfaces = config.get_cloud_config_value(
'network_interfaces',
vm_,
__opts__,
search_global=False
)
if network_interfaces:
_update_enis(network_interfaces, data, vm_)
# At this point, the node is created and tagged, and now needs to be
# bootstrapped, once the necessary port is available.
log.info('Created node %s', vm_['name'])
instance = data[0]['instancesSet']['item']
# Wait for the necessary port to become available to bootstrap
if ssh_interface(vm_) == 'private_ips':
ip_address = instance['privateIpAddress']
log.info('Salt node data. Private_ip: %s', ip_address)
else:
ip_address = instance['ipAddress']
log.info('Salt node data. Public_ip: %s', ip_address)
vm_['ssh_host'] = ip_address
if salt.utils.cloud.get_salt_interface(vm_, __opts__) == 'private_ips':
salt_ip_address = instance['privateIpAddress']
log.info('Salt interface set to: %s', salt_ip_address)
else:
salt_ip_address = instance['ipAddress']
log.debug('Salt interface set to: %s', salt_ip_address)
vm_['salt_host'] = salt_ip_address
if deploy:
display_ssh_output = config.get_cloud_config_value(
'display_ssh_output', vm_, __opts__, default=True
)
vm_ = wait_for_instance(
vm_, data, ip_address, display_ssh_output
)
# The instance is booted and accessible, let's Salt it!
ret = instance.copy()
# Get ANY defined volumes settings, merging data, in the following order
# 1. VM config
# 2. Profile config
# 3. Global configuration
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args={'volumes': volumes},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'zone': ret['placement']['availabilityZone'],
'instance_id': ret['instanceId'],
'del_all_vols_on_destroy': vm_.get('del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
# Associate instance with a ssm document, if present
ssm_document = config.get_cloud_config_value(
'ssm_document', vm_, __opts__, None, search_global=False
)
if ssm_document:
log.debug('Associating with ssm document: %s', ssm_document)
assoc = ssm_create_association(
vm_['name'],
{'ssm_document': ssm_document},
instance_id=vm_['instance_id'],
call='action'
)
if isinstance(assoc, dict) and assoc.get('error', None):
log.error(
'Failed to associate instance %s with ssm document %s',
vm_['instance_id'], ssm_document
)
return {}
for key, value in six.iteritems(__utils__['cloud.bootstrap'](vm_, __opts__)):
ret.setdefault(key, value)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(instance)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': vm_['instance_id'],
}
if volumes:
event_data['volumes'] = volumes
if ssm_document:
event_data['ssm_document'] = ssm_document
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
# Ensure that the latest node data is returned
node = _get_node(instance_id=vm_['instance_id'])
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
ret.update(node)
# Add any block device tags specified
ex_blockdevicetags = {}
blockdevicemappings_holder = block_device_mappings(vm_)
if blockdevicemappings_holder:
for _bd in blockdevicemappings_holder:
if 'tag' in _bd:
ex_blockdevicetags[_bd['DeviceName']] = _bd['tag']
block_device_volume_id_map = {}
if ex_blockdevicetags:
for _device, _map in six.iteritems(ret['blockDeviceMapping']):
bd_items = []
if isinstance(_map, dict):
bd_items.append(_map)
else:
for mapitem in _map:
bd_items.append(mapitem)
for blockitem in bd_items:
if blockitem['deviceName'] in ex_blockdevicetags and 'Name' not in ex_blockdevicetags[blockitem['deviceName']]:
ex_blockdevicetags[blockitem['deviceName']]['Name'] = vm_['name']
if blockitem['deviceName'] in ex_blockdevicetags:
block_device_volume_id_map[blockitem[ret['rootDeviceType']]['volumeId']] = ex_blockdevicetags[blockitem['deviceName']]
if block_device_volume_id_map:
for volid, tags in six.iteritems(block_device_volume_id_map):
__utils__['cloud.fire_event'](
'event',
'setting tags',
'salt/cloud/block_volume_{0}/tagging'.format(str(volid)),
args={'tags': tags},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.wait_for_fun'](
set_tags,
timeout=30,
name=vm_['name'],
tags=tags,
resource_id=volid,
call='action',
location=location
)
return ret
def queue_instances(instances):
'''
Queue a set of instances to be provisioned later. Expects a list.
Currently this only queries node data, and then places it in the cloud
cache (if configured). If the salt-cloud-reactor is being used, these
instances will be automatically provisioned using that.
For more information about the salt-cloud-reactor, see:
https://github.com/saltstack-formulas/salt-cloud-reactor
'''
for instance_id in instances:
node = _get_node(instance_id=instance_id)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if 'instance_id' not in kwargs:
kwargs['instance_id'] = _get_node(name)['instanceId']
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
ret = []
for volume in volumes:
created = False
volume_name = '{0} on {1}'.format(volume['device'], name)
volume_dict = {
'volume_name': volume_name,
'zone': kwargs['zone']
}
if 'volume_id' in volume:
volume_dict['volume_id'] = volume['volume_id']
elif 'snapshot' in volume:
volume_dict['snapshot'] = volume['snapshot']
elif 'size' in volume:
volume_dict['size'] = volume['size']
else:
raise SaltCloudConfigError(
'Cannot create volume. Please define one of \'volume_id\', '
'\'snapshot\', or \'size\''
)
if 'tags' in volume:
volume_dict['tags'] = volume['tags']
if 'type' in volume:
volume_dict['type'] = volume['type']
if 'iops' in volume:
volume_dict['iops'] = volume['iops']
if 'encrypted' in volume:
volume_dict['encrypted'] = volume['encrypted']
if 'kmskeyid' in volume:
volume_dict['kmskeyid'] = volume['kmskeyid']
if 'volume_id' not in volume_dict:
created_volume = create_volume(volume_dict, call='function', wait_to_finish=wait_to_finish)
created = True
if 'volumeId' in created_volume:
volume_dict['volume_id'] = created_volume['volumeId']
attach = attach_volume(
name,
{'volume_id': volume_dict['volume_id'],
'device': volume['device']},
instance_id=kwargs['instance_id'],
call='action'
)
# Update the delvol parameter for this volume
delvols_on_destroy = kwargs.get('del_all_vols_on_destroy', None)
if attach and created and delvols_on_destroy is not None:
_toggle_delvol(instance_id=kwargs['instance_id'],
device=volume['device'],
value=delvols_on_destroy)
if attach:
msg = (
'{0} attached to {1} (aka {2}) as device {3}'.format(
volume_dict['volume_id'],
kwargs['instance_id'],
name,
volume['device']
)
)
log.info(msg)
ret.append(msg)
return ret
def stop(name, call=None):
'''
Stop a node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instance_id = _get_node(name)['instanceId']
__utils__['cloud.fire_event'](
'event',
'stopping instance',
'salt/cloud/{0}/stopping'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
params = {'Action': 'StopInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return result
def start(name, call=None):
'''
Start a node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
log.info('Starting node %s', name)
instance_id = _get_node(name)['instanceId']
__utils__['cloud.fire_event'](
'event',
'starting instance',
'salt/cloud/{0}/starting'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
params = {'Action': 'StartInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return result
def set_tags(name=None,
tags=None,
call=None,
location=None,
instance_id=None,
resource_id=None,
kwargs=None): # pylint: disable=W0613
'''
Set tags for a resource. Normally a VM name or instance_id is passed in,
but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a set_tags mymachine tag1=somestuff tag2='Other stuff'
salt-cloud -a set_tags resource_id=vol-3267ab32 tag=somestuff
'''
if kwargs is None:
kwargs = {}
if location is None:
location = get_location()
if instance_id is None:
if 'resource_id' in kwargs:
resource_id = kwargs['resource_id']
del kwargs['resource_id']
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
del kwargs['instance_id']
if resource_id is None:
if instance_id is None:
instance_id = _get_node(name=name, instance_id=None, location=location)['instanceId']
else:
instance_id = resource_id
# This second check is a safety, in case the above still failed to produce
# a usable ID
if instance_id is None:
return {
'Error': 'A valid instance_id or resource_id was not specified.'
}
params = {'Action': 'CreateTags',
'ResourceId.1': instance_id}
log.debug('Tags to set for %s: %s', name, tags)
if kwargs and not tags:
tags = kwargs
for idx, (tag_k, tag_v) in enumerate(six.iteritems(tags)):
params['Tag.{0}.Key'.format(idx)] = tag_k
params['Tag.{0}.Value'.format(idx)] = tag_v
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
aws.query(params,
setname='tagSet',
location=location,
provider=get_provider(),
opts=__opts__,
sigver='4')
settags = get_tags(
instance_id=instance_id, call='action', location=location
)
log.debug('Setting the tags returned: %s', settags)
failed_to_set_tags = False
for tag in settags:
if tag['key'] not in tags:
# We were not setting this tag
continue
if tag.get('value') is None and tags.get(tag['key']) == '':
# This is a correctly set tag with no value
continue
if six.text_type(tags.get(tag['key'])) != six.text_type(tag['value']):
# Not set to the proper value!?
log.debug(
'Setting the tag %s returned %s instead of %s',
tag['key'], tags.get(tag['key']), tag['value']
)
failed_to_set_tags = True
break
if failed_to_set_tags:
log.warning('Failed to set tags. Remaining attempts %s', attempts)
attempts += 1
aws.sleep_exponential_backoff(attempts)
continue
return settags
raise SaltCloudSystemExit(
'Failed to set tags on {0}!'.format(name)
)
def get_tags(name=None,
instance_id=None,
call=None,
location=None,
kwargs=None,
resource_id=None): # pylint: disable=W0613
'''
Retrieve tags for a resource. Normally a VM name or instance_id is passed
in, but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a get_tags mymachine
salt-cloud -a get_tags resource_id=vol-3267ab32
'''
if location is None:
location = get_location()
if instance_id is None:
if resource_id is None:
if name:
instance_id = _get_node(name)['instanceId']
elif 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
elif 'resource_id' in kwargs:
instance_id = kwargs['resource_id']
else:
instance_id = resource_id
params = {'Action': 'DescribeTags',
'Filter.1.Name': 'resource-id',
'Filter.1.Value': instance_id}
return aws.query(params,
setname='tagSet',
location=location,
provider=get_provider(),
opts=__opts__,
sigver='4')
def del_tags(name=None,
kwargs=None,
call=None,
instance_id=None,
resource_id=None): # pylint: disable=W0613
'''
Delete tags for a resource. Normally a VM name or instance_id is passed in,
but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a del_tags mymachine tags=mytag,
salt-cloud -a del_tags mymachine tags=tag1,tag2,tag3
salt-cloud -a del_tags resource_id=vol-3267ab32 tags=tag1,tag2,tag3
'''
if kwargs is None:
kwargs = {}
if 'tags' not in kwargs:
raise SaltCloudSystemExit(
'A tag or tags must be specified using tags=list,of,tags'
)
if not name and 'resource_id' in kwargs:
instance_id = kwargs['resource_id']
del kwargs['resource_id']
if not instance_id:
instance_id = _get_node(name)['instanceId']
params = {'Action': 'DeleteTags',
'ResourceId.1': instance_id}
for idx, tag in enumerate(kwargs['tags'].split(',')):
params['Tag.{0}.Key'.format(idx)] = tag
aws.query(params,
setname='tagSet',
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if resource_id:
return get_tags(resource_id=resource_id)
else:
return get_tags(instance_id=instance_id)
def rename(name, kwargs, call=None):
'''
Properly rename a node. Pass in the new name as "new name".
CLI Example:
.. code-block:: bash
salt-cloud -a rename mymachine newname=yourmachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The rename action must be called with -a or --action.'
)
log.info('Renaming %s to %s', name, kwargs['newname'])
set_tags(name, {'Name': kwargs['newname']}, call='action')
salt.utils.cloud.rename_key(
__opts__['pki_dir'], name, kwargs['newname']
)
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
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.'
)
node_metadata = _get_node(name)
instance_id = node_metadata['instanceId']
sir_id = node_metadata.get('spotInstanceRequestId')
protected = show_term_protect(
name=name,
instance_id=instance_id,
call='action',
quiet=True
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if protected == 'true':
raise SaltCloudSystemExit(
'This instance has been protected from being destroyed. '
'Use the following command to disable protection:\n\n'
'salt-cloud -a disable_term_protect {0}'.format(
name
)
)
ret = {}
# Default behavior is to rename EC2 VMs when destroyed
# via salt-cloud, unless explicitly set to False.
rename_on_destroy = config.get_cloud_config_value('rename_on_destroy',
get_configured_provider(),
__opts__,
search_global=False)
if rename_on_destroy is not False:
newname = '{0}-DEL{1}'.format(name, uuid.uuid4().hex)
rename(name, kwargs={'newname': newname}, call='action')
log.info(
'Machine will be identified as %s until it has been '
'cleaned up.', newname
)
ret['newname'] = newname
params = {'Action': 'TerminateInstances',
'InstanceId.1': instance_id}
location = get_location()
provider = get_provider()
result = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
log.info(result)
ret.update(result[0])
# If this instance is part of a spot instance request, we
# need to cancel it as well
if sir_id is not None:
params = {'Action': 'CancelSpotInstanceRequests',
'SpotInstanceRequestId.1': sir_id}
result = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
ret['spotInstance'] = result[0]
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name, 'instance_id': instance_id},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_del'](name)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return ret
def reboot(name, call=None):
'''
Reboot a node.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot mymachine
'''
instance_id = _get_node(name)['instanceId']
params = {'Action': 'RebootInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
setname='tagSet',
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if result == []:
log.info('Complete')
return {'Reboot': 'Complete'}
def show_image(kwargs, call=None):
'''
Show the details from EC2 concerning an AMI
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
params = {'ImageId.1': kwargs['image'],
'Action': 'DescribeImages'}
result = aws.query(params,
setname='tagSet',
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
log.info(result)
return result
def show_instance(name=None, instance_id=None, call=None, kwargs=None):
'''
Show the details from EC2 concerning an AMI.
Can be called as an action (which requires a name):
.. code-block:: bash
salt-cloud -a show_instance myinstance
...or as a function (which requires either a name or instance_id):
.. code-block:: bash
salt-cloud -f show_instance my-ec2 name=myinstance
salt-cloud -f show_instance my-ec2 instance_id=i-d34db33f
'''
if not name and call == 'action':
raise SaltCloudSystemExit(
'The show_instance action requires a name.'
)
if call == 'function':
name = kwargs.get('name', None)
instance_id = kwargs.get('instance_id', None)
if not name and not instance_id:
raise SaltCloudSystemExit(
'The show_instance function requires '
'either a name or an instance_id'
)
node = _get_node(name=name, instance_id=instance_id)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name=None, instance_id=None, location=None):
if location is None:
location = get_location()
params = {'Action': 'DescribeInstances'}
if six.text_type(name).startswith('i-') and (len(name) == 10 or len(name) == 19):
instance_id = name
if instance_id:
params['InstanceId.1'] = instance_id
else:
params['Filter.1.Name'] = 'tag:Name'
params['Filter.1.Value.1'] = name
log.trace(params)
provider = get_provider()
attempts = 0
while attempts < aws.AWS_MAX_RETRIES:
try:
instances = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
instance_info = _extract_instance_info(instances).values()
return next(iter(instance_info))
except IndexError:
attempts += 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', instance_id or name, attempts
)
aws.sleep_exponential_backoff(attempts)
return {}
def list_nodes_full(location=None, 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.'
)
return _list_nodes_full(location or get_location())
def _extract_name_tag(item):
if 'tagSet' in item and item['tagSet'] is not None:
tagset = item['tagSet']
if isinstance(tagset['item'], list):
for tag in tagset['item']:
if tag['key'] == 'Name':
return tag['value']
return item['instanceId']
return item['tagSet']['item']['value']
return item['instanceId']
def _extract_instance_info(instances):
'''
Given an instance query, return a dict of all instance data
'''
ret = {}
for instance in instances:
# items could be type dict or list (for stopped EC2 instances)
if isinstance(instance['instancesSet']['item'], list):
for item in instance['instancesSet']['item']:
name = _extract_name_tag(item)
ret[name] = item
ret[name]['name'] = name
ret[name].update(
dict(
id=item['instanceId'],
image=item['imageId'],
size=item['instanceType'],
state=item['instanceState']['name'],
private_ips=item.get('privateIpAddress', []),
public_ips=item.get('ipAddress', [])
)
)
else:
item = instance['instancesSet']['item']
name = _extract_name_tag(item)
ret[name] = item
ret[name]['name'] = name
ret[name].update(
dict(
id=item['instanceId'],
image=item['imageId'],
size=item['instanceType'],
state=item['instanceState']['name'],
private_ips=item.get('privateIpAddress', []),
public_ips=item.get('ipAddress', [])
)
)
return ret
def _list_nodes_full(location=None):
'''
Return a list of the VMs that in this location
'''
provider = __active_provider_name__ or 'ec2'
if ':' in provider:
comps = provider.split(':')
provider = comps[0]
params = {'Action': 'DescribeInstances'}
instances = aws.query(params,
location=location,
provider=provider,
opts=__opts__,
sigver='4')
if 'error' in instances:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
instances['error']['Errors']['Error']['Message']
)
)
ret = _extract_instance_info(instances)
__utils__['cloud.cache_node_list'](ret, provider, __opts__)
return ret
def list_nodes_min(location=None, call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
ret = {}
params = {'Action': 'DescribeInstances'}
instances = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if 'error' in instances:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
instances['error']['Errors']['Error']['Message']
)
)
for instance in instances:
if isinstance(instance['instancesSet']['item'], list):
items = instance['instancesSet']['item']
else:
items = [instance['instancesSet']['item']]
for item in items:
state = item['instanceState']['name']
name = _extract_name_tag(item)
id = item['instanceId']
ret[name] = {'state': state, 'id': id}
return ret
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(get_location())
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]['id'],
'image': nodes[node]['image'],
'name': nodes[node]['name'],
'size': nodes[node]['size'],
'state': nodes[node]['state'],
'private_ips': nodes[node]['private_ips'],
'public_ips': nodes[node]['public_ips'],
}
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(get_location()), __opts__['query.selection'], call,
)
def show_term_protect(name=None, instance_id=None, call=None, quiet=False):
'''
Show the details from EC2 concerning an instance's termination protection state
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_term_protect action must be called with -a or --action.'
)
if not instance_id:
instance_id = _get_node(name)['instanceId']
params = {'Action': 'DescribeInstanceAttribute',
'InstanceId': instance_id,
'Attribute': 'disableApiTermination'}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
disable_protect = False
for item in result:
if 'value' in item:
disable_protect = item['value']
break
log.log(
logging.DEBUG if quiet is True else logging.INFO,
'Termination Protection is %s for %s',
disable_protect == 'true' and 'enabled' or 'disabled', name
)
return disable_protect
def show_detailed_monitoring(name=None, instance_id=None, call=None, quiet=False):
'''
Show the details from EC2 regarding cloudwatch detailed monitoring.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_detailed_monitoring action must be called with -a or --action.'
)
location = get_location()
if six.text_type(name).startswith('i-') and (len(name) == 10 or len(name) == 19):
instance_id = name
if not name and not instance_id:
raise SaltCloudSystemExit(
'The show_detailed_monitoring action must be provided with a name or instance\
ID'
)
matched = _get_node(name=name, instance_id=instance_id, location=location)
log.log(
logging.DEBUG if quiet is True else logging.INFO,
'Detailed Monitoring is %s for %s', matched['monitoring'], name
)
return matched['monitoring']
def _toggle_term_protect(name, value):
'''
Enable or Disable termination protection on a node
'''
instance_id = _get_node(name)['instanceId']
params = {'Action': 'ModifyInstanceAttribute',
'InstanceId': instance_id,
'DisableApiTermination.Value': value}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
return show_term_protect(name=name, instance_id=instance_id, call='action')
def enable_term_protect(name, call=None):
'''
Enable termination protection on a node
CLI Example:
.. code-block:: bash
salt-cloud -a enable_term_protect mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
return _toggle_term_protect(name, 'true')
def disable_term_protect(name, call=None):
'''
Disable termination protection on a node
CLI Example:
.. code-block:: bash
salt-cloud -a disable_term_protect mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
return _toggle_term_protect(name, 'false')
def disable_detailed_monitoring(name, call=None):
'''
Enable/disable detailed monitoring on a node
CLI Example:
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
instance_id = _get_node(name)['instanceId']
params = {'Action': 'UnmonitorInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
return show_detailed_monitoring(name=name, instance_id=instance_id, call='action')
def enable_detailed_monitoring(name, call=None):
'''
Enable/disable detailed monitoring on a node
CLI Example:
'''
if call != 'action':
raise SaltCloudSystemExit(
'The enable_term_protect action must be called with '
'-a or --action.'
)
instance_id = _get_node(name)['instanceId']
params = {'Action': 'MonitorInstances',
'InstanceId.1': instance_id}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
return_root=True,
opts=__opts__,
sigver='4')
return show_detailed_monitoring(name=name, instance_id=instance_id, call='action')
def show_delvol_on_destroy(name, kwargs=None, call=None):
'''
Do not delete all/specified EBS volumes upon instance termination
CLI Example:
.. code-block:: bash
salt-cloud -a show_delvol_on_destroy mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_delvol_on_destroy action must be called '
'with -a or --action.'
)
if not kwargs:
kwargs = {}
instance_id = kwargs.get('instance_id', None)
device = kwargs.get('device', None)
volume_id = kwargs.get('volume_id', None)
if instance_id is None:
instance_id = _get_node(name)['instanceId']
params = {'Action': 'DescribeInstances',
'InstanceId.1': instance_id}
data = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
blockmap = data[0]['instancesSet']['item']['blockDeviceMapping']
if not isinstance(blockmap['item'], list):
blockmap['item'] = [blockmap['item']]
items = []
for idx, item in enumerate(blockmap['item']):
device_name = item['deviceName']
if device is not None and device != device_name:
continue
if volume_id is not None and volume_id != item['ebs']['volumeId']:
continue
info = {
'device_name': device_name,
'volume_id': item['ebs']['volumeId'],
'deleteOnTermination': item['ebs']['deleteOnTermination']
}
items.append(info)
return items
def keepvol_on_destroy(name, kwargs=None, call=None):
'''
Do not delete all/specified EBS volumes upon instance termination
CLI Example:
.. code-block:: bash
salt-cloud -a keepvol_on_destroy mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The keepvol_on_destroy action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
device = kwargs.get('device', None)
volume_id = kwargs.get('volume_id', None)
return _toggle_delvol(name=name, device=device,
volume_id=volume_id, value='false')
def delvol_on_destroy(name, kwargs=None, call=None):
'''
Delete all/specified EBS volumes upon instance termination
CLI Example:
.. code-block:: bash
salt-cloud -a delvol_on_destroy mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The delvol_on_destroy action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
device = kwargs.get('device', None)
volume_id = kwargs.get('volume_id', None)
return _toggle_delvol(name=name, device=device,
volume_id=volume_id, value='true')
def _toggle_delvol(name=None, instance_id=None, device=None, volume_id=None,
value=None, requesturl=None):
if not instance_id:
instance_id = _get_node(name)['instanceId']
if requesturl:
data = aws.query(requesturl=requesturl,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
else:
params = {'Action': 'DescribeInstances',
'InstanceId.1': instance_id}
data, requesturl = aws.query(params, # pylint: disable=unbalanced-tuple-unpacking
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
blockmap = data[0]['instancesSet']['item']['blockDeviceMapping']
params = {'Action': 'ModifyInstanceAttribute',
'InstanceId': instance_id}
if not isinstance(blockmap['item'], list):
blockmap['item'] = [blockmap['item']]
for idx, item in enumerate(blockmap['item']):
device_name = item['deviceName']
if device is not None and device != device_name:
continue
if volume_id is not None and volume_id != item['ebs']['volumeId']:
continue
params['BlockDeviceMapping.{0}.DeviceName'.format(idx)] = device_name
params['BlockDeviceMapping.{0}.Ebs.DeleteOnTermination'.format(idx)] = value
aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
kwargs = {'instance_id': instance_id,
'device': device,
'volume_id': volume_id}
return show_delvol_on_destroy(name, kwargs, call='action')
def register_image(kwargs=None, call=None):
'''
Create an ami from a snapshot
CLI Example:
.. code-block:: bash
salt-cloud -f register_image my-ec2-config ami_name=my_ami description="my description"
root_device_name=/dev/xvda snapshot_id=snap-xxxxxxxx
'''
if call != 'function':
log.error(
'The create_volume function must be called with -f or --function.'
)
return False
if 'ami_name' not in kwargs:
log.error('ami_name must be specified to register an image.')
return False
block_device_mapping = kwargs.get('block_device_mapping', None)
if not block_device_mapping:
if 'snapshot_id' not in kwargs:
log.error('snapshot_id or block_device_mapping must be specified to register an image.')
return False
if 'root_device_name' not in kwargs:
log.error('root_device_name or block_device_mapping must be specified to register an image.')
return False
block_device_mapping = [{
'DeviceName': kwargs['root_device_name'],
'Ebs': {
'VolumeType': kwargs.get('volume_type', 'gp2'),
'SnapshotId': kwargs['snapshot_id'],
}
}]
if not isinstance(block_device_mapping, list):
block_device_mapping = [block_device_mapping]
params = {'Action': 'RegisterImage',
'Name': kwargs['ami_name']}
params.update(_param_from_config('BlockDeviceMapping', block_device_mapping))
if 'root_device_name' in kwargs:
params['RootDeviceName'] = kwargs['root_device_name']
if 'description' in kwargs:
params['Description'] = kwargs['description']
if 'virtualization_type' in kwargs:
params['VirtualizationType'] = kwargs['virtualization_type']
if 'architecture' in kwargs:
params['Architecture'] = kwargs['architecture']
log.debug(params)
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
r_data = {}
for d in data[0]:
for k, v in d.items():
r_data[k] = v
return r_data
def volume_create(**kwargs):
'''
Wrapper around create_volume.
Here just to ensure the compatibility with the cloud module.
'''
return create_volume(kwargs, 'function')
def create_volume(kwargs=None, call=None, wait_to_finish=False):
'''
Create a volume.
zone
The availability zone used to create the volume. Required. String.
size
The size of the volume, in GiBs. Defaults to ``10``. Integer.
snapshot
The snapshot-id from which to create the volume. Integer.
type
The volume type. This can be gp2 for General Purpose SSD, io1 for Provisioned
IOPS SSD, st1 for Throughput Optimized HDD, sc1 for Cold HDD, or standard for
Magnetic volumes. String.
iops
The number of I/O operations per second (IOPS) to provision for the volume,
with a maximum ratio of 50 IOPS/GiB. Only valid for Provisioned IOPS SSD
volumes. Integer.
This option will only be set if ``type`` is also specified as ``io1``.
encrypted
Specifies whether the volume will be encrypted. Boolean.
If ``snapshot`` is also given in the list of kwargs, then this value is ignored
since volumes that are created from encrypted snapshots are also automatically
encrypted.
tags
The tags to apply to the volume during creation. Dictionary.
call
The ``create_volume`` function must be called with ``-f`` or ``--function``.
String.
wait_to_finish
Whether or not to wait for the volume to be available. Boolean. Defaults to
``False``.
CLI Examples:
.. code-block:: bash
salt-cloud -f create_volume my-ec2-config zone=us-east-1b
salt-cloud -f create_volume my-ec2-config zone=us-east-1b tags='{"tag1": "val1", "tag2", "val2"}'
'''
if call != 'function':
log.error(
'The create_volume function must be called with -f or --function.'
)
return False
if 'zone' not in kwargs:
log.error('An availability zone must be specified to create a volume.')
return False
if 'size' not in kwargs and 'snapshot' not in kwargs:
# This number represents GiB
kwargs['size'] = '10'
params = {'Action': 'CreateVolume',
'AvailabilityZone': kwargs['zone']}
if 'size' in kwargs:
params['Size'] = kwargs['size']
if 'snapshot' in kwargs:
params['SnapshotId'] = kwargs['snapshot']
if 'type' in kwargs:
params['VolumeType'] = kwargs['type']
if 'iops' in kwargs and kwargs.get('type', 'standard') == 'io1':
params['Iops'] = kwargs['iops']
# You can't set `encrypted` if you pass a snapshot
if 'encrypted' in kwargs and 'snapshot' not in kwargs:
params['Encrypted'] = kwargs['encrypted']
if 'kmskeyid' in kwargs:
params['KmsKeyId'] = kwargs['kmskeyid']
if 'kmskeyid' in kwargs and 'encrypted' not in kwargs:
log.error(
'If a KMS Key ID is specified, encryption must be enabled'
)
return False
log.debug(params)
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
r_data = {}
for d in data[0]:
for k, v in six.iteritems(d):
r_data[k] = v
volume_id = r_data['volumeId']
# Allow tags to be set upon creation
if 'tags' in kwargs:
if isinstance(kwargs['tags'], six.string_types):
tags = salt.utils.yaml.safe_load(kwargs['tags'])
else:
tags = kwargs['tags']
if isinstance(tags, dict):
new_tags = set_tags(tags=tags,
resource_id=volume_id,
call='action',
location=get_location())
r_data['tags'] = new_tags
# Waits till volume is available
if wait_to_finish:
salt.utils.cloud.run_func_until_ret_arg(fun=describe_volumes,
kwargs={'volume_id': volume_id},
fun_call=call,
argument_being_watched='status',
required_argument_response='available')
return r_data
def __attach_vol_to_instance(params, kws, instance_id):
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
if data[0]:
log.warning(
'Error attaching volume %s to instance %s. Retrying!',
kws['volume_id'], instance_id
)
return False
return data
def attach_volume(name=None, kwargs=None, instance_id=None, call=None):
'''
Attach a volume to an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The attach_volume action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
if name and not instance_id:
instance_id = _get_node(name)['instanceId']
if not name and not instance_id:
log.error('Either a name or an instance_id is required.')
return False
if 'volume_id' not in kwargs:
log.error('A volume_id is required.')
return False
if 'device' not in kwargs:
log.error('A device is required (ex. /dev/sdb1).')
return False
params = {'Action': 'AttachVolume',
'VolumeId': kwargs['volume_id'],
'InstanceId': instance_id,
'Device': kwargs['device']}
log.debug(params)
vm_ = get_configured_provider()
data = salt.utils.cloud.wait_for_ip(
__attach_vol_to_instance,
update_args=(params, kwargs, instance_id),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value(
'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
return data
def show_volume(kwargs=None, call=None):
'''
Wrapper around describe_volumes.
Here just to keep functionality.
Might be depreciated later.
'''
if not kwargs:
kwargs = {}
return describe_volumes(kwargs, call)
def detach_volume(name=None, kwargs=None, instance_id=None, call=None):
'''
Detach a volume from an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The detach_volume action must be called with -a or --action.'
)
if not kwargs:
kwargs = {}
if 'volume_id' not in kwargs:
log.error('A volume_id is required.')
return False
params = {'Action': 'DetachVolume',
'VolumeId': kwargs['volume_id']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def delete_volume(name=None, kwargs=None, instance_id=None, call=None):
'''
Delete a volume
'''
if not kwargs:
kwargs = {}
if 'volume_id' not in kwargs:
log.error('A volume_id is required.')
return False
params = {'Action': 'DeleteVolume',
'VolumeId': kwargs['volume_id']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def volume_list(**kwargs):
'''
Wrapper around describe_volumes.
Here just to ensure the compatibility with the cloud module.
'''
return describe_volumes(kwargs, 'function')
def describe_volumes(kwargs=None, call=None):
'''
Describe a volume (or volumes)
volume_id
One or more volume IDs. Multiple IDs must be separated by ",".
TODO: Add all of the filters.
'''
if call != 'function':
log.error(
'The describe_volumes function must be called with -f '
'or --function.'
)
return False
if not kwargs:
kwargs = {}
params = {'Action': 'DescribeVolumes'}
if 'volume_id' in kwargs:
volume_id = kwargs['volume_id'].split(',')
for volume_index, volume_id in enumerate(volume_id):
params['VolumeId.{0}'.format(volume_index)] = volume_id
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def create_keypair(kwargs=None, call=None):
'''
Create an SSH keypair
'''
if call != 'function':
log.error(
'The create_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
params = {'Action': 'CreateKeyPair',
'KeyName': kwargs['keyname']}
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
keys = [x for x in data[0] if 'requestId' not in x]
return (keys, data[1])
def import_keypair(kwargs=None, call=None):
'''
Import an SSH public key.
.. versionadded:: 2015.8.3
'''
if call != 'function':
log.error(
'The import_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
if 'file' not in kwargs:
log.error('A public key file is required.')
return False
params = {'Action': 'ImportKeyPair',
'KeyName': kwargs['keyname']}
public_key_file = kwargs['file']
if os.path.exists(public_key_file):
with salt.utils.files.fopen(public_key_file, 'r') as fh_:
public_key = salt.utils.stringutils.to_unicode(fh_.read())
if public_key is not None:
params['PublicKeyMaterial'] = base64.b64encode(public_key)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
params = {'Action': 'DescribeKeyPairs',
'KeyName.1': kwargs['keyname']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def delete_keypair(kwargs=None, call=None):
'''
Delete an SSH keypair
'''
if call != 'function':
log.error(
'The delete_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
params = {'Action': 'DeleteKeyPair',
'KeyName': kwargs['keyname']}
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def create_snapshot(kwargs=None, call=None, wait_to_finish=False):
'''
Create a snapshot.
volume_id
The ID of the Volume from which to create a snapshot.
description
The optional description of the snapshot.
CLI Exampe:
.. code-block:: bash
salt-cloud -f create_snapshot my-ec2-config volume_id=vol-351d8826
salt-cloud -f create_snapshot my-ec2-config volume_id=vol-351d8826 \\
description="My Snapshot Description"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_snapshot function must be called with -f '
'or --function.'
)
if kwargs is None:
kwargs = {}
volume_id = kwargs.get('volume_id', None)
description = kwargs.get('description', '')
if volume_id is None:
raise SaltCloudSystemExit(
'A volume_id must be specified to create a snapshot.'
)
params = {'Action': 'CreateSnapshot',
'VolumeId': volume_id,
'Description': description}
log.debug(params)
data = aws.query(params,
return_url=True,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')[0]
r_data = {}
for d in data:
for k, v in six.iteritems(d):
r_data[k] = v
if 'snapshotId' in r_data:
snapshot_id = r_data['snapshotId']
# Waits till volume is available
if wait_to_finish:
salt.utils.cloud.run_func_until_ret_arg(fun=describe_snapshots,
kwargs={'snapshot_id': snapshot_id},
fun_call=call,
argument_being_watched='status',
required_argument_response='completed')
return r_data
def delete_snapshot(kwargs=None, call=None):
'''
Delete a snapshot
'''
if call != 'function':
log.error(
'The delete_snapshot function must be called with -f '
'or --function.'
)
return False
if 'snapshot_id' not in kwargs:
log.error('A snapshot_id must be specified to delete a snapshot.')
return False
params = {'Action': 'DeleteSnapshot'}
if 'snapshot_id' in kwargs:
params['SnapshotId'] = kwargs['snapshot_id']
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def copy_snapshot(kwargs=None, call=None):
'''
Copy a snapshot
'''
if call != 'function':
log.error(
'The copy_snapshot function must be called with -f or --function.'
)
return False
if 'source_region' not in kwargs:
log.error('A source_region must be specified to copy a snapshot.')
return False
if 'source_snapshot_id' not in kwargs:
log.error('A source_snapshot_id must be specified to copy a snapshot.')
return False
if 'description' not in kwargs:
kwargs['description'] = ''
params = {'Action': 'CopySnapshot'}
if 'source_region' in kwargs:
params['SourceRegion'] = kwargs['source_region']
if 'source_snapshot_id' in kwargs:
params['SourceSnapshotId'] = kwargs['source_snapshot_id']
if 'description' in kwargs:
params['Description'] = kwargs['description']
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def describe_snapshots(kwargs=None, call=None):
'''
Describe a snapshot (or snapshots)
snapshot_id
One or more snapshot IDs. Multiple IDs must be separated by ",".
owner
Return the snapshots owned by the specified owner. Valid values
include: self, amazon, <AWS Account ID>. Multiple values must be
separated by ",".
restorable_by
One or more AWS accounts IDs that can create volumes from the snapshot.
Multiple aws account IDs must be separated by ",".
TODO: Add all of the filters.
'''
if call != 'function':
log.error(
'The describe_snapshot function must be called with -f '
'or --function.'
)
return False
params = {'Action': 'DescribeSnapshots'}
# The AWS correct way is to use non-plurals like snapshot_id INSTEAD of snapshot_ids.
if 'snapshot_ids' in kwargs:
kwargs['snapshot_id'] = kwargs['snapshot_ids']
if 'snapshot_id' in kwargs:
snapshot_ids = kwargs['snapshot_id'].split(',')
for snapshot_index, snapshot_id in enumerate(snapshot_ids):
params['SnapshotId.{0}'.format(snapshot_index)] = snapshot_id
if 'owner' in kwargs:
owners = kwargs['owner'].split(',')
for owner_index, owner in enumerate(owners):
params['Owner.{0}'.format(owner_index)] = owner
if 'restorable_by' in kwargs:
restorable_bys = kwargs['restorable_by'].split(',')
for restorable_by_index, restorable_by in enumerate(restorable_bys):
params[
'RestorableBy.{0}'.format(restorable_by_index)
] = restorable_by
log.debug(params)
data = aws.query(params,
return_url=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
return data
def get_console_output(
name=None,
location=None,
instance_id=None,
call=None,
kwargs=None,
):
'''
Show the console output from the instance.
By default, returns decoded data, not the Base64-encoded data that is
actually returned from the EC2 API.
'''
if call != 'action':
raise SaltCloudSystemExit(
'The get_console_output action must be called with '
'-a or --action.'
)
if location is None:
location = get_location()
if not instance_id:
instance_id = _get_node(name)['instanceId']
if kwargs is None:
kwargs = {}
if instance_id is None:
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
del kwargs['instance_id']
params = {'Action': 'GetConsoleOutput',
'InstanceId': instance_id}
ret = {}
data = aws.query(params,
return_root=True,
location=location,
provider=get_provider(),
opts=__opts__,
sigver='4')
for item in data:
if next(six.iterkeys(item)) == 'output':
ret['output_decoded'] = binascii.a2b_base64(next(six.itervalues(item)))
else:
ret[next(six.iterkeys(item))] = next(six.itervalues(item))
return ret
def get_password_data(
name=None,
kwargs=None,
instance_id=None,
call=None,
):
'''
Return password data for a Windows instance.
By default only the encrypted password data will be returned. However, if a
key_file is passed in, then a decrypted password will also be returned.
Note that the key_file references the private key that was used to generate
the keypair associated with this instance. This private key will _not_ be
transmitted to Amazon; it is only used internally inside of Salt Cloud to
decrypt data _after_ it has been received from Amazon.
CLI Examples:
.. code-block:: bash
salt-cloud -a get_password_data mymachine
salt-cloud -a get_password_data mymachine key_file=/root/ec2key.pem
Note: PKCS1_v1_5 was added in PyCrypto 2.5
'''
if call != 'action':
raise SaltCloudSystemExit(
'The get_password_data action must be called with '
'-a or --action.'
)
if not instance_id:
instance_id = _get_node(name)['instanceId']
if kwargs is None:
kwargs = {}
if instance_id is None:
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
del kwargs['instance_id']
params = {'Action': 'GetPasswordData',
'InstanceId': instance_id}
ret = {}
data = aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
for item in data:
ret[next(six.iterkeys(item))] = next(six.itervalues(item))
if not HAS_M2 and not HAS_PYCRYPTO:
return ret
if 'key' not in kwargs:
if 'key_file' in kwargs:
with salt.utils.files.fopen(kwargs['key_file'], 'r') as kf_:
kwargs['key'] = salt.utils.stringutils.to_unicode(kf_.read())
if 'key' in kwargs:
pwdata = ret.get('passwordData', None)
if pwdata is not None:
rsa_key = kwargs['key']
pwdata = base64.b64decode(pwdata)
if HAS_M2:
key = RSA.load_key_string(rsa_key.encode('ascii'))
password = key.private_decrypt(pwdata, RSA.pkcs1_padding)
else:
dsize = Crypto.Hash.SHA.digest_size
sentinel = Crypto.Random.new().read(15 + dsize)
key_obj = Crypto.PublicKey.RSA.importKey(rsa_key)
key_obj = PKCS1_v1_5.new(key_obj)
password = key_obj.decrypt(pwdata, sentinel)
ret['password'] = salt.utils.stringutils.to_unicode(password)
return ret
def update_pricing(kwargs=None, call=None):
'''
Download most recent pricing information from AWS and convert to a local
JSON file.
CLI Examples:
.. code-block:: bash
salt-cloud -f update_pricing my-ec2-config
salt-cloud -f update_pricing my-ec2-config type=linux
.. versionadded:: 2015.8.0
'''
sources = {
'linux': 'https://a0.awsstatic.com/pricing/1/ec2/linux-od.min.js',
'rhel': 'https://a0.awsstatic.com/pricing/1/ec2/rhel-od.min.js',
'sles': 'https://a0.awsstatic.com/pricing/1/ec2/sles-od.min.js',
'mswin': 'https://a0.awsstatic.com/pricing/1/ec2/mswin-od.min.js',
'mswinsql': 'https://a0.awsstatic.com/pricing/1/ec2/mswinSQL-od.min.js',
'mswinsqlweb': 'https://a0.awsstatic.com/pricing/1/ec2/mswinSQLWeb-od.min.js',
}
if kwargs is None:
kwargs = {}
if 'type' not in kwargs:
for source in sources:
_parse_pricing(sources[source], source)
else:
_parse_pricing(sources[kwargs['type']], kwargs['type'])
def _parse_pricing(url, name):
'''
Download and parse an individual pricing file from AWS
.. versionadded:: 2015.8.0
'''
price_js = http.query(url, text=True)
items = []
current_item = ''
price_js = re.sub(JS_COMMENT_RE, '', price_js['text'])
price_js = price_js.strip().rstrip(');').lstrip('callback(')
for keyword in (
'vers',
'config',
'rate',
'valueColumns',
'currencies',
'instanceTypes',
'type',
'ECU',
'storageGB',
'name',
'vCPU',
'memoryGiB',
'storageGiB',
'USD',
):
price_js = price_js.replace(keyword, '"{0}"'.format(keyword))
for keyword in ('region', 'price', 'size'):
price_js = price_js.replace(keyword, '"{0}"'.format(keyword))
price_js = price_js.replace('"{0}"s'.format(keyword), '"{0}s"'.format(keyword))
price_js = price_js.replace('""', '"')
# Turn the data into something that's easier/faster to process
regions = {}
price_json = salt.utils.json.loads(price_js)
for region in price_json['config']['regions']:
sizes = {}
for itype in region['instanceTypes']:
for size in itype['sizes']:
sizes[size['size']] = size
regions[region['region']] = sizes
outfile = os.path.join(
__opts__['cachedir'], 'ec2-pricing-{0}.p'.format(name)
)
with salt.utils.files.fopen(outfile, 'w') as fho:
salt.utils.msgpack.dump(regions, fho)
return True
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-ec2-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: 2015.8.0
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to ec2
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'ec2':
return {'Error': 'The requested profile does not belong to EC2'}
image_id = profile.get('image', None)
image_dict = show_image({'image': image_id}, 'function')
image_info = image_dict[0]
# Find out what platform it is
if image_info.get('imageOwnerAlias', '') == 'amazon':
if image_info.get('platform', '') == 'windows':
image_description = image_info.get('description', '')
if 'sql' in image_description.lower():
if 'web' in image_description.lower():
name = 'mswinsqlweb'
else:
name = 'mswinsql'
else:
name = 'mswin'
elif image_info.get('imageLocation', '').strip().startswith('amazon/suse'):
name = 'sles'
else:
name = 'linux'
elif image_info.get('imageOwnerId', '') == '309956199498':
name = 'rhel'
else:
name = 'linux'
pricefile = os.path.join(
__opts__['cachedir'], 'ec2-pricing-{0}.p'.format(name)
)
if not os.path.isfile(pricefile):
update_pricing({'type': name}, 'function')
with salt.utils.files.fopen(pricefile, 'r') as fhi:
ec2_price = salt.utils.stringutils.to_unicode(
salt.utils.msgpack.load(fhi))
region = get_location(profile)
size = profile.get('size', None)
if size is None:
return {'Error': 'The requested profile does not contain a size'}
try:
raw = ec2_price[region][size]
except KeyError:
return {'Error': 'The size ({0}) in the requested profile does not have '
'a price associated with it for the {1} region'.format(size, region)}
ret = {}
if kwargs.get('raw', False):
ret['_raw'] = raw
ret['per_hour'] = 0
for col in raw.get('valueColumns', []):
ret['per_hour'] += decimal.Decimal(col['prices'].get('USD', 0))
ret['per_hour'] = decimal.Decimal(ret['per_hour'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = ret['per_day'] * 30
ret['per_year'] = ret['per_week'] * 52
return {profile['profile']: ret}
def ssm_create_association(name=None, kwargs=None, instance_id=None, call=None):
'''
Associates the specified SSM document with the specified instance
http://docs.aws.amazon.com/ssm/latest/APIReference/API_CreateAssociation.html
CLI Examples:
.. code-block:: bash
salt-cloud -a ssm_create_association ec2-instance-name ssm_document=ssm-document-name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The ssm_create_association action must be called with '
'-a or --action.'
)
if not kwargs:
kwargs = {}
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
if name and not instance_id:
instance_id = _get_node(name)['instanceId']
if not name and not instance_id:
log.error('Either a name or an instance_id is required.')
return False
if 'ssm_document' not in kwargs:
log.error('A ssm_document is required.')
return False
params = {'Action': 'CreateAssociation',
'InstanceId': instance_id,
'Name': kwargs['ssm_document']}
result = aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
product='ssm',
opts=__opts__,
sigver='4')
log.info(result)
return result
def ssm_describe_association(name=None, kwargs=None, instance_id=None, call=None):
'''
Describes the associations for the specified SSM document or instance.
http://docs.aws.amazon.com/ssm/latest/APIReference/API_DescribeAssociation.html
CLI Examples:
.. code-block:: bash
salt-cloud -a ssm_describe_association ec2-instance-name ssm_document=ssm-document-name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The ssm_describe_association action must be called with '
'-a or --action.'
)
if not kwargs:
kwargs = {}
if 'instance_id' in kwargs:
instance_id = kwargs['instance_id']
if name and not instance_id:
instance_id = _get_node(name)['instanceId']
if not name and not instance_id:
log.error('Either a name or an instance_id is required.')
return False
if 'ssm_document' not in kwargs:
log.error('A ssm_document is required.')
return False
params = {'Action': 'DescribeAssociation',
'InstanceId': instance_id,
'Name': kwargs['ssm_document']}
result = aws.query(params,
return_root=True,
location=get_location(),
provider=get_provider(),
product='ssm',
opts=__opts__,
sigver='4')
log.info(result)
return result
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.