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
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/modules/x509.py
|
_make_regex
|
python
|
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
|
Dynamically generate a regex to match pem_type
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L418-L429
| null |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
get_pem_entry
|
python
|
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
|
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L432-L509
|
[
"def _text_or_file(input_):\n '''\n Determines if input is a path to a file, or a string with the\n content to be parsed.\n '''\n if _isfile(input_):\n with salt.utils.files.fopen(input_) as fp_:\n out = salt.utils.stringutils.to_str(fp_.read())\n else:\n out = salt.utils.stringutils.to_str(input_)\n\n return out\n",
"def _make_regex(pem_type):\n '''\n Dynamically generate a regex to match pem_type\n '''\n return re.compile(\n r\"\\s*(?P<pem_header>-----BEGIN {0}-----)\\s+\"\n r\"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\\s*)?\"\n r\"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\\-]+,[0-9A-F]{{16}}|[0-9A-Z\\-]+,[0-9A-F]{{32}}))\\s*)?\"\n r\"(?P<pem_body>.+?)\\s+(?P<pem_footer>\"\n r\"-----END {0}-----)\\s*\".format(pem_type),\n re.DOTALL\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
get_pem_entries
|
python
|
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
|
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L512-L534
|
[
"def get_pem_entry(text, pem_type=None):\n '''\n Returns a properly formatted PEM string from the input text fixing\n any whitespace or line-break issues\n\n text:\n Text containing the X509 PEM entry to be returned or path to\n a file containing the text.\n\n pem_type:\n If specified, this function will only return a pem of a certain type,\n for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_pem_entry \"-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST\"\n '''\n text = _text_or_file(text)\n # Replace encoded newlines\n text = text.replace('\\\\n', '\\n')\n\n _match = None\n\n if len(text.splitlines()) == 1 and text.startswith(\n '-----') and text.endswith('-----'):\n # mine.get returns the PEM on a single line, we fix this\n pem_fixed = []\n pem_temp = text\n while pem_temp:\n if pem_temp.startswith('-----'):\n # Grab ----(.*)---- blocks\n pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])\n pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]\n else:\n # grab base64 chunks\n if pem_temp[:64].count('-') == 0:\n pem_fixed.append(pem_temp[:64])\n pem_temp = pem_temp[64:]\n else:\n pem_fixed.append(pem_temp[:pem_temp.index('-')])\n pem_temp = pem_temp[pem_temp.index('-'):]\n text = \"\\n\".join(pem_fixed)\n\n _dregex = _make_regex('[0-9A-Z ]+')\n errmsg = 'PEM text not valid:\\n{0}'.format(text)\n if pem_type:\n _dregex = _make_regex(pem_type)\n errmsg = ('PEM does not contain a single entry of type {0}:\\n'\n '{1}'.format(pem_type, text))\n\n for _match in _dregex.finditer(text):\n if _match:\n break\n if not _match:\n raise salt.exceptions.SaltInvocationError(errmsg)\n _match_dict = _match.groupdict()\n pem_header = _match_dict['pem_header']\n proc_type = _match_dict['proc_type']\n dek_info = _match_dict['dek_info']\n pem_footer = _match_dict['pem_footer']\n pem_body = _match_dict['pem_body']\n\n # Remove all whitespace from body\n pem_body = ''.join(pem_body.split())\n\n # Generate correctly formatted pem\n ret = pem_header + '\\n'\n if proc_type:\n ret += proc_type + '\\n'\n if dek_info:\n ret += dek_info + '\\n' + '\\n'\n for i in range(0, len(pem_body), 64):\n ret += pem_body[i:i + 64] + '\\n'\n ret += pem_footer + '\\n'\n\n return salt.utils.stringutils.to_bytes(ret, encoding='ascii')\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
read_certificate
|
python
|
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
|
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L537-L588
|
[
"def _parse_subject(subject):\n '''\n Returns a dict containing all values in an X509 Subject\n '''\n ret = {}\n nids = []\n for nid_name, nid_num in six.iteritems(subject.nid):\n if nid_num in nids:\n continue\n try:\n val = getattr(subject, nid_name)\n if val:\n ret[nid_name] = val\n nids.append(nid_num)\n except TypeError as err:\n log.debug(\"Missing attribute '%s'. Error: %s\", nid_name, err)\n\n return ret\n",
"def _pretty_hex(hex_str):\n '''\n Nicely formats hex strings\n '''\n if len(hex_str) % 2 != 0:\n hex_str = '0' + hex_str\n return ':'.join(\n [hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()\n",
"def _dec2hex(decval):\n '''\n Converts decimal values to nicely formatted hex strings\n '''\n return _pretty_hex('{0:X}'.format(decval))\n",
"def _get_certificate_obj(cert):\n '''\n Returns a certificate object based on PEM text.\n '''\n if isinstance(cert, M2Crypto.X509.X509):\n return cert\n\n text = _text_or_file(cert)\n text = get_pem_entry(text, pem_type='CERTIFICATE')\n return M2Crypto.X509.load_cert_string(text)\n",
"def get_public_key(key, passphrase=None, asObj=False):\n '''\n Returns a string containing the public key in PEM format.\n\n key:\n A path or PEM encoded string containing a CSR, Certificate or\n Private Key from which a public key can be retrieved.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_public_key /etc/pki/mycert.cer\n '''\n\n if isinstance(key, M2Crypto.X509.X509):\n rsa = key.get_pubkey().get_rsa()\n text = b''\n else:\n text = _text_or_file(key)\n text = get_pem_entry(text)\n\n if text.startswith(b'-----BEGIN PUBLIC KEY-----'):\n if not asObj:\n return text\n bio = M2Crypto.BIO.MemoryBuffer()\n bio.write(text)\n rsa = M2Crypto.RSA.load_pub_key_bio(bio)\n\n bio = M2Crypto.BIO.MemoryBuffer()\n if text.startswith(b'-----BEGIN CERTIFICATE-----'):\n cert = M2Crypto.X509.load_cert_string(text)\n rsa = cert.get_pubkey().get_rsa()\n if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):\n csr = M2Crypto.X509.load_request_string(text)\n rsa = csr.get_pubkey().get_rsa()\n if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or\n text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):\n rsa = M2Crypto.RSA.load_key_string(\n text, callback=_passphrase_callback(passphrase))\n\n if asObj:\n evppubkey = M2Crypto.EVP.PKey()\n evppubkey.assign_rsa(rsa)\n return evppubkey\n\n rsa.save_pub_key_bio(bio)\n return bio.read_all()\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
read_certificates
|
python
|
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
|
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L591-L613
|
[
"def read_certificate(certificate):\n '''\n Returns a dict containing details of a certificate. Input can be a PEM\n string or file path.\n\n certificate:\n The certificate to be read. Can be a path to a certificate file, or\n a string containing the PEM formatted text of the certificate.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.read_certificate /etc/pki/mycert.crt\n '''\n cert = _get_certificate_obj(certificate)\n\n ret = {\n # X509 Version 3 has a value of 2 in the field.\n # Version 2 has a value of 1.\n # https://tools.ietf.org/html/rfc5280#section-4.1.2.1\n 'Version': cert.get_version() + 1,\n # Get size returns in bytes. The world thinks of key sizes in bits.\n 'Key Size': cert.get_pubkey().size() * 8,\n 'Serial Number': _dec2hex(cert.get_serial_number()),\n 'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),\n 'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),\n 'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),\n 'Subject': _parse_subject(cert.get_subject()),\n 'Subject Hash': _dec2hex(cert.get_subject().as_hash()),\n 'Issuer': _parse_subject(cert.get_issuer()),\n 'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),\n 'Not Before':\n cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),\n 'Not After':\n cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),\n 'Public Key': get_public_key(cert)\n }\n\n exts = OrderedDict()\n for ext_index in range(0, cert.get_ext_count()):\n ext = cert.get_ext_at(ext_index)\n name = ext.get_name()\n val = ext.get_value()\n if ext.get_critical():\n val = 'critical ' + val\n exts[name] = val\n\n if exts:\n ret['X509v3 Extensions'] = exts\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
read_csr
|
python
|
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
|
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L616-L644
|
[
"def _parse_subject(subject):\n '''\n Returns a dict containing all values in an X509 Subject\n '''\n ret = {}\n nids = []\n for nid_name, nid_num in six.iteritems(subject.nid):\n if nid_num in nids:\n continue\n try:\n val = getattr(subject, nid_name)\n if val:\n ret[nid_name] = val\n nids.append(nid_num)\n except TypeError as err:\n log.debug(\"Missing attribute '%s'. Error: %s\", nid_name, err)\n\n return ret\n",
"def _get_csr_extensions(csr):\n '''\n Returns a list of dicts containing the name, value and critical value of\n any extension contained in a csr object.\n '''\n ret = OrderedDict()\n\n csrtempfile = tempfile.NamedTemporaryFile()\n csrtempfile.write(csr.as_pem())\n csrtempfile.flush()\n csryaml = _parse_openssl_req(csrtempfile.name)\n csrtempfile.close()\n if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:\n csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']\n\n if not csrexts:\n return ret\n\n for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):\n if long_name in csrexts:\n csrexts[short_name] = csrexts[long_name]\n del csrexts[long_name]\n ret = csrexts\n return ret\n",
"def _dec2hex(decval):\n '''\n Converts decimal values to nicely formatted hex strings\n '''\n return _pretty_hex('{0:X}'.format(decval))\n",
"def _get_request_obj(csr):\n '''\n Returns a CSR object based on PEM text.\n '''\n text = _text_or_file(csr)\n text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')\n return M2Crypto.X509.load_request_string(text)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
read_crl
|
python
|
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
|
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L647-L672
|
[
"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_pem_entry(text, pem_type=None):\n '''\n Returns a properly formatted PEM string from the input text fixing\n any whitespace or line-break issues\n\n text:\n Text containing the X509 PEM entry to be returned or path to\n a file containing the text.\n\n pem_type:\n If specified, this function will only return a pem of a certain type,\n for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_pem_entry \"-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST\"\n '''\n text = _text_or_file(text)\n # Replace encoded newlines\n text = text.replace('\\\\n', '\\n')\n\n _match = None\n\n if len(text.splitlines()) == 1 and text.startswith(\n '-----') and text.endswith('-----'):\n # mine.get returns the PEM on a single line, we fix this\n pem_fixed = []\n pem_temp = text\n while pem_temp:\n if pem_temp.startswith('-----'):\n # Grab ----(.*)---- blocks\n pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])\n pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]\n else:\n # grab base64 chunks\n if pem_temp[:64].count('-') == 0:\n pem_fixed.append(pem_temp[:64])\n pem_temp = pem_temp[64:]\n else:\n pem_fixed.append(pem_temp[:pem_temp.index('-')])\n pem_temp = pem_temp[pem_temp.index('-'):]\n text = \"\\n\".join(pem_fixed)\n\n _dregex = _make_regex('[0-9A-Z ]+')\n errmsg = 'PEM text not valid:\\n{0}'.format(text)\n if pem_type:\n _dregex = _make_regex(pem_type)\n errmsg = ('PEM does not contain a single entry of type {0}:\\n'\n '{1}'.format(pem_type, text))\n\n for _match in _dregex.finditer(text):\n if _match:\n break\n if not _match:\n raise salt.exceptions.SaltInvocationError(errmsg)\n _match_dict = _match.groupdict()\n pem_header = _match_dict['pem_header']\n proc_type = _match_dict['proc_type']\n dek_info = _match_dict['dek_info']\n pem_footer = _match_dict['pem_footer']\n pem_body = _match_dict['pem_body']\n\n # Remove all whitespace from body\n pem_body = ''.join(pem_body.split())\n\n # Generate correctly formatted pem\n ret = pem_header + '\\n'\n if proc_type:\n ret += proc_type + '\\n'\n if dek_info:\n ret += dek_info + '\\n' + '\\n'\n for i in range(0, len(pem_body), 64):\n ret += pem_body[i:i + 64] + '\\n'\n ret += pem_footer + '\\n'\n\n return salt.utils.stringutils.to_bytes(ret, encoding='ascii')\n",
"def _parse_openssl_crl(crl_filename):\n '''\n Parses openssl command line output, this is a workaround for M2Crypto's\n inability to get them from CSR objects.\n '''\n if not salt.utils.path.which('openssl'):\n raise salt.exceptions.SaltInvocationError(\n 'openssl binary not found in path'\n )\n cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))\n\n output = __salt__['cmd.run_stdout'](cmd)\n\n crl = {}\n for line in output.split('\\n'):\n line = line.strip()\n if line.startswith('Version '):\n crl['Version'] = line.replace('Version ', '')\n if line.startswith('Signature Algorithm: '):\n crl['Signature Algorithm'] = line.replace(\n 'Signature Algorithm: ', '')\n if line.startswith('Issuer: '):\n line = line.replace('Issuer: ', '')\n subject = {}\n for sub_entry in line.split('/'):\n if '=' in sub_entry:\n sub_entry = sub_entry.split('=')\n subject[sub_entry[0]] = sub_entry[1]\n crl['Issuer'] = subject\n if line.startswith('Last Update: '):\n crl['Last Update'] = line.replace('Last Update: ', '')\n last_update = datetime.datetime.strptime(\n crl['Last Update'], \"%b %d %H:%M:%S %Y %Z\")\n crl['Last Update'] = last_update.strftime(\"%Y-%m-%d %H:%M:%S\")\n if line.startswith('Next Update: '):\n crl['Next Update'] = line.replace('Next Update: ', '')\n next_update = datetime.datetime.strptime(\n crl['Next Update'], \"%b %d %H:%M:%S %Y %Z\")\n crl['Next Update'] = next_update.strftime(\"%Y-%m-%d %H:%M:%S\")\n if line.startswith('Revoked Certificates:'):\n break\n\n if 'No Revoked Certificates.' in output:\n crl['Revoked Certificates'] = []\n return crl\n\n output = output.split('Revoked Certificates:')[1]\n output = output.split('Signature Algorithm:')[0]\n\n rev = []\n for revoked in output.split('Serial Number: '):\n if not revoked.strip():\n continue\n\n rev_sn = revoked.split('\\n')[0].strip()\n revoked = rev_sn + ':\\n' + '\\n'.join(revoked.split('\\n')[1:])\n rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))\n # pylint: disable=unused-variable\n for rev_item, rev_values in six.iteritems(rev_yaml):\n # pylint: enable=unused-variable\n if 'Revocation Date' in rev_values:\n rev_date = datetime.datetime.strptime(\n rev_values['Revocation Date'], \"%b %d %H:%M:%S %Y %Z\")\n rev_values['Revocation Date'] = rev_date.strftime(\n \"%Y-%m-%d %H:%M:%S\")\n\n rev.append(rev_yaml)\n\n crl['Revoked Certificates'] = rev\n\n return crl\n",
"def _text_or_file(input_):\n '''\n Determines if input is a path to a file, or a string with the\n content to be parsed.\n '''\n if _isfile(input_):\n with salt.utils.files.fopen(input_) as fp_:\n out = salt.utils.stringutils.to_str(fp_.read())\n else:\n out = salt.utils.stringutils.to_str(input_)\n\n return out\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
get_public_key
|
python
|
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
|
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L675-L722
|
[
"def get_pem_entry(text, pem_type=None):\n '''\n Returns a properly formatted PEM string from the input text fixing\n any whitespace or line-break issues\n\n text:\n Text containing the X509 PEM entry to be returned or path to\n a file containing the text.\n\n pem_type:\n If specified, this function will only return a pem of a certain type,\n for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_pem_entry \"-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST\"\n '''\n text = _text_or_file(text)\n # Replace encoded newlines\n text = text.replace('\\\\n', '\\n')\n\n _match = None\n\n if len(text.splitlines()) == 1 and text.startswith(\n '-----') and text.endswith('-----'):\n # mine.get returns the PEM on a single line, we fix this\n pem_fixed = []\n pem_temp = text\n while pem_temp:\n if pem_temp.startswith('-----'):\n # Grab ----(.*)---- blocks\n pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])\n pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]\n else:\n # grab base64 chunks\n if pem_temp[:64].count('-') == 0:\n pem_fixed.append(pem_temp[:64])\n pem_temp = pem_temp[64:]\n else:\n pem_fixed.append(pem_temp[:pem_temp.index('-')])\n pem_temp = pem_temp[pem_temp.index('-'):]\n text = \"\\n\".join(pem_fixed)\n\n _dregex = _make_regex('[0-9A-Z ]+')\n errmsg = 'PEM text not valid:\\n{0}'.format(text)\n if pem_type:\n _dregex = _make_regex(pem_type)\n errmsg = ('PEM does not contain a single entry of type {0}:\\n'\n '{1}'.format(pem_type, text))\n\n for _match in _dregex.finditer(text):\n if _match:\n break\n if not _match:\n raise salt.exceptions.SaltInvocationError(errmsg)\n _match_dict = _match.groupdict()\n pem_header = _match_dict['pem_header']\n proc_type = _match_dict['proc_type']\n dek_info = _match_dict['dek_info']\n pem_footer = _match_dict['pem_footer']\n pem_body = _match_dict['pem_body']\n\n # Remove all whitespace from body\n pem_body = ''.join(pem_body.split())\n\n # Generate correctly formatted pem\n ret = pem_header + '\\n'\n if proc_type:\n ret += proc_type + '\\n'\n if dek_info:\n ret += dek_info + '\\n' + '\\n'\n for i in range(0, len(pem_body), 64):\n ret += pem_body[i:i + 64] + '\\n'\n ret += pem_footer + '\\n'\n\n return salt.utils.stringutils.to_bytes(ret, encoding='ascii')\n",
"def _text_or_file(input_):\n '''\n Determines if input is a path to a file, or a string with the\n content to be parsed.\n '''\n if _isfile(input_):\n with salt.utils.files.fopen(input_) as fp_:\n out = salt.utils.stringutils.to_str(fp_.read())\n else:\n out = salt.utils.stringutils.to_str(input_)\n\n return out\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
write_pem
|
python
|
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
|
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L741-L790
|
[
"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_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_pem_entry(text, pem_type=None):\n '''\n Returns a properly formatted PEM string from the input text fixing\n any whitespace or line-break issues\n\n text:\n Text containing the X509 PEM entry to be returned or path to\n a file containing the text.\n\n pem_type:\n If specified, this function will only return a pem of a certain type,\n for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_pem_entry \"-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST\"\n '''\n text = _text_or_file(text)\n # Replace encoded newlines\n text = text.replace('\\\\n', '\\n')\n\n _match = None\n\n if len(text.splitlines()) == 1 and text.startswith(\n '-----') and text.endswith('-----'):\n # mine.get returns the PEM on a single line, we fix this\n pem_fixed = []\n pem_temp = text\n while pem_temp:\n if pem_temp.startswith('-----'):\n # Grab ----(.*)---- blocks\n pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])\n pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]\n else:\n # grab base64 chunks\n if pem_temp[:64].count('-') == 0:\n pem_fixed.append(pem_temp[:64])\n pem_temp = pem_temp[64:]\n else:\n pem_fixed.append(pem_temp[:pem_temp.index('-')])\n pem_temp = pem_temp[pem_temp.index('-'):]\n text = \"\\n\".join(pem_fixed)\n\n _dregex = _make_regex('[0-9A-Z ]+')\n errmsg = 'PEM text not valid:\\n{0}'.format(text)\n if pem_type:\n _dregex = _make_regex(pem_type)\n errmsg = ('PEM does not contain a single entry of type {0}:\\n'\n '{1}'.format(pem_type, text))\n\n for _match in _dregex.finditer(text):\n if _match:\n break\n if not _match:\n raise salt.exceptions.SaltInvocationError(errmsg)\n _match_dict = _match.groupdict()\n pem_header = _match_dict['pem_header']\n proc_type = _match_dict['proc_type']\n dek_info = _match_dict['dek_info']\n pem_footer = _match_dict['pem_footer']\n pem_body = _match_dict['pem_body']\n\n # Remove all whitespace from body\n pem_body = ''.join(pem_body.split())\n\n # Generate correctly formatted pem\n ret = pem_header + '\\n'\n if proc_type:\n ret += proc_type + '\\n'\n if dek_info:\n ret += dek_info + '\\n' + '\\n'\n for i in range(0, len(pem_body), 64):\n ret += pem_body[i:i + 64] + '\\n'\n ret += pem_footer + '\\n'\n\n return salt.utils.stringutils.to_bytes(ret, encoding='ascii')\n",
"def _text_or_file(input_):\n '''\n Determines if input is a path to a file, or a string with the\n content to be parsed.\n '''\n if _isfile(input_):\n with salt.utils.files.fopen(input_) as fp_:\n out = salt.utils.stringutils.to_str(fp_.read())\n else:\n out = salt.utils.stringutils.to_str(input_)\n\n return out\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
create_private_key
|
python
|
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
|
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L793-L860
|
[
"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 _passphrase_callback(passphrase):\n '''\n Returns a callback function used to supply a passphrase for private keys\n '''\n def f(*args):\n return salt.utils.stringutils.to_bytes(passphrase)\n return f\n",
"def write_pem(text, path, overwrite=True, pem_type=None):\n '''\n Writes out a PEM string fixing any formatting or whitespace\n issues before writing.\n\n text:\n PEM string input to be written out.\n\n path:\n Path of the file to write the pem out to.\n\n overwrite:\n If True(default), write_pem will overwrite the entire pem file.\n Set False to preserve existing private keys and dh params that may\n exist in the pem file.\n\n pem_type:\n The PEM type to be saved, for example ``CERTIFICATE`` or\n ``PUBLIC KEY``. Adding this will allow the function to take\n input that may contain multiple pem types.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.write_pem \"-----BEGIN CERTIFICATE-----MIIGMzCCBBugA...\" path=/etc/pki/mycert.crt\n '''\n with salt.utils.files.set_umask(0o077):\n text = get_pem_entry(text, pem_type=pem_type)\n _dhparams = ''\n _private_key = ''\n if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:\n _filecontents = _text_or_file(path)\n try:\n _dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')\n except salt.exceptions.SaltInvocationError as err:\n log.debug(\"Error when getting DH PARAMETERS: %s\", err)\n log.trace(err, exc_info=err)\n try:\n _private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')\n except salt.exceptions.SaltInvocationError as err:\n log.debug(\"Error when getting PRIVATE KEY: %s\", err)\n log.trace(err, exc_info=err)\n with salt.utils.files.fopen(path, 'w') as _fp:\n if pem_type and pem_type == 'CERTIFICATE' and _private_key:\n _fp.write(salt.utils.stringutils.to_str(_private_key))\n _fp.write(salt.utils.stringutils.to_str(text))\n if pem_type and pem_type == 'CERTIFICATE' and _dhparams:\n _fp.write(salt.utils.stringutils.to_str(_dhparams))\n return 'PEM written to {0}'.format(path)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
create_crl
|
python
|
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
|
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L863-L1017
|
[
"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_pem_entry(text, pem_type=None):\n '''\n Returns a properly formatted PEM string from the input text fixing\n any whitespace or line-break issues\n\n text:\n Text containing the X509 PEM entry to be returned or path to\n a file containing the text.\n\n pem_type:\n If specified, this function will only return a pem of a certain type,\n for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_pem_entry \"-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST\"\n '''\n text = _text_or_file(text)\n # Replace encoded newlines\n text = text.replace('\\\\n', '\\n')\n\n _match = None\n\n if len(text.splitlines()) == 1 and text.startswith(\n '-----') and text.endswith('-----'):\n # mine.get returns the PEM on a single line, we fix this\n pem_fixed = []\n pem_temp = text\n while pem_temp:\n if pem_temp.startswith('-----'):\n # Grab ----(.*)---- blocks\n pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])\n pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]\n else:\n # grab base64 chunks\n if pem_temp[:64].count('-') == 0:\n pem_fixed.append(pem_temp[:64])\n pem_temp = pem_temp[64:]\n else:\n pem_fixed.append(pem_temp[:pem_temp.index('-')])\n pem_temp = pem_temp[pem_temp.index('-'):]\n text = \"\\n\".join(pem_fixed)\n\n _dregex = _make_regex('[0-9A-Z ]+')\n errmsg = 'PEM text not valid:\\n{0}'.format(text)\n if pem_type:\n _dregex = _make_regex(pem_type)\n errmsg = ('PEM does not contain a single entry of type {0}:\\n'\n '{1}'.format(pem_type, text))\n\n for _match in _dregex.finditer(text):\n if _match:\n break\n if not _match:\n raise salt.exceptions.SaltInvocationError(errmsg)\n _match_dict = _match.groupdict()\n pem_header = _match_dict['pem_header']\n proc_type = _match_dict['proc_type']\n dek_info = _match_dict['dek_info']\n pem_footer = _match_dict['pem_footer']\n pem_body = _match_dict['pem_body']\n\n # Remove all whitespace from body\n pem_body = ''.join(pem_body.split())\n\n # Generate correctly formatted pem\n ret = pem_header + '\\n'\n if proc_type:\n ret += proc_type + '\\n'\n if dek_info:\n ret += dek_info + '\\n' + '\\n'\n for i in range(0, len(pem_body), 64):\n ret += pem_body[i:i + 64] + '\\n'\n ret += pem_footer + '\\n'\n\n return salt.utils.stringutils.to_bytes(ret, encoding='ascii')\n",
"def read_certificate(certificate):\n '''\n Returns a dict containing details of a certificate. Input can be a PEM\n string or file path.\n\n certificate:\n The certificate to be read. Can be a path to a certificate file, or\n a string containing the PEM formatted text of the certificate.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.read_certificate /etc/pki/mycert.crt\n '''\n cert = _get_certificate_obj(certificate)\n\n ret = {\n # X509 Version 3 has a value of 2 in the field.\n # Version 2 has a value of 1.\n # https://tools.ietf.org/html/rfc5280#section-4.1.2.1\n 'Version': cert.get_version() + 1,\n # Get size returns in bytes. The world thinks of key sizes in bits.\n 'Key Size': cert.get_pubkey().size() * 8,\n 'Serial Number': _dec2hex(cert.get_serial_number()),\n 'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),\n 'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),\n 'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),\n 'Subject': _parse_subject(cert.get_subject()),\n 'Subject Hash': _dec2hex(cert.get_subject().as_hash()),\n 'Issuer': _parse_subject(cert.get_issuer()),\n 'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),\n 'Not Before':\n cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),\n 'Not After':\n cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),\n 'Public Key': get_public_key(cert)\n }\n\n exts = OrderedDict()\n for ext_index in range(0, cert.get_ext_count()):\n ext = cert.get_ext_at(ext_index)\n name = ext.get_name()\n val = ext.get_value()\n if ext.get_critical():\n val = 'critical ' + val\n exts[name] = val\n\n if exts:\n ret['X509v3 Extensions'] = exts\n\n return ret\n",
"def _text_or_file(input_):\n '''\n Determines if input is a path to a file, or a string with the\n content to be parsed.\n '''\n if _isfile(input_):\n with salt.utils.files.fopen(input_) as fp_:\n out = salt.utils.stringutils.to_str(fp_.read())\n else:\n out = salt.utils.stringutils.to_str(input_)\n\n return out\n",
"def _get_private_key_obj(private_key, passphrase=None):\n '''\n Returns a private key object based on PEM text.\n '''\n private_key = _text_or_file(private_key)\n private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')\n rsaprivkey = M2Crypto.RSA.load_key_string(\n private_key, callback=_passphrase_callback(passphrase))\n evpprivkey = M2Crypto.EVP.PKey()\n evpprivkey.assign_rsa(rsaprivkey)\n return evpprivkey\n",
"def write_pem(text, path, overwrite=True, pem_type=None):\n '''\n Writes out a PEM string fixing any formatting or whitespace\n issues before writing.\n\n text:\n PEM string input to be written out.\n\n path:\n Path of the file to write the pem out to.\n\n overwrite:\n If True(default), write_pem will overwrite the entire pem file.\n Set False to preserve existing private keys and dh params that may\n exist in the pem file.\n\n pem_type:\n The PEM type to be saved, for example ``CERTIFICATE`` or\n ``PUBLIC KEY``. Adding this will allow the function to take\n input that may contain multiple pem types.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.write_pem \"-----BEGIN CERTIFICATE-----MIIGMzCCBBugA...\" path=/etc/pki/mycert.crt\n '''\n with salt.utils.files.set_umask(0o077):\n text = get_pem_entry(text, pem_type=pem_type)\n _dhparams = ''\n _private_key = ''\n if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:\n _filecontents = _text_or_file(path)\n try:\n _dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')\n except salt.exceptions.SaltInvocationError as err:\n log.debug(\"Error when getting DH PARAMETERS: %s\", err)\n log.trace(err, exc_info=err)\n try:\n _private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')\n except salt.exceptions.SaltInvocationError as err:\n log.debug(\"Error when getting PRIVATE KEY: %s\", err)\n log.trace(err, exc_info=err)\n with salt.utils.files.fopen(path, 'w') as _fp:\n if pem_type and pem_type == 'CERTIFICATE' and _private_key:\n _fp.write(salt.utils.stringutils.to_str(_private_key))\n _fp.write(salt.utils.stringutils.to_str(text))\n if pem_type and pem_type == 'CERTIFICATE' and _dhparams:\n _fp.write(salt.utils.stringutils.to_str(_dhparams))\n return 'PEM written to {0}'.format(path)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
sign_remote_certificate
|
python
|
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
|
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L1020-L1070
|
[
"def create_certificate(\n path=None, text=False, overwrite=True, ca_server=None, **kwargs):\n '''\n Create an X509 certificate.\n\n path:\n Path to write the certificate to.\n\n text:\n If ``True``, return the PEM text without writing to a file.\n Default ``False``.\n\n overwrite:\n If True(default), create_certificate will overwrite the entire pem\n file. Set False to preserve existing private keys and dh params that\n may exist in the pem file.\n\n kwargs:\n Any of the properties below can be included as additional\n keyword arguments.\n\n ca_server:\n Request a remotely signed certificate from ca_server. For this to\n work, a ``signing_policy`` must be specified, and that same policy\n must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for\n details. Also the salt master must permit peers to call the\n ``sign_remote_certificate`` function.\n\n Example:\n\n /etc/salt/master.d/peer.conf\n\n .. code-block:: yaml\n\n peer:\n .*:\n - x509.sign_remote_certificate\n\n subject properties:\n Any of the values below can be included to set subject properties\n Any other subject properties supported by OpenSSL should also work.\n\n C:\n 2 letter Country code\n CN:\n Certificate common name, typically the FQDN.\n\n Email:\n Email address\n\n GN:\n Given Name\n\n L:\n Locality\n\n O:\n Organization\n\n OU:\n Organization Unit\n\n SN:\n SurName\n\n ST:\n State or Province\n\n signing_private_key:\n A path or string of the private key in PEM format that will be used\n to sign this certificate. If neither ``signing_cert``, ``public_key``,\n or ``csr`` are included, it will be assumed that this is a self-signed\n certificate, and the public key matching ``signing_private_key`` will\n be used to create the certificate.\n\n signing_private_key_passphrase:\n Passphrase used to decrypt the signing_private_key.\n\n signing_cert:\n A certificate matching the private key that will be used to sign this\n certificate. This is used to populate the issuer values in the\n resulting certificate. Do not include this value for\n self-signed certificates.\n\n public_key:\n The public key to be included in this certificate. This can be sourced\n from a public key, certificate, csr or private key. If a private key\n is used, the matching public key from the private key will be\n generated before any processing is done. This means you can request a\n certificate from a remote CA using a private key file as your\n public_key and only the public key will be sent across the network to\n the CA. If neither ``public_key`` or ``csr`` are specified, it will be\n assumed that this is a self-signed certificate, and the public key\n derived from ``signing_private_key`` will be used. Specify either\n ``public_key`` or ``csr``, not both. Because you can input a CSR as a\n public key or as a CSR, it is important to understand the difference.\n If you import a CSR as a public key, only the public key will be added\n to the certificate, subject or extension information in the CSR will\n be lost.\n\n public_key_passphrase:\n If the public key is supplied as a private key, this is the passphrase\n used to decrypt it.\n\n csr:\n A file or PEM string containing a certificate signing request. This\n will be used to supply the subject, extensions and public key of a\n certificate. Any subject or extensions specified explicitly will\n overwrite any in the CSR.\n\n basicConstraints:\n X509v3 Basic Constraints extension.\n\n extensions:\n The following arguments set X509v3 Extension values. If the value\n starts with ``critical``, the extension will be marked as critical.\n\n Some special extensions are ``subjectKeyIdentifier`` and\n ``authorityKeyIdentifier``.\n\n ``subjectKeyIdentifier`` can be an explicit value or it can be the\n special string ``hash``. ``hash`` will set the subjectKeyIdentifier\n equal to the SHA1 hash of the modulus of the public key in this\n certificate. Note that this is not the exact same hashing method used\n by OpenSSL when using the hash value.\n\n ``authorityKeyIdentifier`` Use values acceptable to the openssl CLI\n tools. This will automatically populate ``authorityKeyIdentifier``\n with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a\n self-signed cert these values will be the same.\n\n basicConstraints:\n X509v3 Basic Constraints\n\n keyUsage:\n X509v3 Key Usage\n\n extendedKeyUsage:\n X509v3 Extended Key Usage\n\n subjectKeyIdentifier:\n X509v3 Subject Key Identifier\n\n issuerAltName:\n X509v3 Issuer Alternative Name\n\n subjectAltName:\n X509v3 Subject Alternative Name\n\n crlDistributionPoints:\n X509v3 CRL distribution points\n\n issuingDistributionPoint:\n X509v3 Issuing Distribution Point\n\n certificatePolicies:\n X509v3 Certificate Policies\n\n policyConstraints:\n X509v3 Policy Constraints\n\n inhibitAnyPolicy:\n X509v3 Inhibit Any Policy\n\n nameConstraints:\n X509v3 Name Constraints\n\n noCheck:\n X509v3 OCSP No Check\n\n nsComment:\n Netscape Comment\n\n nsCertType:\n Netscape Certificate Type\n\n days_valid:\n The number of days this certificate should be valid. This sets the\n ``notAfter`` property of the certificate. Defaults to 365.\n\n version:\n The version of the X509 certificate. Defaults to 3. This is\n automatically converted to the version value, so ``version=3``\n sets the certificate version field to 0x2.\n\n serial_number:\n The serial number to assign to this certificate. If omitted a random\n serial number of size ``serial_bits`` is generated.\n\n serial_bits:\n The number of bits to use when randomly generating a serial number.\n Defaults to 64.\n\n algorithm:\n The hashing algorithm to be used for signing this certificate.\n Defaults to sha256.\n\n copypath:\n An additional path to copy the resulting certificate to. Can be used\n to maintain a copy of all certificates issued for revocation purposes.\n\n prepend_cn:\n If set to True, the CN and a dash will be prepended to the copypath's filename.\n\n Example:\n /etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt\n\n signing_policy:\n A signing policy that should be used to create this certificate.\n Signing policies should be defined in the minion configuration, or in\n a minion pillar. It should be a yaml formatted list of arguments\n which will override any arguments passed to this function. If the\n ``minions`` key is included in the signing policy, only minions\n matching that pattern (see match.glob and match.compound) will be\n permitted to remotely request certificates from that policy.\n\n Example:\n\n .. code-block:: yaml\n\n x509_signing_policies:\n www:\n - minions: 'www*'\n - signing_private_key: /etc/pki/ca.key\n - signing_cert: /etc/pki/ca.crt\n - C: US\n - ST: Utah\n - L: Salt Lake City\n - basicConstraints: \"critical CA:false\"\n - keyUsage: \"critical cRLSign, keyCertSign\"\n - subjectKeyIdentifier: hash\n - authorityKeyIdentifier: keyid,issuer:always\n - days_valid: 90\n - copypath: /etc/pki/issued_certs/\n\n The above signing policy can be invoked with ``signing_policy=www``\n\n ext_mapping:\n Provide additional X509v3 extension mappings. This argument should be\n in the form of a dictionary and should include both the OID and the\n friendly name for the extension.\n\n .. versionadded:: Neon\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}\n '''\n\n if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):\n raise salt.exceptions.SaltInvocationError(\n 'Either path or text must be specified.')\n if path and text:\n raise salt.exceptions.SaltInvocationError(\n 'Either path or text must be specified, not both.')\n\n if 'public_key_passphrase' not in kwargs:\n kwargs['public_key_passphrase'] = None\n if ca_server:\n if 'signing_policy' not in kwargs:\n raise salt.exceptions.SaltInvocationError(\n 'signing_policy must be specified'\n 'if requesting remote certificate from ca_server {0}.'\n .format(ca_server))\n if 'csr' in kwargs:\n kwargs['csr'] = get_pem_entry(\n kwargs['csr'],\n pem_type='CERTIFICATE REQUEST').replace('\\n', '')\n if 'public_key' in kwargs:\n # Strip newlines to make passing through as cli functions easier\n kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(\n kwargs['public_key'],\n passphrase=kwargs['public_key_passphrase'])).replace('\\n', '')\n\n # Remove system entries in kwargs\n # Including listen_in and preqreuired because they are not included\n # in STATE_INTERNAL_KEYWORDS\n # for salt 2014.7.2\n for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:\n kwargs.pop(ignore, None)\n\n if not isinstance(ca_server, list):\n ca_server = [ca_server]\n random.shuffle(ca_server)\n for server in ca_server:\n certs = __salt__['publish.publish'](\n tgt=server,\n fun='x509.sign_remote_certificate',\n arg=six.text_type(kwargs))\n if certs is None or not any(certs):\n continue\n else:\n cert_txt = certs[server]\n break\n\n if not any(certs):\n raise salt.exceptions.SaltInvocationError(\n 'ca_server did not respond'\n ' salt master must permit peers to'\n ' call the sign_remote_certificate function.')\n\n if path:\n return write_pem(\n text=cert_txt,\n overwrite=overwrite,\n path=path,\n pem_type='CERTIFICATE'\n )\n else:\n return cert_txt\n\n signing_policy = {}\n if 'signing_policy' in kwargs:\n signing_policy = _get_signing_policy(kwargs['signing_policy'])\n if isinstance(signing_policy, list):\n dict_ = {}\n for item in signing_policy:\n dict_.update(item)\n signing_policy = dict_\n\n # Overwrite any arguments in kwargs with signing_policy\n kwargs.update(signing_policy)\n\n for prop, default in six.iteritems(CERT_DEFAULTS):\n if prop not in kwargs:\n kwargs[prop] = default\n\n cert = M2Crypto.X509.X509()\n\n # X509 Version 3 has a value of 2 in the field.\n # Version 2 has a value of 1.\n # https://tools.ietf.org/html/rfc5280#section-4.1.2.1\n cert.set_version(kwargs['version'] - 1)\n\n # Random serial number if not specified\n if 'serial_number' not in kwargs:\n kwargs['serial_number'] = _dec2hex(\n random.getrandbits(kwargs['serial_bits']))\n serial_number = int(kwargs['serial_number'].replace(':', ''), 16)\n # With Python3 we occasionally end up with an INT that is greater than a C\n # long max_value. This causes an overflow error due to a bug in M2Crypto.\n # See issue: https://gitlab.com/m2crypto/m2crypto/issues/232\n # Remove this after M2Crypto fixes the bug.\n if six.PY3:\n if salt.utils.platform.is_windows():\n INT_MAX = 2147483647\n if serial_number >= INT_MAX:\n serial_number -= int(serial_number / INT_MAX) * INT_MAX\n else:\n if serial_number >= sys.maxsize:\n serial_number -= int(serial_number / sys.maxsize) * sys.maxsize\n cert.set_serial_number(serial_number)\n\n # Set validity dates\n # pylint: disable=no-member\n not_before = M2Crypto.m2.x509_get_not_before(cert.x509)\n not_after = M2Crypto.m2.x509_get_not_after(cert.x509)\n M2Crypto.m2.x509_gmtime_adj(not_before, 0)\n M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])\n # pylint: enable=no-member\n\n # If neither public_key or csr are included, this cert is self-signed\n if 'public_key' not in kwargs and 'csr' not in kwargs:\n kwargs['public_key'] = kwargs['signing_private_key']\n if 'signing_private_key_passphrase' in kwargs:\n kwargs['public_key_passphrase'] = kwargs[\n 'signing_private_key_passphrase']\n\n csrexts = {}\n if 'csr' in kwargs:\n kwargs['public_key'] = kwargs['csr']\n csr = _get_request_obj(kwargs['csr'])\n cert.set_subject(csr.get_subject())\n csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']\n\n cert.set_pubkey(get_public_key(kwargs['public_key'],\n passphrase=kwargs['public_key_passphrase'], asObj=True))\n\n subject = cert.get_subject()\n\n # pylint: disable=unused-variable\n for entry, num in six.iteritems(subject.nid):\n if entry in kwargs:\n setattr(subject, entry, kwargs[entry])\n # pylint: enable=unused-variable\n\n if 'signing_cert' in kwargs:\n signing_cert = _get_certificate_obj(kwargs['signing_cert'])\n else:\n signing_cert = cert\n cert.set_issuer(signing_cert.get_subject())\n\n if 'ext_mapping' in kwargs:\n EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])\n\n for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):\n if (extname in kwargs or extlongname in kwargs or\n extname in csrexts or extlongname in csrexts) is False:\n continue\n\n # Use explicitly set values first, fall back to CSR values.\n extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)\n\n critical = False\n if extval.startswith('critical '):\n critical = True\n extval = extval[9:]\n\n if extname == 'subjectKeyIdentifier' and 'hash' in extval:\n extval = extval.replace('hash', _get_pubkey_hash(cert))\n\n issuer = None\n if extname == 'authorityKeyIdentifier':\n issuer = signing_cert\n\n if extname == 'subjectAltName':\n extval = extval.replace('IP Address', 'IP')\n\n ext = _new_extension(\n name=extname, value=extval, critical=critical, issuer=issuer)\n if not ext.x509_ext:\n log.info('Invalid X509v3 Extension. %s: %s', extname, extval)\n continue\n\n cert.add_ext(ext)\n\n if 'signing_private_key_passphrase' not in kwargs:\n kwargs['signing_private_key_passphrase'] = None\n if 'testrun' in kwargs and kwargs['testrun'] is True:\n cert_props = read_certificate(cert)\n cert_props['Issuer Public Key'] = get_public_key(\n kwargs['signing_private_key'],\n passphrase=kwargs['signing_private_key_passphrase'])\n return cert_props\n\n if not verify_private_key(private_key=kwargs['signing_private_key'],\n passphrase=kwargs[\n 'signing_private_key_passphrase'],\n public_key=signing_cert):\n raise salt.exceptions.SaltInvocationError(\n 'signing_private_key: {0} '\n 'does no match signing_cert: {1}'.format(\n kwargs['signing_private_key'],\n kwargs.get('signing_cert', '')\n )\n )\n\n cert.sign(\n _get_private_key_obj(kwargs['signing_private_key'],\n passphrase=kwargs['signing_private_key_passphrase']),\n kwargs['algorithm']\n )\n\n if not verify_signature(cert, signing_pub_key=signing_cert):\n raise salt.exceptions.SaltInvocationError(\n 'failed to verify certificate signature')\n\n if 'copypath' in kwargs:\n if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:\n prepend = six.text_type(kwargs['CN']) + '-'\n else:\n prepend = ''\n write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],\n prepend + kwargs['serial_number'] + '.crt'),\n pem_type='CERTIFICATE')\n\n if path:\n return write_pem(\n text=cert.as_pem(),\n overwrite=overwrite,\n path=path,\n pem_type='CERTIFICATE'\n )\n else:\n return salt.utils.stringutils.to_str(cert.as_pem())\n",
"def _get_signing_policy(name):\n policies = __salt__['pillar.get']('x509_signing_policies', None)\n if policies:\n signing_policy = policies.get(name)\n if signing_policy:\n return signing_policy\n return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
get_signing_policy
|
python
|
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
|
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L1073-L1105
|
[
"def get_pem_entry(text, pem_type=None):\n '''\n Returns a properly formatted PEM string from the input text fixing\n any whitespace or line-break issues\n\n text:\n Text containing the X509 PEM entry to be returned or path to\n a file containing the text.\n\n pem_type:\n If specified, this function will only return a pem of a certain type,\n for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_pem_entry \"-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST\"\n '''\n text = _text_or_file(text)\n # Replace encoded newlines\n text = text.replace('\\\\n', '\\n')\n\n _match = None\n\n if len(text.splitlines()) == 1 and text.startswith(\n '-----') and text.endswith('-----'):\n # mine.get returns the PEM on a single line, we fix this\n pem_fixed = []\n pem_temp = text\n while pem_temp:\n if pem_temp.startswith('-----'):\n # Grab ----(.*)---- blocks\n pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])\n pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]\n else:\n # grab base64 chunks\n if pem_temp[:64].count('-') == 0:\n pem_fixed.append(pem_temp[:64])\n pem_temp = pem_temp[64:]\n else:\n pem_fixed.append(pem_temp[:pem_temp.index('-')])\n pem_temp = pem_temp[pem_temp.index('-'):]\n text = \"\\n\".join(pem_fixed)\n\n _dregex = _make_regex('[0-9A-Z ]+')\n errmsg = 'PEM text not valid:\\n{0}'.format(text)\n if pem_type:\n _dregex = _make_regex(pem_type)\n errmsg = ('PEM does not contain a single entry of type {0}:\\n'\n '{1}'.format(pem_type, text))\n\n for _match in _dregex.finditer(text):\n if _match:\n break\n if not _match:\n raise salt.exceptions.SaltInvocationError(errmsg)\n _match_dict = _match.groupdict()\n pem_header = _match_dict['pem_header']\n proc_type = _match_dict['proc_type']\n dek_info = _match_dict['dek_info']\n pem_footer = _match_dict['pem_footer']\n pem_body = _match_dict['pem_body']\n\n # Remove all whitespace from body\n pem_body = ''.join(pem_body.split())\n\n # Generate correctly formatted pem\n ret = pem_header + '\\n'\n if proc_type:\n ret += proc_type + '\\n'\n if dek_info:\n ret += dek_info + '\\n' + '\\n'\n for i in range(0, len(pem_body), 64):\n ret += pem_body[i:i + 64] + '\\n'\n ret += pem_footer + '\\n'\n\n return salt.utils.stringutils.to_bytes(ret, encoding='ascii')\n",
"def _get_signing_policy(name):\n policies = __salt__['pillar.get']('x509_signing_policies', None)\n if policies:\n signing_policy = policies.get(name)\n if signing_policy:\n return signing_policy\n return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
create_certificate
|
python
|
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
|
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L1109-L1585
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\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 verify_signature(certificate, signing_pub_key=None,\n signing_pub_key_passphrase=None):\n '''\n Verify that ``certificate`` has been signed by ``signing_pub_key``\n\n certificate:\n The certificate to verify. Can be a path or string containing a\n PEM formatted certificate.\n\n signing_pub_key:\n The public key to verify, can be a string or path to a PEM formatted\n certificate, csr, or private key.\n\n signing_pub_key_passphrase:\n Passphrase to the signing_pub_key if it is an encrypted private key.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.verify_signature /etc/pki/mycert.pem \\\\\n signing_pub_key=/etc/pki/myca.crt\n '''\n cert = _get_certificate_obj(certificate)\n\n if signing_pub_key:\n signing_pub_key = get_public_key(signing_pub_key,\n passphrase=signing_pub_key_passphrase, asObj=True)\n\n return bool(cert.verify(pkey=signing_pub_key) == 1)\n",
"def get_pem_entry(text, pem_type=None):\n '''\n Returns a properly formatted PEM string from the input text fixing\n any whitespace or line-break issues\n\n text:\n Text containing the X509 PEM entry to be returned or path to\n a file containing the text.\n\n pem_type:\n If specified, this function will only return a pem of a certain type,\n for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_pem_entry \"-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST\"\n '''\n text = _text_or_file(text)\n # Replace encoded newlines\n text = text.replace('\\\\n', '\\n')\n\n _match = None\n\n if len(text.splitlines()) == 1 and text.startswith(\n '-----') and text.endswith('-----'):\n # mine.get returns the PEM on a single line, we fix this\n pem_fixed = []\n pem_temp = text\n while pem_temp:\n if pem_temp.startswith('-----'):\n # Grab ----(.*)---- blocks\n pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])\n pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]\n else:\n # grab base64 chunks\n if pem_temp[:64].count('-') == 0:\n pem_fixed.append(pem_temp[:64])\n pem_temp = pem_temp[64:]\n else:\n pem_fixed.append(pem_temp[:pem_temp.index('-')])\n pem_temp = pem_temp[pem_temp.index('-'):]\n text = \"\\n\".join(pem_fixed)\n\n _dregex = _make_regex('[0-9A-Z ]+')\n errmsg = 'PEM text not valid:\\n{0}'.format(text)\n if pem_type:\n _dregex = _make_regex(pem_type)\n errmsg = ('PEM does not contain a single entry of type {0}:\\n'\n '{1}'.format(pem_type, text))\n\n for _match in _dregex.finditer(text):\n if _match:\n break\n if not _match:\n raise salt.exceptions.SaltInvocationError(errmsg)\n _match_dict = _match.groupdict()\n pem_header = _match_dict['pem_header']\n proc_type = _match_dict['proc_type']\n dek_info = _match_dict['dek_info']\n pem_footer = _match_dict['pem_footer']\n pem_body = _match_dict['pem_body']\n\n # Remove all whitespace from body\n pem_body = ''.join(pem_body.split())\n\n # Generate correctly formatted pem\n ret = pem_header + '\\n'\n if proc_type:\n ret += proc_type + '\\n'\n if dek_info:\n ret += dek_info + '\\n' + '\\n'\n for i in range(0, len(pem_body), 64):\n ret += pem_body[i:i + 64] + '\\n'\n ret += pem_footer + '\\n'\n\n return salt.utils.stringutils.to_bytes(ret, encoding='ascii')\n",
"def read_certificate(certificate):\n '''\n Returns a dict containing details of a certificate. Input can be a PEM\n string or file path.\n\n certificate:\n The certificate to be read. Can be a path to a certificate file, or\n a string containing the PEM formatted text of the certificate.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.read_certificate /etc/pki/mycert.crt\n '''\n cert = _get_certificate_obj(certificate)\n\n ret = {\n # X509 Version 3 has a value of 2 in the field.\n # Version 2 has a value of 1.\n # https://tools.ietf.org/html/rfc5280#section-4.1.2.1\n 'Version': cert.get_version() + 1,\n # Get size returns in bytes. The world thinks of key sizes in bits.\n 'Key Size': cert.get_pubkey().size() * 8,\n 'Serial Number': _dec2hex(cert.get_serial_number()),\n 'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),\n 'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),\n 'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),\n 'Subject': _parse_subject(cert.get_subject()),\n 'Subject Hash': _dec2hex(cert.get_subject().as_hash()),\n 'Issuer': _parse_subject(cert.get_issuer()),\n 'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),\n 'Not Before':\n cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),\n 'Not After':\n cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),\n 'Public Key': get_public_key(cert)\n }\n\n exts = OrderedDict()\n for ext_index in range(0, cert.get_ext_count()):\n ext = cert.get_ext_at(ext_index)\n name = ext.get_name()\n val = ext.get_value()\n if ext.get_critical():\n val = 'critical ' + val\n exts[name] = val\n\n if exts:\n ret['X509v3 Extensions'] = exts\n\n return ret\n",
"def read_csr(csr):\n '''\n Returns a dict containing details of a certificate request.\n\n :depends: - OpenSSL command line tool\n\n csr:\n A path or PEM encoded string containing the CSR to read.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.read_csr /etc/pki/mycert.csr\n '''\n csr = _get_request_obj(csr)\n ret = {\n # X509 Version 3 has a value of 2 in the field.\n # Version 2 has a value of 1.\n # https://tools.ietf.org/html/rfc5280#section-4.1.2.1\n 'Version': csr.get_version() + 1,\n # Get size returns in bytes. The world thinks of key sizes in bits.\n 'Subject': _parse_subject(csr.get_subject()),\n 'Subject Hash': _dec2hex(csr.get_subject().as_hash()),\n 'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),\n 'X509v3 Extensions': _get_csr_extensions(csr),\n }\n\n return ret\n",
"def _get_signing_policy(name):\n policies = __salt__['pillar.get']('x509_signing_policies', None)\n if policies:\n signing_policy = policies.get(name)\n if signing_policy:\n return signing_policy\n return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}\n",
"def _dec2hex(decval):\n '''\n Converts decimal values to nicely formatted hex strings\n '''\n return _pretty_hex('{0:X}'.format(decval))\n",
"def _get_certificate_obj(cert):\n '''\n Returns a certificate object based on PEM text.\n '''\n if isinstance(cert, M2Crypto.X509.X509):\n return cert\n\n text = _text_or_file(cert)\n text = get_pem_entry(text, pem_type='CERTIFICATE')\n return M2Crypto.X509.load_cert_string(text)\n",
"def _get_private_key_obj(private_key, passphrase=None):\n '''\n Returns a private key object based on PEM text.\n '''\n private_key = _text_or_file(private_key)\n private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')\n rsaprivkey = M2Crypto.RSA.load_key_string(\n private_key, callback=_passphrase_callback(passphrase))\n evpprivkey = M2Crypto.EVP.PKey()\n evpprivkey.assign_rsa(rsaprivkey)\n return evpprivkey\n",
"def _get_request_obj(csr):\n '''\n Returns a CSR object based on PEM text.\n '''\n text = _text_or_file(csr)\n text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')\n return M2Crypto.X509.load_request_string(text)\n",
"def get_public_key(key, passphrase=None, asObj=False):\n '''\n Returns a string containing the public key in PEM format.\n\n key:\n A path or PEM encoded string containing a CSR, Certificate or\n Private Key from which a public key can be retrieved.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_public_key /etc/pki/mycert.cer\n '''\n\n if isinstance(key, M2Crypto.X509.X509):\n rsa = key.get_pubkey().get_rsa()\n text = b''\n else:\n text = _text_or_file(key)\n text = get_pem_entry(text)\n\n if text.startswith(b'-----BEGIN PUBLIC KEY-----'):\n if not asObj:\n return text\n bio = M2Crypto.BIO.MemoryBuffer()\n bio.write(text)\n rsa = M2Crypto.RSA.load_pub_key_bio(bio)\n\n bio = M2Crypto.BIO.MemoryBuffer()\n if text.startswith(b'-----BEGIN CERTIFICATE-----'):\n cert = M2Crypto.X509.load_cert_string(text)\n rsa = cert.get_pubkey().get_rsa()\n if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):\n csr = M2Crypto.X509.load_request_string(text)\n rsa = csr.get_pubkey().get_rsa()\n if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or\n text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):\n rsa = M2Crypto.RSA.load_key_string(\n text, callback=_passphrase_callback(passphrase))\n\n if asObj:\n evppubkey = M2Crypto.EVP.PKey()\n evppubkey.assign_rsa(rsa)\n return evppubkey\n\n rsa.save_pub_key_bio(bio)\n return bio.read_all()\n",
"def write_pem(text, path, overwrite=True, pem_type=None):\n '''\n Writes out a PEM string fixing any formatting or whitespace\n issues before writing.\n\n text:\n PEM string input to be written out.\n\n path:\n Path of the file to write the pem out to.\n\n overwrite:\n If True(default), write_pem will overwrite the entire pem file.\n Set False to preserve existing private keys and dh params that may\n exist in the pem file.\n\n pem_type:\n The PEM type to be saved, for example ``CERTIFICATE`` or\n ``PUBLIC KEY``. Adding this will allow the function to take\n input that may contain multiple pem types.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.write_pem \"-----BEGIN CERTIFICATE-----MIIGMzCCBBugA...\" path=/etc/pki/mycert.crt\n '''\n with salt.utils.files.set_umask(0o077):\n text = get_pem_entry(text, pem_type=pem_type)\n _dhparams = ''\n _private_key = ''\n if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:\n _filecontents = _text_or_file(path)\n try:\n _dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')\n except salt.exceptions.SaltInvocationError as err:\n log.debug(\"Error when getting DH PARAMETERS: %s\", err)\n log.trace(err, exc_info=err)\n try:\n _private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')\n except salt.exceptions.SaltInvocationError as err:\n log.debug(\"Error when getting PRIVATE KEY: %s\", err)\n log.trace(err, exc_info=err)\n with salt.utils.files.fopen(path, 'w') as _fp:\n if pem_type and pem_type == 'CERTIFICATE' and _private_key:\n _fp.write(salt.utils.stringutils.to_str(_private_key))\n _fp.write(salt.utils.stringutils.to_str(text))\n if pem_type and pem_type == 'CERTIFICATE' and _dhparams:\n _fp.write(salt.utils.stringutils.to_str(_dhparams))\n return 'PEM written to {0}'.format(path)\n",
"def verify_private_key(private_key, public_key, passphrase=None):\n '''\n Verify that 'private_key' matches 'public_key'\n\n private_key:\n The private key to verify, can be a string or path to a private\n key in PEM format.\n\n public_key:\n The public key to verify, can be a string or path to a PEM formatted\n certificate, csr, or another private key.\n\n passphrase:\n Passphrase to decrypt the private key.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\\\\n public_key=/etc/pki/myca.crt\n '''\n return get_public_key(private_key, passphrase) == get_public_key(public_key)\n",
"def update(*args, **kwds): # pylint: disable=E0211\n '''od.update(E, **F) -> None. Update od from dict/iterable E and F.\n\n If E is a dict instance, does: for k in E: od[k] = E[k]\n If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]\n Or if E is an iterable of items, does: for k, v in E: od[k] = v\n In either case, this is followed by: for k, v in F.items(): od[k] = v\n\n '''\n if len(args) > 2:\n raise TypeError(\n 'update() takes at most 2 positional '\n 'arguments ({0} given)'.format(len(args))\n )\n elif not args:\n raise TypeError('update() takes at least 1 argument (0 given)')\n self = args[0]\n # Make progressively weaker assumptions about \"other\"\n other = ()\n if len(args) == 2:\n other = args[1]\n if isinstance(other, dict):\n for key in other:\n self[key] = other[key]\n elif hasattr(other, 'keys'):\n for key in other:\n self[key] = other[key]\n else:\n for key, value in other:\n self[key] = value\n for key, value in six.iteritems(kwds):\n self[key] = value\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
create_csr
|
python
|
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
|
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L1589-L1704
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):\n '''\n Create new X509_Extension, This is required because M2Crypto\n doesn't support getting the publickeyidentifier from the issuer\n to create the authoritykeyidentifier extension.\n '''\n if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':\n raise salt.exceptions.SaltInvocationError('value must be precomputed hash')\n\n # ensure name and value are bytes\n name = salt.utils.stringutils.to_str(name)\n value = salt.utils.stringutils.to_str(value)\n\n try:\n ctx = M2Crypto.m2.x509v3_set_nconf()\n _fix_ctx(ctx, issuer)\n if ctx is None:\n raise MemoryError(\n 'Not enough memory when creating a new X509 extension')\n x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)\n lhash = None\n except AttributeError:\n lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member\n ctx = M2Crypto.m2.x509v3_set_conf_lhash(\n lhash) # pylint: disable=no-member\n # ctx not zeroed\n _fix_ctx(ctx, issuer)\n x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(\n lhash, ctx, name, value) # pylint: disable=no-member\n # ctx,lhash freed\n\n if x509_ext_ptr is None:\n raise M2Crypto.X509.X509Error(\n \"Cannot create X509_Extension with name '{0}' and value '{1}'\".format(name, value))\n x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)\n x509_ext.set_critical(critical)\n return x509_ext\n",
"def _get_private_key_obj(private_key, passphrase=None):\n '''\n Returns a private key object based on PEM text.\n '''\n private_key = _text_or_file(private_key)\n private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')\n rsaprivkey = M2Crypto.RSA.load_key_string(\n private_key, callback=_passphrase_callback(passphrase))\n evpprivkey = M2Crypto.EVP.PKey()\n evpprivkey.assign_rsa(rsaprivkey)\n return evpprivkey\n",
"def _get_pubkey_hash(cert):\n '''\n Returns the sha1 hash of the modulus of a public key in a cert\n Used for generating subject key identifiers\n '''\n sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()\n return _pretty_hex(sha_hash)\n",
"def get_public_key(key, passphrase=None, asObj=False):\n '''\n Returns a string containing the public key in PEM format.\n\n key:\n A path or PEM encoded string containing a CSR, Certificate or\n Private Key from which a public key can be retrieved.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_public_key /etc/pki/mycert.cer\n '''\n\n if isinstance(key, M2Crypto.X509.X509):\n rsa = key.get_pubkey().get_rsa()\n text = b''\n else:\n text = _text_or_file(key)\n text = get_pem_entry(text)\n\n if text.startswith(b'-----BEGIN PUBLIC KEY-----'):\n if not asObj:\n return text\n bio = M2Crypto.BIO.MemoryBuffer()\n bio.write(text)\n rsa = M2Crypto.RSA.load_pub_key_bio(bio)\n\n bio = M2Crypto.BIO.MemoryBuffer()\n if text.startswith(b'-----BEGIN CERTIFICATE-----'):\n cert = M2Crypto.X509.load_cert_string(text)\n rsa = cert.get_pubkey().get_rsa()\n if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):\n csr = M2Crypto.X509.load_request_string(text)\n rsa = csr.get_pubkey().get_rsa()\n if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or\n text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):\n rsa = M2Crypto.RSA.load_key_string(\n text, callback=_passphrase_callback(passphrase))\n\n if asObj:\n evppubkey = M2Crypto.EVP.PKey()\n evppubkey.assign_rsa(rsa)\n return evppubkey\n\n rsa.save_pub_key_bio(bio)\n return bio.read_all()\n",
"def write_pem(text, path, overwrite=True, pem_type=None):\n '''\n Writes out a PEM string fixing any formatting or whitespace\n issues before writing.\n\n text:\n PEM string input to be written out.\n\n path:\n Path of the file to write the pem out to.\n\n overwrite:\n If True(default), write_pem will overwrite the entire pem file.\n Set False to preserve existing private keys and dh params that may\n exist in the pem file.\n\n pem_type:\n The PEM type to be saved, for example ``CERTIFICATE`` or\n ``PUBLIC KEY``. Adding this will allow the function to take\n input that may contain multiple pem types.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.write_pem \"-----BEGIN CERTIFICATE-----MIIGMzCCBBugA...\" path=/etc/pki/mycert.crt\n '''\n with salt.utils.files.set_umask(0o077):\n text = get_pem_entry(text, pem_type=pem_type)\n _dhparams = ''\n _private_key = ''\n if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:\n _filecontents = _text_or_file(path)\n try:\n _dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')\n except salt.exceptions.SaltInvocationError as err:\n log.debug(\"Error when getting DH PARAMETERS: %s\", err)\n log.trace(err, exc_info=err)\n try:\n _private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')\n except salt.exceptions.SaltInvocationError as err:\n log.debug(\"Error when getting PRIVATE KEY: %s\", err)\n log.trace(err, exc_info=err)\n with salt.utils.files.fopen(path, 'w') as _fp:\n if pem_type and pem_type == 'CERTIFICATE' and _private_key:\n _fp.write(salt.utils.stringutils.to_str(_private_key))\n _fp.write(salt.utils.stringutils.to_str(text))\n if pem_type and pem_type == 'CERTIFICATE' and _dhparams:\n _fp.write(salt.utils.stringutils.to_str(_dhparams))\n return 'PEM written to {0}'.format(path)\n",
"def update(*args, **kwds): # pylint: disable=E0211\n '''od.update(E, **F) -> None. Update od from dict/iterable E and F.\n\n If E is a dict instance, does: for k in E: od[k] = E[k]\n If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]\n Or if E is an iterable of items, does: for k, v in E: od[k] = v\n In either case, this is followed by: for k, v in F.items(): od[k] = v\n\n '''\n if len(args) > 2:\n raise TypeError(\n 'update() takes at most 2 positional '\n 'arguments ({0} given)'.format(len(args))\n )\n elif not args:\n raise TypeError('update() takes at least 1 argument (0 given)')\n self = args[0]\n # Make progressively weaker assumptions about \"other\"\n other = ()\n if len(args) == 2:\n other = args[1]\n if isinstance(other, dict):\n for key in other:\n self[key] = other[key]\n elif hasattr(other, 'keys'):\n for key in other:\n self[key] = other[key]\n else:\n for key, value in other:\n self[key] = value\n for key, value in six.iteritems(kwds):\n self[key] = value\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
verify_signature
|
python
|
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
|
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L1732-L1761
|
[
"def _get_certificate_obj(cert):\n '''\n Returns a certificate object based on PEM text.\n '''\n if isinstance(cert, M2Crypto.X509.X509):\n return cert\n\n text = _text_or_file(cert)\n text = get_pem_entry(text, pem_type='CERTIFICATE')\n return M2Crypto.X509.load_cert_string(text)\n",
"def get_public_key(key, passphrase=None, asObj=False):\n '''\n Returns a string containing the public key in PEM format.\n\n key:\n A path or PEM encoded string containing a CSR, Certificate or\n Private Key from which a public key can be retrieved.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_public_key /etc/pki/mycert.cer\n '''\n\n if isinstance(key, M2Crypto.X509.X509):\n rsa = key.get_pubkey().get_rsa()\n text = b''\n else:\n text = _text_or_file(key)\n text = get_pem_entry(text)\n\n if text.startswith(b'-----BEGIN PUBLIC KEY-----'):\n if not asObj:\n return text\n bio = M2Crypto.BIO.MemoryBuffer()\n bio.write(text)\n rsa = M2Crypto.RSA.load_pub_key_bio(bio)\n\n bio = M2Crypto.BIO.MemoryBuffer()\n if text.startswith(b'-----BEGIN CERTIFICATE-----'):\n cert = M2Crypto.X509.load_cert_string(text)\n rsa = cert.get_pubkey().get_rsa()\n if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):\n csr = M2Crypto.X509.load_request_string(text)\n rsa = csr.get_pubkey().get_rsa()\n if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or\n text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):\n rsa = M2Crypto.RSA.load_key_string(\n text, callback=_passphrase_callback(passphrase))\n\n if asObj:\n evppubkey = M2Crypto.EVP.PKey()\n evppubkey.assign_rsa(rsa)\n return evppubkey\n\n rsa.save_pub_key_bio(bio)\n return bio.read_all()\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
verify_crl
|
python
|
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
|
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L1764-L1805
|
[
"def get_pem_entry(text, pem_type=None):\n '''\n Returns a properly formatted PEM string from the input text fixing\n any whitespace or line-break issues\n\n text:\n Text containing the X509 PEM entry to be returned or path to\n a file containing the text.\n\n pem_type:\n If specified, this function will only return a pem of a certain type,\n for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' x509.get_pem_entry \"-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST\"\n '''\n text = _text_or_file(text)\n # Replace encoded newlines\n text = text.replace('\\\\n', '\\n')\n\n _match = None\n\n if len(text.splitlines()) == 1 and text.startswith(\n '-----') and text.endswith('-----'):\n # mine.get returns the PEM on a single line, we fix this\n pem_fixed = []\n pem_temp = text\n while pem_temp:\n if pem_temp.startswith('-----'):\n # Grab ----(.*)---- blocks\n pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])\n pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]\n else:\n # grab base64 chunks\n if pem_temp[:64].count('-') == 0:\n pem_fixed.append(pem_temp[:64])\n pem_temp = pem_temp[64:]\n else:\n pem_fixed.append(pem_temp[:pem_temp.index('-')])\n pem_temp = pem_temp[pem_temp.index('-'):]\n text = \"\\n\".join(pem_fixed)\n\n _dregex = _make_regex('[0-9A-Z ]+')\n errmsg = 'PEM text not valid:\\n{0}'.format(text)\n if pem_type:\n _dregex = _make_regex(pem_type)\n errmsg = ('PEM does not contain a single entry of type {0}:\\n'\n '{1}'.format(pem_type, text))\n\n for _match in _dregex.finditer(text):\n if _match:\n break\n if not _match:\n raise salt.exceptions.SaltInvocationError(errmsg)\n _match_dict = _match.groupdict()\n pem_header = _match_dict['pem_header']\n proc_type = _match_dict['proc_type']\n dek_info = _match_dict['dek_info']\n pem_footer = _match_dict['pem_footer']\n pem_body = _match_dict['pem_body']\n\n # Remove all whitespace from body\n pem_body = ''.join(pem_body.split())\n\n # Generate correctly formatted pem\n ret = pem_header + '\\n'\n if proc_type:\n ret += proc_type + '\\n'\n if dek_info:\n ret += dek_info + '\\n' + '\\n'\n for i in range(0, len(pem_body), 64):\n ret += pem_body[i:i + 64] + '\\n'\n ret += pem_footer + '\\n'\n\n return salt.utils.stringutils.to_bytes(ret, encoding='ascii')\n",
"def _text_or_file(input_):\n '''\n Determines if input is a path to a file, or a string with the\n content to be parsed.\n '''\n if _isfile(input_):\n with salt.utils.files.fopen(input_) as fp_:\n out = salt.utils.stringutils.to_str(fp_.read())\n else:\n out = salt.utils.stringutils.to_str(input_)\n\n return out\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
expired
|
python
|
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
|
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L1808-L1846
|
[
"def _parse_subject(subject):\n '''\n Returns a dict containing all values in an X509 Subject\n '''\n ret = {}\n nids = []\n for nid_name, nid_num in six.iteritems(subject.nid):\n if nid_num in nids:\n continue\n try:\n val = getattr(subject, nid_name)\n if val:\n ret[nid_name] = val\n nids.append(nid_num)\n except TypeError as err:\n log.debug(\"Missing attribute '%s'. Error: %s\", nid_name, err)\n\n return ret\n",
"def _get_certificate_obj(cert):\n '''\n Returns a certificate object based on PEM text.\n '''\n if isinstance(cert, M2Crypto.X509.X509):\n return cert\n\n text = _text_or_file(cert)\n text = get_pem_entry(text, pem_type='CERTIFICATE')\n return M2Crypto.X509.load_cert_string(text)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/modules/x509.py
|
will_expire
|
python
|
def will_expire(certificate, days):
'''
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
'''
ts_pt = "%Y-%m-%d %H:%M:%S"
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
ret['check_days'] = days
cert = _get_certificate_obj(certificate)
_check_time = datetime.datetime.utcnow() + datetime.timedelta(days=days)
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
ret['will_expire'] = _expiration_date.strftime(ts_pt) <= _check_time.strftime(ts_pt)
except ValueError as err:
log.debug('Unable to return details of a sertificate expiration: %s', err)
log.trace(err, exc_info=True)
return ret
|
Returns a dict containing details of a certificate and whether
the certificate will expire in the specified number of days.
Input can be a PEM string or file path.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L1849-L1886
|
[
"def _parse_subject(subject):\n '''\n Returns a dict containing all values in an X509 Subject\n '''\n ret = {}\n nids = []\n for nid_name, nid_num in six.iteritems(subject.nid):\n if nid_num in nids:\n continue\n try:\n val = getattr(subject, nid_name)\n if val:\n ret[nid_name] = val\n nids.append(nid_num)\n except TypeError as err:\n log.debug(\"Missing attribute '%s'. Error: %s\", nid_name, err)\n\n return ret\n",
"def _get_certificate_obj(cert):\n '''\n Returns a certificate object based on PEM text.\n '''\n if isinstance(cert, M2Crypto.X509.X509):\n return cert\n\n text = _text_or_file(cert)\n text = get_pem_entry(text, pem_type='CERTIFICATE')\n return M2Crypto.X509.load_cert_string(text)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import logging
import hashlib
import glob
import random
import ctypes
import tempfile
import re
import datetime
import ast
import sys
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
import salt.utils.platform
import salt.exceptions
from salt.ext import six
from salt.utils.odict import OrderedDict
# pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import range
# pylint: enable=import-error,redefined-builtin
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
# Import 3rd Party Libs
try:
import M2Crypto
except ImportError:
M2Crypto = None
try:
import OpenSSL
except ImportError:
OpenSSL = None
__virtualname__ = 'x509'
log = logging.getLogger(__name__) # pylint: disable=invalid-name
EXT_NAME_MAPPINGS = OrderedDict([
('basicConstraints', 'X509v3 Basic Constraints'),
('keyUsage', 'X509v3 Key Usage'),
('extendedKeyUsage', 'X509v3 Extended Key Usage'),
('subjectKeyIdentifier', 'X509v3 Subject Key Identifier'),
('authorityKeyIdentifier', 'X509v3 Authority Key Identifier'),
('issuserAltName', 'X509v3 Issuer Alternative Name'),
('authorityInfoAccess', 'X509v3 Authority Info Access'),
('subjectAltName', 'X509v3 Subject Alternative Name'),
('crlDistributionPoints', 'X509v3 CRL Distribution Points'),
('issuingDistributionPoint', 'X509v3 Issuing Distribution Point'),
('certificatePolicies', 'X509v3 Certificate Policies'),
('policyConstraints', 'X509v3 Policy Constraints'),
('inhibitAnyPolicy', 'X509v3 Inhibit Any Policy'),
('nameConstraints', 'X509v3 Name Constraints'),
('noCheck', 'X509v3 OCSP No Check'),
('nsComment', 'Netscape Comment'),
('nsCertType', 'Netscape Certificate Type'),
])
CERT_DEFAULTS = {
'days_valid': 365,
'version': 3,
'serial_bits': 64,
'algorithm': 'sha256'
}
def __virtual__():
'''
only load this module if m2crypto is available
'''
return __virtualname__ if M2Crypto is not None else False, 'Could not load x509 module, m2crypto unavailable'
class _Ctx(ctypes.Structure):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
# pylint: disable=too-few-public-methods
_fields_ = [
('flags', ctypes.c_int),
('issuer_cert', ctypes.c_void_p),
('subject_cert', ctypes.c_void_p),
('subject_req', ctypes.c_void_p),
('crl', ctypes.c_void_p),
('db_meth', ctypes.c_void_p),
('db', ctypes.c_void_p),
]
def _fix_ctx(m2_ctx, issuer=None):
'''
This is part of an ugly hack to fix an ancient bug in M2Crypto
https://bugzilla.osafoundation.org/show_bug.cgi?id=7530#c13
'''
ctx = _Ctx.from_address(int(m2_ctx)) # pylint: disable=no-member
ctx.flags = 0
ctx.subject_cert = None
ctx.subject_req = None
ctx.crl = None
if issuer is None:
ctx.issuer_cert = None
else:
ctx.issuer_cert = int(issuer.x509)
def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
'''
Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
'''
if name == 'subjectKeyIdentifier' and value.strip('0123456789abcdefABCDEF:') is not '':
raise salt.exceptions.SaltInvocationError('value must be precomputed hash')
# ensure name and value are bytes
name = salt.utils.stringutils.to_str(name)
value = salt.utils.stringutils.to_str(value)
try:
ctx = M2Crypto.m2.x509v3_set_nconf()
_fix_ctx(ctx, issuer)
if ctx is None:
raise MemoryError(
'Not enough memory when creating a new X509 extension')
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(None, ctx, name, value)
lhash = None
except AttributeError:
lhash = M2Crypto.m2.x509v3_lhash() # pylint: disable=no-member
ctx = M2Crypto.m2.x509v3_set_conf_lhash(
lhash) # pylint: disable=no-member
# ctx not zeroed
_fix_ctx(ctx, issuer)
x509_ext_ptr = M2Crypto.m2.x509v3_ext_conf(
lhash, ctx, name, value) # pylint: disable=no-member
# ctx,lhash freed
if x509_ext_ptr is None:
raise M2Crypto.X509.X509Error(
"Cannot create X509_Extension with name '{0}' and value '{1}'".format(name, value))
x509_ext = M2Crypto.X509.X509_Extension(x509_ext_ptr, _pyfree)
x509_ext.set_critical(critical)
return x509_ext
# The next four functions are more hacks because M2Crypto doesn't support
# getting Extensions from CSRs.
# https://github.com/martinpaljak/M2Crypto/issues/63
def _parse_openssl_req(csr_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl req -text -noout -in {0}'.format(csr_filename))
output = __salt__['cmd.run_stdout'](cmd)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _parse_openssl_req(csrtempfile.name)
csrtempfile.close()
if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']
if not csrexts:
return ret
for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
if long_name in csrexts:
csrexts[short_name] = csrexts[long_name]
del csrexts[long_name]
ret = csrexts
return ret
# None of python libraries read CRLs. Again have to hack it with the
# openssl CLI
# pylint: disable=too-many-branches,too-many-locals
def _parse_openssl_crl(crl_filename):
'''
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError(
'openssl binary not found in path'
)
cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))
output = __salt__['cmd.run_stdout'](cmd)
crl = {}
for line in output.split('\n'):
line = line.strip()
if line.startswith('Version '):
crl['Version'] = line.replace('Version ', '')
if line.startswith('Signature Algorithm: '):
crl['Signature Algorithm'] = line.replace(
'Signature Algorithm: ', '')
if line.startswith('Issuer: '):
line = line.replace('Issuer: ', '')
subject = {}
for sub_entry in line.split('/'):
if '=' in sub_entry:
sub_entry = sub_entry.split('=')
subject[sub_entry[0]] = sub_entry[1]
crl['Issuer'] = subject
if line.startswith('Last Update: '):
crl['Last Update'] = line.replace('Last Update: ', '')
last_update = datetime.datetime.strptime(
crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Next Update: '):
crl['Next Update'] = line.replace('Next Update: ', '')
next_update = datetime.datetime.strptime(
crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
if line.startswith('Revoked Certificates:'):
break
if 'No Revoked Certificates.' in output:
crl['Revoked Certificates'] = []
return crl
output = output.split('Revoked Certificates:')[1]
output = output.split('Signature Algorithm:')[0]
rev = []
for revoked in output.split('Serial Number: '):
if not revoked.strip():
continue
rev_sn = revoked.split('\n')[0].strip()
revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
# pylint: disable=unused-variable
for rev_item, rev_values in six.iteritems(rev_yaml):
# pylint: enable=unused-variable
if 'Revocation Date' in rev_values:
rev_date = datetime.datetime.strptime(
rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
rev_values['Revocation Date'] = rev_date.strftime(
"%Y-%m-%d %H:%M:%S")
rev.append(rev_yaml)
crl['Revoked Certificates'] = rev
return crl
# pylint: enable=too-many-branches
def _get_signing_policy(name):
policies = __salt__['pillar.get']('x509_signing_policies', None)
if policies:
signing_policy = policies.get(name)
if signing_policy:
return signing_policy
return __salt__['config.get']('x509_signing_policies', {}).get(name) or {}
def _pretty_hex(hex_str):
'''
Nicely formats hex strings
'''
if len(hex_str) % 2 != 0:
hex_str = '0' + hex_str
return ':'.join(
[hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]).upper()
def _dec2hex(decval):
'''
Converts decimal values to nicely formatted hex strings
'''
return _pretty_hex('{0:X}'.format(decval))
def _isfile(path):
'''
A wrapper around os.path.isfile that ignores ValueError exceptions which
can be raised if the input to isfile is too long.
'''
try:
return os.path.isfile(path)
except ValueError:
pass
return False
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to_str(input_)
return out
def _parse_subject(subject):
'''
Returns a dict containing all values in an X509 Subject
'''
ret = {}
nids = []
for nid_name, nid_num in six.iteritems(subject.nid):
if nid_num in nids:
continue
try:
val = getattr(subject, nid_name)
if val:
ret[nid_name] = val
nids.append(nid_num)
except TypeError as err:
log.debug("Missing attribute '%s'. Error: %s", nid_name, err)
return ret
def _get_certificate_obj(cert):
'''
Returns a certificate object based on PEM text.
'''
if isinstance(cert, M2Crypto.X509.X509):
return cert
text = _text_or_file(cert)
text = get_pem_entry(text, pem_type='CERTIFICATE')
return M2Crypto.X509.load_cert_string(text)
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callback=_passphrase_callback(passphrase))
evpprivkey = M2Crypto.EVP.PKey()
evpprivkey.assign_rsa(rsaprivkey)
return evpprivkey
def _passphrase_callback(passphrase):
'''
Returns a callback function used to supply a passphrase for private keys
'''
def f(*args):
return salt.utils.stringutils.to_bytes(passphrase)
return f
def _get_request_obj(csr):
'''
Returns a CSR object based on PEM text.
'''
text = _text_or_file(csr)
text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
return M2Crypto.X509.load_request_string(text)
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash)
def _keygen_callback():
'''
Replacement keygen callback function which silences the output
sent to stdout by the default keygen function
'''
return
def _make_regex(pem_type):
'''
Dynamically generate a regex to match pem_type
'''
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?"
r"(?P<pem_body>.+?)\s+(?P<pem_footer>"
r"-----END {0}-----)\s*".format(pem_type),
re.DOTALL
)
def get_pem_entry(text, pem_type=None):
'''
Returns a properly formatted PEM string from the input text fixing
any whitespace or line-break issues
text:
Text containing the X509 PEM entry to be returned or path to
a file containing the text.
pem_type:
If specified, this function will only return a pem of a certain type,
for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"
'''
text = _text_or_file(text)
# Replace encoded newlines
text = text.replace('\\n', '\n')
_match = None
if len(text.splitlines()) == 1 and text.startswith(
'-----') and text.endswith('-----'):
# mine.get returns the PEM on a single line, we fix this
pem_fixed = []
pem_temp = text
while pem_temp:
if pem_temp.startswith('-----'):
# Grab ----(.*)---- blocks
pem_fixed.append(pem_temp[:pem_temp.index('-----', 5) + 5])
pem_temp = pem_temp[pem_temp.index('-----', 5) + 5:]
else:
# grab base64 chunks
if pem_temp[:64].count('-') == 0:
pem_fixed.append(pem_temp[:64])
pem_temp = pem_temp[64:]
else:
pem_fixed.append(pem_temp[:pem_temp.index('-')])
pem_temp = pem_temp[pem_temp.index('-'):]
text = "\n".join(pem_fixed)
_dregex = _make_regex('[0-9A-Z ]+')
errmsg = 'PEM text not valid:\n{0}'.format(text)
if pem_type:
_dregex = _make_regex(pem_type)
errmsg = ('PEM does not contain a single entry of type {0}:\n'
'{1}'.format(pem_type, text))
for _match in _dregex.finditer(text):
if _match:
break
if not _match:
raise salt.exceptions.SaltInvocationError(errmsg)
_match_dict = _match.groupdict()
pem_header = _match_dict['pem_header']
proc_type = _match_dict['proc_type']
dek_info = _match_dict['dek_info']
pem_footer = _match_dict['pem_footer']
pem_body = _match_dict['pem_body']
# Remove all whitespace from body
pem_body = ''.join(pem_body.split())
# Generate correctly formatted pem
ret = pem_header + '\n'
if proc_type:
ret += proc_type + '\n'
if dek_info:
ret += dek_info + '\n' + '\n'
for i in range(0, len(pem_body), 64):
ret += pem_body[i:i + 64] + '\n'
ret += pem_footer + '\n'
return salt.utils.stringutils.to_bytes(ret, encoding='ascii')
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = get_pem_entry(text=path)
except ValueError as err:
log.debug('Unable to get PEM entries from %s: %s', path, err)
return ret
def read_certificate(certificate):
'''
Returns a dict containing details of a certificate. Input can be a PEM
string or file path.
certificate:
The certificate to be read. Can be a path to a certificate file, or
a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificate /etc/pki/mycert.crt
'''
cert = _get_certificate_obj(certificate)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': cert.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Key Size': cert.get_pubkey().size() * 8,
'Serial Number': _dec2hex(cert.get_serial_number()),
'SHA-256 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha256')),
'MD5 Finger Print': _pretty_hex(cert.get_fingerprint(md='md5')),
'SHA1 Finger Print': _pretty_hex(cert.get_fingerprint(md='sha1')),
'Subject': _parse_subject(cert.get_subject()),
'Subject Hash': _dec2hex(cert.get_subject().as_hash()),
'Issuer': _parse_subject(cert.get_issuer()),
'Issuer Hash': _dec2hex(cert.get_issuer().as_hash()),
'Not Before':
cert.get_not_before().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Not After':
cert.get_not_after().get_datetime().strftime('%Y-%m-%d %H:%M:%S'),
'Public Key': get_public_key(cert)
}
exts = OrderedDict()
for ext_index in range(0, cert.get_ext_count()):
ext = cert.get_ext_at(ext_index)
name = ext.get_name()
val = ext.get_value()
if ext.get_critical():
val = 'critical ' + val
exts[name] = val
if exts:
ret['X509v3 Extensions'] = exts
return ret
def read_certificates(glob_path):
'''
Returns a dict containing details of a all certificates matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.read_certificates "/etc/pki/*.crt"
'''
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError as err:
log.debug('Unable to read certificate %s: %s', path, err)
return ret
def read_csr(csr):
'''
Returns a dict containing details of a certificate request.
:depends: - OpenSSL command line tool
csr:
A path or PEM encoded string containing the CSR to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_csr /etc/pki/mycert.csr
'''
csr = _get_request_obj(csr)
ret = {
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
'Version': csr.get_version() + 1,
# Get size returns in bytes. The world thinks of key sizes in bits.
'Subject': _parse_subject(csr.get_subject()),
'Subject Hash': _dec2hex(csr.get_subject().as_hash()),
'Public Key Hash': hashlib.sha1(csr.get_pubkey().get_modulus()).hexdigest(),
'X509v3 Extensions': _get_csr_extensions(csr),
}
return ret
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/mycrl.crl
'''
text = _text_or_file(crl)
text = get_pem_entry(text, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(text))
crltempfile.flush()
crlparsed = _parse_openssl_crl(crltempfile.name)
crltempfile.close()
return crlparsed
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer
'''
if isinstance(key, M2Crypto.X509.X509):
rsa = key.get_pubkey().get_rsa()
text = b''
else:
text = _text_or_file(key)
text = get_pem_entry(text)
if text.startswith(b'-----BEGIN PUBLIC KEY-----'):
if not asObj:
return text
bio = M2Crypto.BIO.MemoryBuffer()
bio.write(text)
rsa = M2Crypto.RSA.load_pub_key_bio(bio)
bio = M2Crypto.BIO.MemoryBuffer()
if text.startswith(b'-----BEGIN CERTIFICATE-----'):
cert = M2Crypto.X509.load_cert_string(text)
rsa = cert.get_pubkey().get_rsa()
if text.startswith(b'-----BEGIN CERTIFICATE REQUEST-----'):
csr = M2Crypto.X509.load_request_string(text)
rsa = csr.get_pubkey().get_rsa()
if (text.startswith(b'-----BEGIN PRIVATE KEY-----') or
text.startswith(b'-----BEGIN RSA PRIVATE KEY-----')):
rsa = M2Crypto.RSA.load_key_string(
text, callback=_passphrase_callback(passphrase))
if asObj:
evppubkey = M2Crypto.EVP.PKey()
evppubkey.assign_rsa(rsa)
return evppubkey
rsa.save_pub_key_bio(bio)
return bio.read_all()
def get_private_key_size(private_key, passphrase=None):
'''
Returns the bit length of a private key in PEM format.
private_key:
A path or PEM encoded string containing a private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_private_key_size /etc/pki/mycert.key
'''
return _get_private_key_obj(private_key, passphrase).size() * 8
def write_pem(text, path, overwrite=True, pem_type=None):
'''
Writes out a PEM string fixing any formatting or whitespace
issues before writing.
text:
PEM string input to be written out.
path:
Path of the file to write the pem out to.
overwrite:
If True(default), write_pem will overwrite the entire pem file.
Set False to preserve existing private keys and dh params that may
exist in the pem file.
pem_type:
The PEM type to be saved, for example ``CERTIFICATE`` or
``PUBLIC KEY``. Adding this will allow the function to take
input that may contain multiple pem types.
CLI Example:
.. code-block:: bash
salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt
'''
with salt.utils.files.set_umask(0o077):
text = get_pem_entry(text, pem_type=pem_type)
_dhparams = ''
_private_key = ''
if pem_type and pem_type == 'CERTIFICATE' and os.path.isfile(path) and not overwrite:
_filecontents = _text_or_file(path)
try:
_dhparams = get_pem_entry(_filecontents, 'DH PARAMETERS')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting DH PARAMETERS: %s", err)
log.trace(err, exc_info=err)
try:
_private_key = get_pem_entry(_filecontents, '(?:RSA )?PRIVATE KEY')
except salt.exceptions.SaltInvocationError as err:
log.debug("Error when getting PRIVATE KEY: %s", err)
log.trace(err, exc_info=err)
with salt.utils.files.fopen(path, 'w') as _fp:
if pem_type and pem_type == 'CERTIFICATE' and _private_key:
_fp.write(salt.utils.stringutils.to_str(_private_key))
_fp.write(salt.utils.stringutils.to_str(text))
if pem_type and pem_type == 'CERTIFICATE' and _dhparams:
_fp.write(salt.utils.stringutils.to_str(_dhparams))
return 'PEM written to {0}'.format(path)
def create_private_key(path=None,
text=False,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
verbose=True):
'''
Creates a private key in PEM format.
path:
The path to write the file to, either ``path`` or ``text``
are required.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
bits:
Length of the private key in bits. Default 2048
passphrase:
Passphrase for encryting the private key
cipher:
Cipher for encrypting the private key. Has no effect if passhprase is None.
verbose:
Provide visual feedback on stdout. Default True
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt '*' x509.create_private_key path=/etc/pki/mykey.key
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if verbose:
_callback_func = M2Crypto.RSA.keygen_callback
else:
_callback_func = _keygen_callback
# pylint: disable=no-member
rsa = M2Crypto.RSA.gen_key(bits, M2Crypto.m2.RSA_F4, _callback_func)
# pylint: enable=no-member
bio = M2Crypto.BIO.MemoryBuffer()
if passphrase is None:
cipher = None
rsa.save_key_bio(
bio,
cipher=cipher,
callback=_passphrase_callback(passphrase))
if path:
return write_pem(
text=bio.read_all(),
path=path,
pem_type='(?:RSA )?PRIVATE KEY'
)
else:
return salt.utils.stringutils.to_str(bio.read_all())
def create_crl( # pylint: disable=too-many-arguments,too-many-locals
path=None, text=False, signing_private_key=None,
signing_private_key_passphrase=None,
signing_cert=None, revoked=None, include_expired=False,
days_valid=100, digest=''):
'''
Create a CRL
:depends: - PyOpenSSL Python module
path:
Path to write the crl to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this crl. This is required.
signing_private_key_passphrase:
Passphrase to decrypt the private key.
signing_cert:
A certificate matching the private key that will be used to sign
this crl. This is required.
revoked:
A list of dicts containing all the certificates to revoke. Each dict
represents one certificate. A dict must contain either the key
``serial_number`` with the value of the serial number to revoke, or
``certificate`` with either the PEM encoded text of the certificate,
or a path to the certificate to revoke.
The dict can optionally contain the ``revocation_date`` key. If this
key is omitted the revocation date will be set to now. If should be a
string in the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``not_after`` key. This is
redundant if the ``certificate`` key is included. If the
``Certificate`` key is not included, this can be used for the logic
behind the ``include_expired`` parameter. If should be a string in
the format "%Y-%m-%d %H:%M:%S".
The dict can also optionally contain the ``reason`` key. This is the
reason code for the revocation. Available choices are ``unspecified``,
``keyCompromise``, ``CACompromise``, ``affiliationChanged``,
``superseded``, ``cessationOfOperation`` and ``certificateHold``.
include_expired:
Include expired certificates in the CRL. Default is ``False``.
days_valid:
The number of days that the CRL should be valid. This sets the Next
Update field in the CRL.
digest:
The digest to use for signing the CRL.
This has no effect on versions of pyOpenSSL less than 0.14
.. note
At this time the pyOpenSSL library does not allow choosing a signing
algorithm for CRLs See https://github.com/pyca/pyopenssl/issues/159
CLI Example:
.. code-block:: bash
salt '*' x509.create_crl path=/etc/pki/mykey.key signing_private_key=/etc/pki/ca.key signing_cert=/etc/pki/ca.crt revoked="{'compromized-web-key': {'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}}"
'''
# pyOpenSSL is required for dealing with CSLs. Importing inside these
# functions because Client operations like creating CRLs shouldn't require
# pyOpenSSL Note due to current limitations in pyOpenSSL it is impossible
# to specify a digest For signing the CRL. This will hopefully be fixed
# soon: https://github.com/pyca/pyopenssl/pull/161
if OpenSSL is None:
raise salt.exceptions.SaltInvocationError(
'Could not load OpenSSL module, OpenSSL unavailable'
)
crl = OpenSSL.crypto.CRL()
if revoked is None:
revoked = []
for rev_item in revoked:
if 'certificate' in rev_item:
rev_cert = read_certificate(rev_item['certificate'])
rev_item['serial_number'] = rev_cert['Serial Number']
rev_item['not_after'] = rev_cert['Not After']
serial_number = rev_item['serial_number'].replace(':', '')
# OpenSSL bindings requires this to be a non-unicode string
serial_number = salt.utils.stringutils.to_bytes(serial_number)
if 'not_after' in rev_item and not include_expired:
not_after = datetime.datetime.strptime(
rev_item['not_after'], '%Y-%m-%d %H:%M:%S')
if datetime.datetime.now() > not_after:
continue
if 'revocation_date' not in rev_item:
rev_item['revocation_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rev_date = datetime.datetime.strptime(
rev_item['revocation_date'], '%Y-%m-%d %H:%M:%S')
rev_date = rev_date.strftime('%Y%m%d%H%M%SZ')
rev_date = salt.utils.stringutils.to_bytes(rev_date)
rev = OpenSSL.crypto.Revoked()
rev.set_serial(salt.utils.stringutils.to_bytes(serial_number))
rev.set_rev_date(salt.utils.stringutils.to_bytes(rev_date))
if 'reason' in rev_item:
# Same here for OpenSSL bindings and non-unicode strings
reason = salt.utils.stringutils.to_str(rev_item['reason'])
rev.set_reason(reason)
crl.add_revoked(rev)
signing_cert = _text_or_file(signing_cert)
cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_cert, pem_type='CERTIFICATE'))
signing_private_key = _get_private_key_obj(signing_private_key,
passphrase=signing_private_key_passphrase).as_pem(cipher=None)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
get_pem_entry(signing_private_key))
export_kwargs = {
'cert': cert,
'key': key,
'type': OpenSSL.crypto.FILETYPE_PEM,
'days': days_valid
}
if digest:
export_kwargs['digest'] = salt.utils.stringutils.to_bytes(digest)
else:
log.warning('No digest specified. The default md5 digest will be used.')
try:
crltext = crl.export(**export_kwargs)
except (TypeError, ValueError):
log.warning('Error signing crl with specified digest. '
'Are you using pyopenssl 0.15 or newer? '
'The default md5 digest will be used.')
export_kwargs.pop('digest', None)
crltext = crl.export(**export_kwargs)
if text:
return crltext
return write_pem(text=crltext, path=path, pem_type='X509 CRL')
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
kwargs:
kwargs delivered from publish.publish
CLI Example:
.. code-block:: bash
salt '*' x509.sign_remote_certificate argdic="{'public_key': '/etc/pki/www.key', 'signing_policy': 'www'}" __pub_id='www1'
'''
if 'signing_policy' not in argdic:
return 'signing_policy must be specified'
if not isinstance(argdic, dict):
argdic = ast.literal_eval(argdic)
signing_policy = {}
if 'signing_policy' in argdic:
signing_policy = _get_signing_policy(argdic['signing_policy'])
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(argdic['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
if 'minions' in signing_policy:
if '__pub_id' not in kwargs:
return 'minion sending this request could not be identified'
matcher = 'match.glob'
if '@' in signing_policy['minions']:
matcher = 'match.compound'
if not __salt__[matcher](
signing_policy['minions'], kwargs['__pub_id']):
return '{0} not permitted to use signing policy {1}'.format(
kwargs['__pub_id'], argdic['signing_policy'])
try:
return create_certificate(path=None, text=True, **argdic)
except Exception as except_: # pylint: disable=broad-except
return six.text_type(except_)
def get_signing_policy(signing_policy_name):
'''
Returns the details of a names signing policy, including the text of
the public key that will be used to sign it. Does not return the
private key.
CLI Example:
.. code-block:: bash
salt '*' x509.get_signing_policy www
'''
signing_policy = _get_signing_policy(signing_policy_name)
if not signing_policy:
return 'Signing policy {0} does not exist.'.format(signing_policy_name)
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
try:
del signing_policy['signing_private_key']
except KeyError:
pass
try:
signing_policy['signing_cert'] = get_pem_entry(signing_policy['signing_cert'], 'CERTIFICATE')
except KeyError:
log.debug('Unable to get "certificate" PEM entry')
return signing_policy
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existing private keys and dh params that
may exist in the pem file.
kwargs:
Any of the properties below can be included as additional
keyword arguments.
ca_server:
Request a remotely signed certificate from ca_server. For this to
work, a ``signing_policy`` must be specified, and that same policy
must be configured on the ca_server (name or list of ca server). See ``signing_policy`` for
details. Also the salt master must permit peers to call the
``sign_remote_certificate`` function.
Example:
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
subject properties:
Any of the values below can be included to set subject properties
Any other subject properties supported by OpenSSL should also work.
C:
2 letter Country code
CN:
Certificate common name, typically the FQDN.
Email:
Email address
GN:
Given Name
L:
Locality
O:
Organization
OU:
Organization Unit
SN:
SurName
ST:
State or Province
signing_private_key:
A path or string of the private key in PEM format that will be used
to sign this certificate. If neither ``signing_cert``, ``public_key``,
or ``csr`` are included, it will be assumed that this is a self-signed
certificate, and the public key matching ``signing_private_key`` will
be used to create the certificate.
signing_private_key_passphrase:
Passphrase used to decrypt the signing_private_key.
signing_cert:
A certificate matching the private key that will be used to sign this
certificate. This is used to populate the issuer values in the
resulting certificate. Do not include this value for
self-signed certificates.
public_key:
The public key to be included in this certificate. This can be sourced
from a public key, certificate, csr or private key. If a private key
is used, the matching public key from the private key will be
generated before any processing is done. This means you can request a
certificate from a remote CA using a private key file as your
public_key and only the public key will be sent across the network to
the CA. If neither ``public_key`` or ``csr`` are specified, it will be
assumed that this is a self-signed certificate, and the public key
derived from ``signing_private_key`` will be used. Specify either
``public_key`` or ``csr``, not both. Because you can input a CSR as a
public key or as a CSR, it is important to understand the difference.
If you import a CSR as a public key, only the public key will be added
to the certificate, subject or extension information in the CSR will
be lost.
public_key_passphrase:
If the public key is supplied as a private key, this is the passphrase
used to decrypt it.
csr:
A file or PEM string containing a certificate signing request. This
will be used to supply the subject, extensions and public key of a
certificate. Any subject or extensions specified explicitly will
overwrite any in the CSR.
basicConstraints:
X509v3 Basic Constraints extension.
extensions:
The following arguments set X509v3 Extension values. If the value
starts with ``critical``, the extension will be marked as critical.
Some special extensions are ``subjectKeyIdentifier`` and
``authorityKeyIdentifier``.
``subjectKeyIdentifier`` can be an explicit value or it can be the
special string ``hash``. ``hash`` will set the subjectKeyIdentifier
equal to the SHA1 hash of the modulus of the public key in this
certificate. Note that this is not the exact same hashing method used
by OpenSSL when using the hash value.
``authorityKeyIdentifier`` Use values acceptable to the openssl CLI
tools. This will automatically populate ``authorityKeyIdentifier``
with the ``subjectKeyIdentifier`` of ``signing_cert``. If this is a
self-signed cert these values will be the same.
basicConstraints:
X509v3 Basic Constraints
keyUsage:
X509v3 Key Usage
extendedKeyUsage:
X509v3 Extended Key Usage
subjectKeyIdentifier:
X509v3 Subject Key Identifier
issuerAltName:
X509v3 Issuer Alternative Name
subjectAltName:
X509v3 Subject Alternative Name
crlDistributionPoints:
X509v3 CRL distribution points
issuingDistributionPoint:
X509v3 Issuing Distribution Point
certificatePolicies:
X509v3 Certificate Policies
policyConstraints:
X509v3 Policy Constraints
inhibitAnyPolicy:
X509v3 Inhibit Any Policy
nameConstraints:
X509v3 Name Constraints
noCheck:
X509v3 OCSP No Check
nsComment:
Netscape Comment
nsCertType:
Netscape Certificate Type
days_valid:
The number of days this certificate should be valid. This sets the
``notAfter`` property of the certificate. Defaults to 365.
version:
The version of the X509 certificate. Defaults to 3. This is
automatically converted to the version value, so ``version=3``
sets the certificate version field to 0x2.
serial_number:
The serial number to assign to this certificate. If omitted a random
serial number of size ``serial_bits`` is generated.
serial_bits:
The number of bits to use when randomly generating a serial number.
Defaults to 64.
algorithm:
The hashing algorithm to be used for signing this certificate.
Defaults to sha256.
copypath:
An additional path to copy the resulting certificate to. Can be used
to maintain a copy of all certificates issued for revocation purposes.
prepend_cn:
If set to True, the CN and a dash will be prepended to the copypath's filename.
Example:
/etc/pki/issued_certs/www.example.com-DE:CA:FB:AD:00:00:00:00.crt
signing_policy:
A signing policy that should be used to create this certificate.
Signing policies should be defined in the minion configuration, or in
a minion pillar. It should be a yaml formatted list of arguments
which will override any arguments passed to this function. If the
``minions`` key is included in the signing policy, only minions
matching that pattern (see match.glob and match.compound) will be
permitted to remotely request certificates from that policy.
Example:
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www*'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
The above signing policy can be invoked with ``signing_policy=www``
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_certificate path=/etc/pki/myca.crt signing_private_key='/etc/pki/myca.key' csr='/etc/pki/myca.csr'}
'''
if not path and not text and ('testrun' not in kwargs or kwargs['testrun'] is False):
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if ca_server:
if 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified'
'if requesting remote certificate from ca_server {0}.'
.format(ca_server))
if 'csr' in kwargs:
kwargs['csr'] = get_pem_entry(
kwargs['csr'],
pem_type='CERTIFICATE REQUEST').replace('\n', '')
if 'public_key' in kwargs:
# Strip newlines to make passing through as cli functions easier
kwargs['public_key'] = salt.utils.stringutils.to_str(get_public_key(
kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'])).replace('\n', '')
# Remove system entries in kwargs
# Including listen_in and preqreuired because they are not included
# in STATE_INTERNAL_KEYWORDS
# for salt 2014.7.2
for ignore in list(_STATE_INTERNAL_KEYWORDS) + ['listen_in', 'preqrequired', '__prerequired__']:
kwargs.pop(ignore, None)
if not isinstance(ca_server, list):
ca_server = [ca_server]
random.shuffle(ca_server)
for server in ca_server:
certs = __salt__['publish.publish'](
tgt=server,
fun='x509.sign_remote_certificate',
arg=six.text_type(kwargs))
if certs is None or not any(certs):
continue
else:
cert_txt = certs[server]
break
if not any(certs):
raise salt.exceptions.SaltInvocationError(
'ca_server did not respond'
' salt master must permit peers to'
' call the sign_remote_certificate function.')
if path:
return write_pem(
text=cert_txt,
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return cert_txt
signing_policy = {}
if 'signing_policy' in kwargs:
signing_policy = _get_signing_policy(kwargs['signing_policy'])
if isinstance(signing_policy, list):
dict_ = {}
for item in signing_policy:
dict_.update(item)
signing_policy = dict_
# Overwrite any arguments in kwargs with signing_policy
kwargs.update(signing_policy)
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
cert = M2Crypto.X509.X509()
# X509 Version 3 has a value of 2 in the field.
# Version 2 has a value of 1.
# https://tools.ietf.org/html/rfc5280#section-4.1.2.1
cert.set_version(kwargs['version'] - 1)
# Random serial number if not specified
if 'serial_number' not in kwargs:
kwargs['serial_number'] = _dec2hex(
random.getrandbits(kwargs['serial_bits']))
serial_number = int(kwargs['serial_number'].replace(':', ''), 16)
# With Python3 we occasionally end up with an INT that is greater than a C
# long max_value. This causes an overflow error due to a bug in M2Crypto.
# See issue: https://gitlab.com/m2crypto/m2crypto/issues/232
# Remove this after M2Crypto fixes the bug.
if six.PY3:
if salt.utils.platform.is_windows():
INT_MAX = 2147483647
if serial_number >= INT_MAX:
serial_number -= int(serial_number / INT_MAX) * INT_MAX
else:
if serial_number >= sys.maxsize:
serial_number -= int(serial_number / sys.maxsize) * sys.maxsize
cert.set_serial_number(serial_number)
# Set validity dates
# pylint: disable=no-member
not_before = M2Crypto.m2.x509_get_not_before(cert.x509)
not_after = M2Crypto.m2.x509_get_not_after(cert.x509)
M2Crypto.m2.x509_gmtime_adj(not_before, 0)
M2Crypto.m2.x509_gmtime_adj(not_after, 60 * 60 * 24 * kwargs['days_valid'])
# pylint: enable=no-member
# If neither public_key or csr are included, this cert is self-signed
if 'public_key' not in kwargs and 'csr' not in kwargs:
kwargs['public_key'] = kwargs['signing_private_key']
if 'signing_private_key_passphrase' in kwargs:
kwargs['public_key_passphrase'] = kwargs[
'signing_private_key_passphrase']
csrexts = {}
if 'csr' in kwargs:
kwargs['public_key'] = kwargs['csr']
csr = _get_request_obj(kwargs['csr'])
cert.set_subject(csr.get_subject())
csrexts = read_csr(kwargs['csr'])['X509v3 Extensions']
cert.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
subject = cert.get_subject()
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'signing_cert' in kwargs:
signing_cert = _get_certificate_obj(kwargs['signing_cert'])
else:
signing_cert = cert
cert.set_issuer(signing_cert.get_subject())
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if (extname in kwargs or extlongname in kwargs or
extname in csrexts or extlongname in csrexts) is False:
continue
# Use explicitly set values first, fall back to CSR values.
extval = kwargs.get(extname) or kwargs.get(extlongname) or csrexts.get(extname) or csrexts.get(extlongname)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(cert))
issuer = None
if extname == 'authorityKeyIdentifier':
issuer = signing_cert
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
cert.add_ext(ext)
if 'signing_private_key_passphrase' not in kwargs:
kwargs['signing_private_key_passphrase'] = None
if 'testrun' in kwargs and kwargs['testrun'] is True:
cert_props = read_certificate(cert)
cert_props['Issuer Public Key'] = get_public_key(
kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase'])
return cert_props
if not verify_private_key(private_key=kwargs['signing_private_key'],
passphrase=kwargs[
'signing_private_key_passphrase'],
public_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'signing_private_key: {0} '
'does no match signing_cert: {1}'.format(
kwargs['signing_private_key'],
kwargs.get('signing_cert', '')
)
)
cert.sign(
_get_private_key_obj(kwargs['signing_private_key'],
passphrase=kwargs['signing_private_key_passphrase']),
kwargs['algorithm']
)
if not verify_signature(cert, signing_pub_key=signing_cert):
raise salt.exceptions.SaltInvocationError(
'failed to verify certificate signature')
if 'copypath' in kwargs:
if 'prepend_cn' in kwargs and kwargs['prepend_cn'] is True:
prepend = six.text_type(kwargs['CN']) + '-'
else:
prepend = ''
write_pem(text=cert.as_pem(), path=os.path.join(kwargs['copypath'],
prepend + kwargs['serial_number'] + '.crt'),
pem_type='CERTIFICATE')
if path:
return write_pem(
text=cert.as_pem(),
overwrite=overwrite,
path=path,
pem_type='CERTIFICATE'
)
else:
return salt.utils.stringutils.to_str(cert.as_pem())
# pylint: enable=too-many-locals
def create_csr(path=None, text=False, **kwargs):
'''
Create a certificate signing request.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
algorithm:
The hashing algorithm to be used for signing this request. Defaults to sha256.
kwargs:
The subject, extension and version arguments from
:mod:`x509.create_certificate <salt.modules.x509.create_certificate>`
can be used.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
CLI Example:
.. code-block:: bash
salt '*' x509.create_csr path=/etc/pki/myca.csr public_key='/etc/pki/myca.key' CN='My Cert'
'''
if not path and not text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified.')
if path and text:
raise salt.exceptions.SaltInvocationError(
'Either path or text must be specified, not both.')
csr = M2Crypto.X509.Request()
subject = csr.get_subject()
for prop, default in six.iteritems(CERT_DEFAULTS):
if prop not in kwargs:
kwargs[prop] = default
csr.set_version(kwargs['version'] - 1)
if 'private_key' not in kwargs and 'public_key' in kwargs:
kwargs['private_key'] = kwargs['public_key']
log.warning("OpenSSL no longer allows working with non-signed CSRs. "
"A private_key must be specified. Attempting to use public_key as private_key")
if 'private_key' not in kwargs:
raise salt.exceptions.SaltInvocationError('private_key is required')
if 'public_key' not in kwargs:
kwargs['public_key'] = kwargs['private_key']
if 'private_key_passphrase' not in kwargs:
kwargs['private_key_passphrase'] = None
if 'public_key_passphrase' not in kwargs:
kwargs['public_key_passphrase'] = None
if kwargs['public_key_passphrase'] and not kwargs['private_key_passphrase']:
kwargs['private_key_passphrase'] = kwargs['public_key_passphrase']
if kwargs['private_key_passphrase'] and not kwargs['public_key_passphrase']:
kwargs['public_key_passphrase'] = kwargs['private_key_passphrase']
csr.set_pubkey(get_public_key(kwargs['public_key'],
passphrase=kwargs['public_key_passphrase'], asObj=True))
# pylint: disable=unused-variable
for entry, num in six.iteritems(subject.nid):
if entry in kwargs:
setattr(subject, entry, kwargs[entry])
# pylint: enable=unused-variable
if 'ext_mapping' in kwargs:
EXT_NAME_MAPPINGS.update(kwargs['ext_mapping'])
extstack = M2Crypto.X509.X509_Extension_Stack()
for extname, extlongname in six.iteritems(EXT_NAME_MAPPINGS):
if extname not in kwargs and extlongname not in kwargs:
continue
extval = kwargs.get(extname, None) or kwargs.get(extlongname, None)
critical = False
if extval.startswith('critical '):
critical = True
extval = extval[9:]
if extname == 'subjectKeyIdentifier' and 'hash' in extval:
extval = extval.replace('hash', _get_pubkey_hash(csr))
if extname == 'subjectAltName':
extval = extval.replace('IP Address', 'IP')
if extname == 'authorityKeyIdentifier':
continue
issuer = None
ext = _new_extension(
name=extname, value=extval, critical=critical, issuer=issuer)
if not ext.x509_ext:
log.info('Invalid X509v3 Extension. %s: %s', extname, extval)
continue
extstack.push(ext)
csr.add_extensions(extstack)
csr.sign(_get_private_key_obj(kwargs['private_key'],
passphrase=kwargs['private_key_passphrase']), kwargs['algorithm'])
return write_pem(text=csr.as_pem(), path=path, pem_type='CERTIFICATE REQUEST') if path else csr.as_pem()
def verify_private_key(private_key, public_key, passphrase=None):
'''
Verify that 'private_key' matches 'public_key'
private_key:
The private key to verify, can be a string or path to a private
key in PEM format.
public_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or another private key.
passphrase:
Passphrase to decrypt the private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_private_key private_key=/etc/pki/myca.key \\
public_key=/etc/pki/myca.crt
'''
return get_public_key(private_key, passphrase) == get_public_key(public_key)
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or private key.
signing_pub_key_passphrase:
Passphrase to the signing_pub_key if it is an encrypted private key.
CLI Example:
.. code-block:: bash
salt '*' x509.verify_signature /etc/pki/mycert.pem \\
signing_pub_key=/etc/pki/myca.crt
'''
cert = _get_certificate_obj(certificate)
if signing_pub_key:
signing_pub_key = get_public_key(signing_pub_key,
passphrase=signing_pub_key_passphrase, asObj=True)
return bool(cert.verify(pkey=signing_pub_key) == 1)
def verify_crl(crl, cert):
'''
Validate a CRL against a certificate.
Parses openssl command line output, this is a workaround for M2Crypto's
inability to get them from CSR objects.
crl:
The CRL to verify
cert:
The certificate to verify the CRL against
CLI Example:
.. code-block:: bash
salt '*' x509.verify_crl crl=/etc/pki/myca.crl cert=/etc/pki/myca.crt
'''
if not salt.utils.path.which('openssl'):
raise salt.exceptions.SaltInvocationError('External command "openssl" not found')
crltext = _text_or_file(crl)
crltext = get_pem_entry(crltext, pem_type='X509 CRL')
crltempfile = tempfile.NamedTemporaryFile()
crltempfile.write(salt.utils.stringutils.to_str(crltext))
crltempfile.flush()
certtext = _text_or_file(cert)
certtext = get_pem_entry(certtext, pem_type='CERTIFICATE')
certtempfile = tempfile.NamedTemporaryFile()
certtempfile.write(salt.utils.stringutils.to_str(certtext))
certtempfile.flush()
cmd = ('openssl crl -noout -in {0} -CAfile {1}'.format(
crltempfile.name, certtempfile.name))
output = __salt__['cmd.run_stderr'](cmd)
crltempfile.close()
certtempfile.close()
return 'verify OK' in output
def expired(certificate):
'''
Returns a dict containing limited details of a
certificate and whether the certificate has expired.
.. versionadded:: 2016.11.0
certificate:
The certificate to be read. Can be a path to a certificate file,
or a string containing the PEM formatted text of the certificate.
CLI Example:
.. code-block:: bash
salt '*' x509.expired "/etc/pki/mycert.crt"
'''
ret = {}
if os.path.isfile(certificate):
try:
ret['path'] = certificate
cert = _get_certificate_obj(certificate)
_now = datetime.datetime.utcnow()
_expiration_date = cert.get_not_after().get_datetime()
ret['cn'] = _parse_subject(cert.get_subject())['CN']
if _expiration_date.strftime("%Y-%m-%d %H:%M:%S") <= \
_now.strftime("%Y-%m-%d %H:%M:%S"):
ret['expired'] = True
else:
ret['expired'] = False
except ValueError as err:
log.debug('Failed to get data of expired certificate: %s', err)
log.trace(err, exc_info=True)
return ret
|
saltstack/salt
|
salt/pillar/django_orm.py
|
ext_pillar
|
python
|
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
pillar_name,
project_path,
settings_module,
django_app,
env=None,
env_file=None,
*args, # pylint: disable=W0613
**kwargs): # pylint: disable=W0613
'''
Connect to a Django database through the ORM and retrieve model fields
:type pillar_name: str
:param pillar_name: The name of the pillar to be returned
:type project_path: str
:param project_path: The full path to your Django project (the directory
manage.py is in)
:type settings_module: str
:param settings_module: The settings module for your project. This can be
found in your manage.py file
:type django_app: str
:param django_app: A dictionary containing your apps, models, and fields
:type env: str
:param env: The full path to the virtualenv for your Django project
:type env_file: str
:param env_file: An optional bash file that sets up your environment. The
file is run in a subprocess and the changed variables are then added
'''
if not os.path.isdir(project_path):
log.error('Django project dir: \'%s\' not a directory!', project_path)
return {}
if HAS_VIRTUALENV and env is not None and os.path.isdir(env):
for path in virtualenv.path_locations(env):
if not os.path.isdir(path):
log.error('Virtualenv %s not a directory!', path)
return {}
# load the virtualenv first
sys.path.insert(0,
os.path.join(
virtualenv.path_locations(env)[1],
'site-packages'))
# load the django project
sys.path.append(project_path)
os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
if env_file is not None:
import subprocess
base_env = {}
proc = subprocess.Popen(['bash', '-c', 'env'], stdout=subprocess.PIPE)
for line in proc.stdout:
(key, _, value) = salt.utils.stringutils.to_str(line).partition('=')
base_env[key] = value
command = ['bash', '-c', 'source {0} && env'.format(env_file)]
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
for line in proc.stdout:
(key, _, value) = salt.utils.stringutils.to_str(line).partition('=')
# only add a key if it is different or doesn't already exist
if key not in base_env or base_env[key] != value:
os.environ[key] = value.rstrip('\n')
log.debug('Adding %s = %s to Django environment', key, value.rstrip('\n'))
try:
from django.db.models.loading import get_model
django_pillar = {}
for proj_app, models in six.iteritems(django_app):
_, _, app = proj_app.rpartition('.')
django_pillar[app] = {}
for model_name, model_meta in six.iteritems(models):
model_orm = get_model(app, model_name)
if model_orm is None:
raise salt.exceptions.SaltException(
"Django model '{0}' not found in app '{1}'."
.format(app, model_name))
pillar_for_model = django_pillar[app][model_orm.__name__] = {}
name_field = model_meta['name']
fields = model_meta['fields']
if 'filter' in model_meta:
qs = (model_orm.objects
.filter(**model_meta['filter'])
.values(*fields))
else:
qs = model_orm.objects.values(*fields)
for model in qs:
# Check that the human-friendly name given is valid (will
# be able to pick up a value from the query) and unique
# (since we're using it as the key in a dictionary)
if name_field not in model:
raise salt.exceptions.SaltException(
"Name '{0}' not found in returned fields.".format(
name_field))
if model[name_field] in pillar_for_model:
raise salt.exceptions.SaltException(
"Value for '{0}' is not unique: {0}".format(
model[name_field]))
pillar_for_model[model[name_field]] = model
return {pillar_name: django_pillar}
except ImportError as e:
log.error('Failed to import library: %s', e)
return {}
except Exception as e:
log.error('Failed on Error: %s', e)
log.debug('django_orm traceback', exc_info=True)
return {}
|
Connect to a Django database through the ORM and retrieve model fields
:type pillar_name: str
:param pillar_name: The name of the pillar to be returned
:type project_path: str
:param project_path: The full path to your Django project (the directory
manage.py is in)
:type settings_module: str
:param settings_module: The settings module for your project. This can be
found in your manage.py file
:type django_app: str
:param django_app: A dictionary containing your apps, models, and fields
:type env: str
:param env: The full path to the virtualenv for your Django project
:type env_file: str
:param env_file: An optional bash file that sets up your environment. The
file is run in a subprocess and the changed variables are then added
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/django_orm.py#L120-L243
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\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"
] |
# -*- coding: utf-8 -*-
'''
Generate Pillar data from Django models through the Django ORM
:maintainer: Micah Hausler <micah.hausler@gmail.com>
:maturity: new
Configuring the django_orm ext_pillar
=====================================
To use this module, your Django project must be on the salt master server with
database access. This assumes you are using virtualenv with all the project's
requirements installed.
.. code-block:: yaml
ext_pillar:
- django_orm:
pillar_name: my_application
project_path: /path/to/project/
settings_module: my_application.settings
env_file: /path/to/env/file.sh
# Optional: If your project is not using the system python,
# add your virtualenv path below.
env: /path/to/virtualenv/
django_app:
# Required: the app that is included in INSTALLED_APPS
my_application.clients:
# Required: the model name
Client:
# Required: model field to use as the key in the rendered
# Pillar. Must be unique; must also be included in the
# ``fields`` list below.
name: shortname
# Optional:
# See Django's QuerySet documentation for how to use .filter()
filter: {'kw': 'args'}
# Required: a list of field names
# List items will be used as arguments to the .values() method.
# See Django's QuerySet documentation for how to use .values()
fields:
- field_1
- field_2
This would return pillar data that would look like
.. code-block:: yaml
my_application:
my_application.clients:
Client:
client_1:
field_1: data_from_field_1
field_2: data_from_field_2
client_2:
field_1: data_from_field_1
field_2: data_from_field_2
As another example, data from multiple database tables can be fetched using
Django's regular lookup syntax. Note, using ManyToManyFields will not currently
work since the return from values() changes if a ManyToMany is present.
.. code-block:: yaml
ext_pillar:
- django_orm:
pillar_name: djangotutorial
project_path: /path/to/mysite
settings_module: mysite.settings
django_app:
mysite.polls:
Choices:
name: poll__question
fields:
- poll__question
- poll__id
- choice_text
- votes
Module Documentation
====================
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import sys
import salt.exceptions
from salt.ext import six
import salt.utils.stringutils
HAS_VIRTUALENV = False
try:
import virtualenv
HAS_VIRTUALENV = True
except ImportError:
pass
log = logging.getLogger(__name__)
def __virtual__():
'''
Always load
'''
return True
|
saltstack/salt
|
salt/modules/smartos_virt.py
|
list_domains
|
python
|
def list_domains():
'''
Return a list of virtual machine names on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_domains
'''
data = __salt__['vmadm.list'](keyed=True)
vms = ["UUID TYPE RAM STATE ALIAS"]
for vm in data:
vms.append("{vmuuid}{vmtype}{vmram}{vmstate}{vmalias}".format(
vmuuid=vm.ljust(38),
vmtype=data[vm]['type'].ljust(6),
vmram=data[vm]['ram'].ljust(9),
vmstate=data[vm]['state'].ljust(18),
vmalias=data[vm]['alias'],
))
return vms
|
Return a list of virtual machine names on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_domains
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_virt.py#L49-L69
| null |
# -*- coding: utf-8 -*-
'''
virst compatibility module for managing VMs on SmartOS
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'virt'
def __virtual__():
'''
Provides virt on SmartOS
'''
if salt.utils.platform.is_smartos_globalzone() \
and salt.utils.path.which('vmadm'):
return __virtualname__
return (
False,
'{0} module can only be loaded on SmartOS compute nodes'.format(
__virtualname__
)
)
def init(**kwargs):
'''
Initialize a new VM
CLI Example:
.. code-block:: bash
salt '*' virt.init image_uuid='...' alias='...' [...]
'''
return __salt__['vmadm.create'](**kwargs)
def list_active_vms():
'''
Return a list of uuids for active virtual machine on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_active_vms
'''
return __salt__['vmadm.list'](search="state='running'", order='uuid')
def list_inactive_vms():
'''
Return a list of uuids for inactive virtual machine on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_inactive_vms
'''
return __salt__['vmadm.list'](search="state='stopped'", order='uuid')
def vm_info(domain):
'''
Return a dict with information about the specified VM on this CN
CLI Example:
.. code-block:: bash
salt '*' virt.vm_info <domain>
'''
return __salt__['vmadm.get'](domain)
def start(domain):
'''
Start a defined domain
CLI Example:
.. code-block:: bash
salt '*' virt.start <domain>
'''
if domain in list_active_vms():
raise CommandExecutionError('The specified vm is already running')
__salt__['vmadm.start'](domain)
return domain in list_active_vms()
def shutdown(domain):
'''
Send a soft shutdown signal to the named vm
CLI Example:
.. code-block:: bash
salt '*' virt.shutdown <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is already stopped')
__salt__['vmadm.stop'](domain)
return domain in list_inactive_vms()
def reboot(domain):
'''
Reboot a domain via ACPI request
CLI Example:
.. code-block:: bash
salt '*' virt.reboot <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is stopped')
__salt__['vmadm.reboot'](domain)
return domain in list_active_vms()
def stop(domain):
'''
Hard power down the virtual machine, this is equivalent to powering off the hardware.
CLI Example:
.. code-block:: bash
salt '*' virt.destroy <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is stopped')
return __salt__['vmadm.delete'](domain)
def vm_virt_type(domain):
'''
Return VM virtualization type : OS or KVM
CLI Example:
.. code-block:: bash
salt '*' virt.vm_virt_type <domain>
'''
ret = __salt__['vmadm.lookup'](search="uuid={uuid}".format(uuid=domain), order='type')
if not ret:
raise CommandExecutionError("We can't determine the type of this VM")
return ret[0]['type']
def setmem(domain, memory):
'''
Change the amount of memory allocated to VM.
<memory> is to be specified in MB.
Note for KVM : this would require a restart of the VM.
CLI Example:
.. code-block:: bash
salt '*' virt.setmem <domain> 512
'''
vmtype = vm_virt_type(domain)
if vmtype == 'OS':
return __salt__['vmadm.update'](vm=domain, max_physical_memory=memory)
elif vmtype == 'LX':
return __salt__['vmadm.update'](vm=domain, max_physical_memory=memory)
elif vmtype == 'KVM':
log.warning('Changes will be applied after the VM restart.')
return __salt__['vmadm.update'](vm=domain, ram=memory)
else:
raise CommandExecutionError('Unknown VM type')
return False
def get_macs(domain):
'''
Return a list off MAC addresses from the named VM
CLI Example:
.. code-block:: bash
salt '*' virt.get_macs <domain>
'''
macs = []
ret = __salt__['vmadm.lookup'](search="uuid={uuid}".format(uuid=domain), order='nics')
if not ret:
raise CommandExecutionError('We can\'t find the MAC address of this VM')
else:
for nic in ret[0]['nics']:
macs.append(nic['mac'])
return macs
|
saltstack/salt
|
salt/modules/smartos_virt.py
|
vm_virt_type
|
python
|
def vm_virt_type(domain):
'''
Return VM virtualization type : OS or KVM
CLI Example:
.. code-block:: bash
salt '*' virt.vm_virt_type <domain>
'''
ret = __salt__['vmadm.lookup'](search="uuid={uuid}".format(uuid=domain), order='type')
if not ret:
raise CommandExecutionError("We can't determine the type of this VM")
return ret[0]['type']
|
Return VM virtualization type : OS or KVM
CLI Example:
.. code-block:: bash
salt '*' virt.vm_virt_type <domain>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_virt.py#L181-L195
| null |
# -*- coding: utf-8 -*-
'''
virst compatibility module for managing VMs on SmartOS
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'virt'
def __virtual__():
'''
Provides virt on SmartOS
'''
if salt.utils.platform.is_smartos_globalzone() \
and salt.utils.path.which('vmadm'):
return __virtualname__
return (
False,
'{0} module can only be loaded on SmartOS compute nodes'.format(
__virtualname__
)
)
def init(**kwargs):
'''
Initialize a new VM
CLI Example:
.. code-block:: bash
salt '*' virt.init image_uuid='...' alias='...' [...]
'''
return __salt__['vmadm.create'](**kwargs)
def list_domains():
'''
Return a list of virtual machine names on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_domains
'''
data = __salt__['vmadm.list'](keyed=True)
vms = ["UUID TYPE RAM STATE ALIAS"]
for vm in data:
vms.append("{vmuuid}{vmtype}{vmram}{vmstate}{vmalias}".format(
vmuuid=vm.ljust(38),
vmtype=data[vm]['type'].ljust(6),
vmram=data[vm]['ram'].ljust(9),
vmstate=data[vm]['state'].ljust(18),
vmalias=data[vm]['alias'],
))
return vms
def list_active_vms():
'''
Return a list of uuids for active virtual machine on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_active_vms
'''
return __salt__['vmadm.list'](search="state='running'", order='uuid')
def list_inactive_vms():
'''
Return a list of uuids for inactive virtual machine on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_inactive_vms
'''
return __salt__['vmadm.list'](search="state='stopped'", order='uuid')
def vm_info(domain):
'''
Return a dict with information about the specified VM on this CN
CLI Example:
.. code-block:: bash
salt '*' virt.vm_info <domain>
'''
return __salt__['vmadm.get'](domain)
def start(domain):
'''
Start a defined domain
CLI Example:
.. code-block:: bash
salt '*' virt.start <domain>
'''
if domain in list_active_vms():
raise CommandExecutionError('The specified vm is already running')
__salt__['vmadm.start'](domain)
return domain in list_active_vms()
def shutdown(domain):
'''
Send a soft shutdown signal to the named vm
CLI Example:
.. code-block:: bash
salt '*' virt.shutdown <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is already stopped')
__salt__['vmadm.stop'](domain)
return domain in list_inactive_vms()
def reboot(domain):
'''
Reboot a domain via ACPI request
CLI Example:
.. code-block:: bash
salt '*' virt.reboot <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is stopped')
__salt__['vmadm.reboot'](domain)
return domain in list_active_vms()
def stop(domain):
'''
Hard power down the virtual machine, this is equivalent to powering off the hardware.
CLI Example:
.. code-block:: bash
salt '*' virt.destroy <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is stopped')
return __salt__['vmadm.delete'](domain)
def setmem(domain, memory):
'''
Change the amount of memory allocated to VM.
<memory> is to be specified in MB.
Note for KVM : this would require a restart of the VM.
CLI Example:
.. code-block:: bash
salt '*' virt.setmem <domain> 512
'''
vmtype = vm_virt_type(domain)
if vmtype == 'OS':
return __salt__['vmadm.update'](vm=domain, max_physical_memory=memory)
elif vmtype == 'LX':
return __salt__['vmadm.update'](vm=domain, max_physical_memory=memory)
elif vmtype == 'KVM':
log.warning('Changes will be applied after the VM restart.')
return __salt__['vmadm.update'](vm=domain, ram=memory)
else:
raise CommandExecutionError('Unknown VM type')
return False
def get_macs(domain):
'''
Return a list off MAC addresses from the named VM
CLI Example:
.. code-block:: bash
salt '*' virt.get_macs <domain>
'''
macs = []
ret = __salt__['vmadm.lookup'](search="uuid={uuid}".format(uuid=domain), order='nics')
if not ret:
raise CommandExecutionError('We can\'t find the MAC address of this VM')
else:
for nic in ret[0]['nics']:
macs.append(nic['mac'])
return macs
|
saltstack/salt
|
salt/modules/smartos_virt.py
|
setmem
|
python
|
def setmem(domain, memory):
'''
Change the amount of memory allocated to VM.
<memory> is to be specified in MB.
Note for KVM : this would require a restart of the VM.
CLI Example:
.. code-block:: bash
salt '*' virt.setmem <domain> 512
'''
vmtype = vm_virt_type(domain)
if vmtype == 'OS':
return __salt__['vmadm.update'](vm=domain, max_physical_memory=memory)
elif vmtype == 'LX':
return __salt__['vmadm.update'](vm=domain, max_physical_memory=memory)
elif vmtype == 'KVM':
log.warning('Changes will be applied after the VM restart.')
return __salt__['vmadm.update'](vm=domain, ram=memory)
else:
raise CommandExecutionError('Unknown VM type')
return False
|
Change the amount of memory allocated to VM.
<memory> is to be specified in MB.
Note for KVM : this would require a restart of the VM.
CLI Example:
.. code-block:: bash
salt '*' virt.setmem <domain> 512
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_virt.py#L198-L222
|
[
"def vm_virt_type(domain):\n '''\n Return VM virtualization type : OS or KVM\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' virt.vm_virt_type <domain>\n '''\n ret = __salt__['vmadm.lookup'](search=\"uuid={uuid}\".format(uuid=domain), order='type')\n if not ret:\n raise CommandExecutionError(\"We can't determine the type of this VM\")\n\n return ret[0]['type']\n"
] |
# -*- coding: utf-8 -*-
'''
virst compatibility module for managing VMs on SmartOS
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'virt'
def __virtual__():
'''
Provides virt on SmartOS
'''
if salt.utils.platform.is_smartos_globalzone() \
and salt.utils.path.which('vmadm'):
return __virtualname__
return (
False,
'{0} module can only be loaded on SmartOS compute nodes'.format(
__virtualname__
)
)
def init(**kwargs):
'''
Initialize a new VM
CLI Example:
.. code-block:: bash
salt '*' virt.init image_uuid='...' alias='...' [...]
'''
return __salt__['vmadm.create'](**kwargs)
def list_domains():
'''
Return a list of virtual machine names on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_domains
'''
data = __salt__['vmadm.list'](keyed=True)
vms = ["UUID TYPE RAM STATE ALIAS"]
for vm in data:
vms.append("{vmuuid}{vmtype}{vmram}{vmstate}{vmalias}".format(
vmuuid=vm.ljust(38),
vmtype=data[vm]['type'].ljust(6),
vmram=data[vm]['ram'].ljust(9),
vmstate=data[vm]['state'].ljust(18),
vmalias=data[vm]['alias'],
))
return vms
def list_active_vms():
'''
Return a list of uuids for active virtual machine on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_active_vms
'''
return __salt__['vmadm.list'](search="state='running'", order='uuid')
def list_inactive_vms():
'''
Return a list of uuids for inactive virtual machine on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_inactive_vms
'''
return __salt__['vmadm.list'](search="state='stopped'", order='uuid')
def vm_info(domain):
'''
Return a dict with information about the specified VM on this CN
CLI Example:
.. code-block:: bash
salt '*' virt.vm_info <domain>
'''
return __salt__['vmadm.get'](domain)
def start(domain):
'''
Start a defined domain
CLI Example:
.. code-block:: bash
salt '*' virt.start <domain>
'''
if domain in list_active_vms():
raise CommandExecutionError('The specified vm is already running')
__salt__['vmadm.start'](domain)
return domain in list_active_vms()
def shutdown(domain):
'''
Send a soft shutdown signal to the named vm
CLI Example:
.. code-block:: bash
salt '*' virt.shutdown <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is already stopped')
__salt__['vmadm.stop'](domain)
return domain in list_inactive_vms()
def reboot(domain):
'''
Reboot a domain via ACPI request
CLI Example:
.. code-block:: bash
salt '*' virt.reboot <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is stopped')
__salt__['vmadm.reboot'](domain)
return domain in list_active_vms()
def stop(domain):
'''
Hard power down the virtual machine, this is equivalent to powering off the hardware.
CLI Example:
.. code-block:: bash
salt '*' virt.destroy <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is stopped')
return __salt__['vmadm.delete'](domain)
def vm_virt_type(domain):
'''
Return VM virtualization type : OS or KVM
CLI Example:
.. code-block:: bash
salt '*' virt.vm_virt_type <domain>
'''
ret = __salt__['vmadm.lookup'](search="uuid={uuid}".format(uuid=domain), order='type')
if not ret:
raise CommandExecutionError("We can't determine the type of this VM")
return ret[0]['type']
def get_macs(domain):
'''
Return a list off MAC addresses from the named VM
CLI Example:
.. code-block:: bash
salt '*' virt.get_macs <domain>
'''
macs = []
ret = __salt__['vmadm.lookup'](search="uuid={uuid}".format(uuid=domain), order='nics')
if not ret:
raise CommandExecutionError('We can\'t find the MAC address of this VM')
else:
for nic in ret[0]['nics']:
macs.append(nic['mac'])
return macs
|
saltstack/salt
|
salt/modules/smartos_virt.py
|
get_macs
|
python
|
def get_macs(domain):
'''
Return a list off MAC addresses from the named VM
CLI Example:
.. code-block:: bash
salt '*' virt.get_macs <domain>
'''
macs = []
ret = __salt__['vmadm.lookup'](search="uuid={uuid}".format(uuid=domain), order='nics')
if not ret:
raise CommandExecutionError('We can\'t find the MAC address of this VM')
else:
for nic in ret[0]['nics']:
macs.append(nic['mac'])
return macs
|
Return a list off MAC addresses from the named VM
CLI Example:
.. code-block:: bash
salt '*' virt.get_macs <domain>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_virt.py#L225-L242
| null |
# -*- coding: utf-8 -*-
'''
virst compatibility module for managing VMs on SmartOS
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import Python libs
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'virt'
def __virtual__():
'''
Provides virt on SmartOS
'''
if salt.utils.platform.is_smartos_globalzone() \
and salt.utils.path.which('vmadm'):
return __virtualname__
return (
False,
'{0} module can only be loaded on SmartOS compute nodes'.format(
__virtualname__
)
)
def init(**kwargs):
'''
Initialize a new VM
CLI Example:
.. code-block:: bash
salt '*' virt.init image_uuid='...' alias='...' [...]
'''
return __salt__['vmadm.create'](**kwargs)
def list_domains():
'''
Return a list of virtual machine names on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_domains
'''
data = __salt__['vmadm.list'](keyed=True)
vms = ["UUID TYPE RAM STATE ALIAS"]
for vm in data:
vms.append("{vmuuid}{vmtype}{vmram}{vmstate}{vmalias}".format(
vmuuid=vm.ljust(38),
vmtype=data[vm]['type'].ljust(6),
vmram=data[vm]['ram'].ljust(9),
vmstate=data[vm]['state'].ljust(18),
vmalias=data[vm]['alias'],
))
return vms
def list_active_vms():
'''
Return a list of uuids for active virtual machine on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_active_vms
'''
return __salt__['vmadm.list'](search="state='running'", order='uuid')
def list_inactive_vms():
'''
Return a list of uuids for inactive virtual machine on the minion
CLI Example:
.. code-block:: bash
salt '*' virt.list_inactive_vms
'''
return __salt__['vmadm.list'](search="state='stopped'", order='uuid')
def vm_info(domain):
'''
Return a dict with information about the specified VM on this CN
CLI Example:
.. code-block:: bash
salt '*' virt.vm_info <domain>
'''
return __salt__['vmadm.get'](domain)
def start(domain):
'''
Start a defined domain
CLI Example:
.. code-block:: bash
salt '*' virt.start <domain>
'''
if domain in list_active_vms():
raise CommandExecutionError('The specified vm is already running')
__salt__['vmadm.start'](domain)
return domain in list_active_vms()
def shutdown(domain):
'''
Send a soft shutdown signal to the named vm
CLI Example:
.. code-block:: bash
salt '*' virt.shutdown <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is already stopped')
__salt__['vmadm.stop'](domain)
return domain in list_inactive_vms()
def reboot(domain):
'''
Reboot a domain via ACPI request
CLI Example:
.. code-block:: bash
salt '*' virt.reboot <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is stopped')
__salt__['vmadm.reboot'](domain)
return domain in list_active_vms()
def stop(domain):
'''
Hard power down the virtual machine, this is equivalent to powering off the hardware.
CLI Example:
.. code-block:: bash
salt '*' virt.destroy <domain>
'''
if domain in list_inactive_vms():
raise CommandExecutionError('The specified vm is stopped')
return __salt__['vmadm.delete'](domain)
def vm_virt_type(domain):
'''
Return VM virtualization type : OS or KVM
CLI Example:
.. code-block:: bash
salt '*' virt.vm_virt_type <domain>
'''
ret = __salt__['vmadm.lookup'](search="uuid={uuid}".format(uuid=domain), order='type')
if not ret:
raise CommandExecutionError("We can't determine the type of this VM")
return ret[0]['type']
def setmem(domain, memory):
'''
Change the amount of memory allocated to VM.
<memory> is to be specified in MB.
Note for KVM : this would require a restart of the VM.
CLI Example:
.. code-block:: bash
salt '*' virt.setmem <domain> 512
'''
vmtype = vm_virt_type(domain)
if vmtype == 'OS':
return __salt__['vmadm.update'](vm=domain, max_physical_memory=memory)
elif vmtype == 'LX':
return __salt__['vmadm.update'](vm=domain, max_physical_memory=memory)
elif vmtype == 'KVM':
log.warning('Changes will be applied after the VM restart.')
return __salt__['vmadm.update'](vm=domain, ram=memory)
else:
raise CommandExecutionError('Unknown VM type')
return False
|
saltstack/salt
|
salt/modules/linux_acl.py
|
getfacl
|
python
|
def getfacl(*args, **kwargs):
'''
Return (extremely verbose) map of FACLs on specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.getfacl /tmp/house/kitchen
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
ret = {}
cmd = 'getfacl --absolute-names'
if recursive:
cmd += ' -R'
for dentry in args:
cmd += ' "{0}"'.format(dentry)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
dentry = ''
for line in out:
if not line:
continue
elif line.startswith('getfacl'):
continue
elif line.startswith('#'):
comps = line.replace('# ', '').split(': ')
if comps[0] == 'file':
dentry = comps[1]
ret[dentry] = {'comment': {},
'user': [],
'group': []}
ret[dentry]['comment'][comps[0]] = comps[1]
if comps[0] == 'flags':
flags = list(comps[1])
if flags[0] == 's':
ret[dentry]['suid'] = True
if flags[1] == 's':
ret[dentry]['sgid'] = True
if flags[2] == 't':
ret[dentry]['sticky'] = True
else:
vals = _parse_acl(acl=line,
user=ret[dentry]['comment']['owner'],
group=ret[dentry]['comment']['group'])
acl_type = vals['type']
del vals['type']
for entity in ('user', 'group'):
if entity in vals:
usergroup = vals[entity]
del vals[entity]
if acl_type == 'acl':
ret[dentry][entity].append({usergroup: vals})
elif acl_type == 'default':
if 'defaults' not in ret[dentry]:
ret[dentry]['defaults'] = {}
if entity not in ret[dentry]['defaults']:
ret[dentry]['defaults'][entity] = []
ret[dentry]['defaults'][entity].append({usergroup: vals})
for entity in ('other', 'mask'):
if entity in vals:
del vals[entity]
if acl_type == 'acl':
ret[dentry][entity] = [{"": vals}]
elif acl_type == 'default':
if 'defaults' not in ret[dentry]:
ret[dentry]['defaults'] = {}
ret[dentry]['defaults'][entity] = [{"": vals}]
return ret
|
Return (extremely verbose) map of FACLs on specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.getfacl /tmp/house/kitchen
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom recursive=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_acl.py#L48-L121
|
[
"def _raise_on_no_files(*args):\n if not args:\n raise CommandExecutionError('You need to specify at least one file or directory to work with!')\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Linux File Access Control Lists
The Linux ACL module requires the `getfacl` and `setfacl` binaries.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.path
from salt.exceptions import CommandExecutionError
# Define the module's virtual name
__virtualname__ = 'acl'
def __virtual__():
'''
Only load the module if getfacl is installed
'''
if salt.utils.path.which('getfacl'):
return __virtualname__
return (False, 'The linux_acl execution module cannot be loaded: the getfacl binary is not in the path.')
def version():
'''
Return facl version from getfacl --version
CLI Example:
.. code-block:: bash
salt '*' acl.version
'''
cmd = 'getfacl --version'
out = __salt__['cmd.run'](cmd).splitlines()
ret = out[0].split()
return ret[1].strip()
def _raise_on_no_files(*args):
if not args:
raise CommandExecutionError('You need to specify at least one file or directory to work with!')
def _parse_acl(acl, user, group):
'''
Parse a single ACL rule
'''
comps = acl.split(':')
vals = {}
# What type of rule is this?
vals['type'] = 'acl'
if comps[0] == 'default':
vals['type'] = 'default'
comps.pop(0)
# If a user is not specified, use the owner of the file
if comps[0] == 'user' and not comps[1]:
comps[1] = user
elif comps[0] == 'group' and not comps[1]:
comps[1] = group
vals[comps[0]] = comps[1]
# Set the permissions fields
octal = 0
vals['permissions'] = {}
if 'r' in comps[-1]:
octal += 4
vals['permissions']['read'] = True
else:
vals['permissions']['read'] = False
if 'w' in comps[-1]:
octal += 2
vals['permissions']['write'] = True
else:
vals['permissions']['write'] = False
if 'x' in comps[-1]:
octal += 1
vals['permissions']['execute'] = True
else:
vals['permissions']['execute'] = False
vals['octal'] = octal
return vals
def wipefacls(*args, **kwargs):
'''
Remove all FACLs from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.wipefacls /tmp/house/kitchen
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
cmd = 'setfacl -b'
if recursive:
cmd += ' -R'
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False)
return True
def _acl_prefix(acl_type):
prefix = ''
if acl_type.startswith('d'):
prefix = 'd:'
acl_type = acl_type.replace('default:', '')
acl_type = acl_type.replace('d:', '')
if acl_type == 'user' or acl_type == 'u':
prefix += 'u'
elif acl_type == 'group' or acl_type == 'g':
prefix += 'g'
elif acl_type == 'mask' or acl_type == 'm':
prefix += 'm'
return prefix
def modfacl(acl_type, acl_name='', perms='', *args, **kwargs):
'''
Add or modify a FACL for the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen
salt '*' acl.modfacl default:group mygroup rx /tmp/house/kitchen
salt '*' acl.modfacl d:u myuser 7 /tmp/house/kitchen
salt '*' acl.modfacl g mygroup 0 /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen recursive=True
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen raise_err=True
'''
recursive = kwargs.pop('recursive', False)
raise_err = kwargs.pop('raise_err', False)
_raise_on_no_files(*args)
cmd = 'setfacl'
if recursive:
cmd += ' -R' # -R must come first as -m needs the acl_* arguments that come later
cmd += ' -m'
cmd = '{0} {1}:{2}:{3}'.format(cmd, _acl_prefix(acl_type), acl_name, perms)
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False, raise_err=raise_err)
return True
def delfacl(acl_type, acl_name='', *args, **kwargs):
'''
Remove specific FACL from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.delfacl user myuser /tmp/house/kitchen
salt '*' acl.delfacl default:group mygroup /tmp/house/kitchen
salt '*' acl.delfacl d:u myuser /tmp/house/kitchen
salt '*' acl.delfacl g myuser /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.delfacl user myuser /tmp/house/kitchen recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
cmd = 'setfacl'
if recursive:
cmd += ' -R'
cmd += ' -x'
cmd = '{0} {1}:{2}'.format(cmd, _acl_prefix(acl_type), acl_name)
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False)
return True
|
saltstack/salt
|
salt/modules/linux_acl.py
|
_parse_acl
|
python
|
def _parse_acl(acl, user, group):
'''
Parse a single ACL rule
'''
comps = acl.split(':')
vals = {}
# What type of rule is this?
vals['type'] = 'acl'
if comps[0] == 'default':
vals['type'] = 'default'
comps.pop(0)
# If a user is not specified, use the owner of the file
if comps[0] == 'user' and not comps[1]:
comps[1] = user
elif comps[0] == 'group' and not comps[1]:
comps[1] = group
vals[comps[0]] = comps[1]
# Set the permissions fields
octal = 0
vals['permissions'] = {}
if 'r' in comps[-1]:
octal += 4
vals['permissions']['read'] = True
else:
vals['permissions']['read'] = False
if 'w' in comps[-1]:
octal += 2
vals['permissions']['write'] = True
else:
vals['permissions']['write'] = False
if 'x' in comps[-1]:
octal += 1
vals['permissions']['execute'] = True
else:
vals['permissions']['execute'] = False
vals['octal'] = octal
return vals
|
Parse a single ACL rule
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_acl.py#L124-L164
| null |
# -*- coding: utf-8 -*-
'''
Support for Linux File Access Control Lists
The Linux ACL module requires the `getfacl` and `setfacl` binaries.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.path
from salt.exceptions import CommandExecutionError
# Define the module's virtual name
__virtualname__ = 'acl'
def __virtual__():
'''
Only load the module if getfacl is installed
'''
if salt.utils.path.which('getfacl'):
return __virtualname__
return (False, 'The linux_acl execution module cannot be loaded: the getfacl binary is not in the path.')
def version():
'''
Return facl version from getfacl --version
CLI Example:
.. code-block:: bash
salt '*' acl.version
'''
cmd = 'getfacl --version'
out = __salt__['cmd.run'](cmd).splitlines()
ret = out[0].split()
return ret[1].strip()
def _raise_on_no_files(*args):
if not args:
raise CommandExecutionError('You need to specify at least one file or directory to work with!')
def getfacl(*args, **kwargs):
'''
Return (extremely verbose) map of FACLs on specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.getfacl /tmp/house/kitchen
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
ret = {}
cmd = 'getfacl --absolute-names'
if recursive:
cmd += ' -R'
for dentry in args:
cmd += ' "{0}"'.format(dentry)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
dentry = ''
for line in out:
if not line:
continue
elif line.startswith('getfacl'):
continue
elif line.startswith('#'):
comps = line.replace('# ', '').split(': ')
if comps[0] == 'file':
dentry = comps[1]
ret[dentry] = {'comment': {},
'user': [],
'group': []}
ret[dentry]['comment'][comps[0]] = comps[1]
if comps[0] == 'flags':
flags = list(comps[1])
if flags[0] == 's':
ret[dentry]['suid'] = True
if flags[1] == 's':
ret[dentry]['sgid'] = True
if flags[2] == 't':
ret[dentry]['sticky'] = True
else:
vals = _parse_acl(acl=line,
user=ret[dentry]['comment']['owner'],
group=ret[dentry]['comment']['group'])
acl_type = vals['type']
del vals['type']
for entity in ('user', 'group'):
if entity in vals:
usergroup = vals[entity]
del vals[entity]
if acl_type == 'acl':
ret[dentry][entity].append({usergroup: vals})
elif acl_type == 'default':
if 'defaults' not in ret[dentry]:
ret[dentry]['defaults'] = {}
if entity not in ret[dentry]['defaults']:
ret[dentry]['defaults'][entity] = []
ret[dentry]['defaults'][entity].append({usergroup: vals})
for entity in ('other', 'mask'):
if entity in vals:
del vals[entity]
if acl_type == 'acl':
ret[dentry][entity] = [{"": vals}]
elif acl_type == 'default':
if 'defaults' not in ret[dentry]:
ret[dentry]['defaults'] = {}
ret[dentry]['defaults'][entity] = [{"": vals}]
return ret
def wipefacls(*args, **kwargs):
'''
Remove all FACLs from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.wipefacls /tmp/house/kitchen
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
cmd = 'setfacl -b'
if recursive:
cmd += ' -R'
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False)
return True
def _acl_prefix(acl_type):
prefix = ''
if acl_type.startswith('d'):
prefix = 'd:'
acl_type = acl_type.replace('default:', '')
acl_type = acl_type.replace('d:', '')
if acl_type == 'user' or acl_type == 'u':
prefix += 'u'
elif acl_type == 'group' or acl_type == 'g':
prefix += 'g'
elif acl_type == 'mask' or acl_type == 'm':
prefix += 'm'
return prefix
def modfacl(acl_type, acl_name='', perms='', *args, **kwargs):
'''
Add or modify a FACL for the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen
salt '*' acl.modfacl default:group mygroup rx /tmp/house/kitchen
salt '*' acl.modfacl d:u myuser 7 /tmp/house/kitchen
salt '*' acl.modfacl g mygroup 0 /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen recursive=True
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen raise_err=True
'''
recursive = kwargs.pop('recursive', False)
raise_err = kwargs.pop('raise_err', False)
_raise_on_no_files(*args)
cmd = 'setfacl'
if recursive:
cmd += ' -R' # -R must come first as -m needs the acl_* arguments that come later
cmd += ' -m'
cmd = '{0} {1}:{2}:{3}'.format(cmd, _acl_prefix(acl_type), acl_name, perms)
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False, raise_err=raise_err)
return True
def delfacl(acl_type, acl_name='', *args, **kwargs):
'''
Remove specific FACL from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.delfacl user myuser /tmp/house/kitchen
salt '*' acl.delfacl default:group mygroup /tmp/house/kitchen
salt '*' acl.delfacl d:u myuser /tmp/house/kitchen
salt '*' acl.delfacl g myuser /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.delfacl user myuser /tmp/house/kitchen recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
cmd = 'setfacl'
if recursive:
cmd += ' -R'
cmd += ' -x'
cmd = '{0} {1}:{2}'.format(cmd, _acl_prefix(acl_type), acl_name)
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False)
return True
|
saltstack/salt
|
salt/modules/linux_acl.py
|
wipefacls
|
python
|
def wipefacls(*args, **kwargs):
'''
Remove all FACLs from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.wipefacls /tmp/house/kitchen
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
cmd = 'setfacl -b'
if recursive:
cmd += ' -R'
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False)
return True
|
Remove all FACLs from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.wipefacls /tmp/house/kitchen
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom recursive=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_acl.py#L167-L188
|
[
"def _raise_on_no_files(*args):\n if not args:\n raise CommandExecutionError('You need to specify at least one file or directory to work with!')\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Linux File Access Control Lists
The Linux ACL module requires the `getfacl` and `setfacl` binaries.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.path
from salt.exceptions import CommandExecutionError
# Define the module's virtual name
__virtualname__ = 'acl'
def __virtual__():
'''
Only load the module if getfacl is installed
'''
if salt.utils.path.which('getfacl'):
return __virtualname__
return (False, 'The linux_acl execution module cannot be loaded: the getfacl binary is not in the path.')
def version():
'''
Return facl version from getfacl --version
CLI Example:
.. code-block:: bash
salt '*' acl.version
'''
cmd = 'getfacl --version'
out = __salt__['cmd.run'](cmd).splitlines()
ret = out[0].split()
return ret[1].strip()
def _raise_on_no_files(*args):
if not args:
raise CommandExecutionError('You need to specify at least one file or directory to work with!')
def getfacl(*args, **kwargs):
'''
Return (extremely verbose) map of FACLs on specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.getfacl /tmp/house/kitchen
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
ret = {}
cmd = 'getfacl --absolute-names'
if recursive:
cmd += ' -R'
for dentry in args:
cmd += ' "{0}"'.format(dentry)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
dentry = ''
for line in out:
if not line:
continue
elif line.startswith('getfacl'):
continue
elif line.startswith('#'):
comps = line.replace('# ', '').split(': ')
if comps[0] == 'file':
dentry = comps[1]
ret[dentry] = {'comment': {},
'user': [],
'group': []}
ret[dentry]['comment'][comps[0]] = comps[1]
if comps[0] == 'flags':
flags = list(comps[1])
if flags[0] == 's':
ret[dentry]['suid'] = True
if flags[1] == 's':
ret[dentry]['sgid'] = True
if flags[2] == 't':
ret[dentry]['sticky'] = True
else:
vals = _parse_acl(acl=line,
user=ret[dentry]['comment']['owner'],
group=ret[dentry]['comment']['group'])
acl_type = vals['type']
del vals['type']
for entity in ('user', 'group'):
if entity in vals:
usergroup = vals[entity]
del vals[entity]
if acl_type == 'acl':
ret[dentry][entity].append({usergroup: vals})
elif acl_type == 'default':
if 'defaults' not in ret[dentry]:
ret[dentry]['defaults'] = {}
if entity not in ret[dentry]['defaults']:
ret[dentry]['defaults'][entity] = []
ret[dentry]['defaults'][entity].append({usergroup: vals})
for entity in ('other', 'mask'):
if entity in vals:
del vals[entity]
if acl_type == 'acl':
ret[dentry][entity] = [{"": vals}]
elif acl_type == 'default':
if 'defaults' not in ret[dentry]:
ret[dentry]['defaults'] = {}
ret[dentry]['defaults'][entity] = [{"": vals}]
return ret
def _parse_acl(acl, user, group):
'''
Parse a single ACL rule
'''
comps = acl.split(':')
vals = {}
# What type of rule is this?
vals['type'] = 'acl'
if comps[0] == 'default':
vals['type'] = 'default'
comps.pop(0)
# If a user is not specified, use the owner of the file
if comps[0] == 'user' and not comps[1]:
comps[1] = user
elif comps[0] == 'group' and not comps[1]:
comps[1] = group
vals[comps[0]] = comps[1]
# Set the permissions fields
octal = 0
vals['permissions'] = {}
if 'r' in comps[-1]:
octal += 4
vals['permissions']['read'] = True
else:
vals['permissions']['read'] = False
if 'w' in comps[-1]:
octal += 2
vals['permissions']['write'] = True
else:
vals['permissions']['write'] = False
if 'x' in comps[-1]:
octal += 1
vals['permissions']['execute'] = True
else:
vals['permissions']['execute'] = False
vals['octal'] = octal
return vals
def _acl_prefix(acl_type):
prefix = ''
if acl_type.startswith('d'):
prefix = 'd:'
acl_type = acl_type.replace('default:', '')
acl_type = acl_type.replace('d:', '')
if acl_type == 'user' or acl_type == 'u':
prefix += 'u'
elif acl_type == 'group' or acl_type == 'g':
prefix += 'g'
elif acl_type == 'mask' or acl_type == 'm':
prefix += 'm'
return prefix
def modfacl(acl_type, acl_name='', perms='', *args, **kwargs):
'''
Add or modify a FACL for the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen
salt '*' acl.modfacl default:group mygroup rx /tmp/house/kitchen
salt '*' acl.modfacl d:u myuser 7 /tmp/house/kitchen
salt '*' acl.modfacl g mygroup 0 /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen recursive=True
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen raise_err=True
'''
recursive = kwargs.pop('recursive', False)
raise_err = kwargs.pop('raise_err', False)
_raise_on_no_files(*args)
cmd = 'setfacl'
if recursive:
cmd += ' -R' # -R must come first as -m needs the acl_* arguments that come later
cmd += ' -m'
cmd = '{0} {1}:{2}:{3}'.format(cmd, _acl_prefix(acl_type), acl_name, perms)
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False, raise_err=raise_err)
return True
def delfacl(acl_type, acl_name='', *args, **kwargs):
'''
Remove specific FACL from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.delfacl user myuser /tmp/house/kitchen
salt '*' acl.delfacl default:group mygroup /tmp/house/kitchen
salt '*' acl.delfacl d:u myuser /tmp/house/kitchen
salt '*' acl.delfacl g myuser /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.delfacl user myuser /tmp/house/kitchen recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
cmd = 'setfacl'
if recursive:
cmd += ' -R'
cmd += ' -x'
cmd = '{0} {1}:{2}'.format(cmd, _acl_prefix(acl_type), acl_name)
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False)
return True
|
saltstack/salt
|
salt/modules/linux_acl.py
|
modfacl
|
python
|
def modfacl(acl_type, acl_name='', perms='', *args, **kwargs):
'''
Add or modify a FACL for the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen
salt '*' acl.modfacl default:group mygroup rx /tmp/house/kitchen
salt '*' acl.modfacl d:u myuser 7 /tmp/house/kitchen
salt '*' acl.modfacl g mygroup 0 /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen recursive=True
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen raise_err=True
'''
recursive = kwargs.pop('recursive', False)
raise_err = kwargs.pop('raise_err', False)
_raise_on_no_files(*args)
cmd = 'setfacl'
if recursive:
cmd += ' -R' # -R must come first as -m needs the acl_* arguments that come later
cmd += ' -m'
cmd = '{0} {1}:{2}:{3}'.format(cmd, _acl_prefix(acl_type), acl_name, perms)
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False, raise_err=raise_err)
return True
|
Add or modify a FACL for the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen
salt '*' acl.modfacl default:group mygroup rx /tmp/house/kitchen
salt '*' acl.modfacl d:u myuser 7 /tmp/house/kitchen
salt '*' acl.modfacl g mygroup 0 /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen recursive=True
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen raise_err=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_acl.py#L206-L237
|
[
"def _raise_on_no_files(*args):\n if not args:\n raise CommandExecutionError('You need to specify at least one file or directory to work with!')\n",
"def _acl_prefix(acl_type):\n prefix = ''\n if acl_type.startswith('d'):\n prefix = 'd:'\n acl_type = acl_type.replace('default:', '')\n acl_type = acl_type.replace('d:', '')\n if acl_type == 'user' or acl_type == 'u':\n prefix += 'u'\n elif acl_type == 'group' or acl_type == 'g':\n prefix += 'g'\n elif acl_type == 'mask' or acl_type == 'm':\n prefix += 'm'\n return prefix\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Linux File Access Control Lists
The Linux ACL module requires the `getfacl` and `setfacl` binaries.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.path
from salt.exceptions import CommandExecutionError
# Define the module's virtual name
__virtualname__ = 'acl'
def __virtual__():
'''
Only load the module if getfacl is installed
'''
if salt.utils.path.which('getfacl'):
return __virtualname__
return (False, 'The linux_acl execution module cannot be loaded: the getfacl binary is not in the path.')
def version():
'''
Return facl version from getfacl --version
CLI Example:
.. code-block:: bash
salt '*' acl.version
'''
cmd = 'getfacl --version'
out = __salt__['cmd.run'](cmd).splitlines()
ret = out[0].split()
return ret[1].strip()
def _raise_on_no_files(*args):
if not args:
raise CommandExecutionError('You need to specify at least one file or directory to work with!')
def getfacl(*args, **kwargs):
'''
Return (extremely verbose) map of FACLs on specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.getfacl /tmp/house/kitchen
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
ret = {}
cmd = 'getfacl --absolute-names'
if recursive:
cmd += ' -R'
for dentry in args:
cmd += ' "{0}"'.format(dentry)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
dentry = ''
for line in out:
if not line:
continue
elif line.startswith('getfacl'):
continue
elif line.startswith('#'):
comps = line.replace('# ', '').split(': ')
if comps[0] == 'file':
dentry = comps[1]
ret[dentry] = {'comment': {},
'user': [],
'group': []}
ret[dentry]['comment'][comps[0]] = comps[1]
if comps[0] == 'flags':
flags = list(comps[1])
if flags[0] == 's':
ret[dentry]['suid'] = True
if flags[1] == 's':
ret[dentry]['sgid'] = True
if flags[2] == 't':
ret[dentry]['sticky'] = True
else:
vals = _parse_acl(acl=line,
user=ret[dentry]['comment']['owner'],
group=ret[dentry]['comment']['group'])
acl_type = vals['type']
del vals['type']
for entity in ('user', 'group'):
if entity in vals:
usergroup = vals[entity]
del vals[entity]
if acl_type == 'acl':
ret[dentry][entity].append({usergroup: vals})
elif acl_type == 'default':
if 'defaults' not in ret[dentry]:
ret[dentry]['defaults'] = {}
if entity not in ret[dentry]['defaults']:
ret[dentry]['defaults'][entity] = []
ret[dentry]['defaults'][entity].append({usergroup: vals})
for entity in ('other', 'mask'):
if entity in vals:
del vals[entity]
if acl_type == 'acl':
ret[dentry][entity] = [{"": vals}]
elif acl_type == 'default':
if 'defaults' not in ret[dentry]:
ret[dentry]['defaults'] = {}
ret[dentry]['defaults'][entity] = [{"": vals}]
return ret
def _parse_acl(acl, user, group):
'''
Parse a single ACL rule
'''
comps = acl.split(':')
vals = {}
# What type of rule is this?
vals['type'] = 'acl'
if comps[0] == 'default':
vals['type'] = 'default'
comps.pop(0)
# If a user is not specified, use the owner of the file
if comps[0] == 'user' and not comps[1]:
comps[1] = user
elif comps[0] == 'group' and not comps[1]:
comps[1] = group
vals[comps[0]] = comps[1]
# Set the permissions fields
octal = 0
vals['permissions'] = {}
if 'r' in comps[-1]:
octal += 4
vals['permissions']['read'] = True
else:
vals['permissions']['read'] = False
if 'w' in comps[-1]:
octal += 2
vals['permissions']['write'] = True
else:
vals['permissions']['write'] = False
if 'x' in comps[-1]:
octal += 1
vals['permissions']['execute'] = True
else:
vals['permissions']['execute'] = False
vals['octal'] = octal
return vals
def wipefacls(*args, **kwargs):
'''
Remove all FACLs from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.wipefacls /tmp/house/kitchen
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
cmd = 'setfacl -b'
if recursive:
cmd += ' -R'
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False)
return True
def _acl_prefix(acl_type):
prefix = ''
if acl_type.startswith('d'):
prefix = 'd:'
acl_type = acl_type.replace('default:', '')
acl_type = acl_type.replace('d:', '')
if acl_type == 'user' or acl_type == 'u':
prefix += 'u'
elif acl_type == 'group' or acl_type == 'g':
prefix += 'g'
elif acl_type == 'mask' or acl_type == 'm':
prefix += 'm'
return prefix
def delfacl(acl_type, acl_name='', *args, **kwargs):
'''
Remove specific FACL from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.delfacl user myuser /tmp/house/kitchen
salt '*' acl.delfacl default:group mygroup /tmp/house/kitchen
salt '*' acl.delfacl d:u myuser /tmp/house/kitchen
salt '*' acl.delfacl g myuser /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.delfacl user myuser /tmp/house/kitchen recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
cmd = 'setfacl'
if recursive:
cmd += ' -R'
cmd += ' -x'
cmd = '{0} {1}:{2}'.format(cmd, _acl_prefix(acl_type), acl_name)
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False)
return True
|
saltstack/salt
|
salt/modules/linux_acl.py
|
delfacl
|
python
|
def delfacl(acl_type, acl_name='', *args, **kwargs):
'''
Remove specific FACL from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.delfacl user myuser /tmp/house/kitchen
salt '*' acl.delfacl default:group mygroup /tmp/house/kitchen
salt '*' acl.delfacl d:u myuser /tmp/house/kitchen
salt '*' acl.delfacl g myuser /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.delfacl user myuser /tmp/house/kitchen recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
cmd = 'setfacl'
if recursive:
cmd += ' -R'
cmd += ' -x'
cmd = '{0} {1}:{2}'.format(cmd, _acl_prefix(acl_type), acl_name)
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False)
return True
|
Remove specific FACL from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.delfacl user myuser /tmp/house/kitchen
salt '*' acl.delfacl default:group mygroup /tmp/house/kitchen
salt '*' acl.delfacl d:u myuser /tmp/house/kitchen
salt '*' acl.delfacl g myuser /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.delfacl user myuser /tmp/house/kitchen recursive=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_acl.py#L240-L269
|
[
"def _raise_on_no_files(*args):\n if not args:\n raise CommandExecutionError('You need to specify at least one file or directory to work with!')\n",
"def _acl_prefix(acl_type):\n prefix = ''\n if acl_type.startswith('d'):\n prefix = 'd:'\n acl_type = acl_type.replace('default:', '')\n acl_type = acl_type.replace('d:', '')\n if acl_type == 'user' or acl_type == 'u':\n prefix += 'u'\n elif acl_type == 'group' or acl_type == 'g':\n prefix += 'g'\n elif acl_type == 'mask' or acl_type == 'm':\n prefix += 'm'\n return prefix\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Linux File Access Control Lists
The Linux ACL module requires the `getfacl` and `setfacl` binaries.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.path
from salt.exceptions import CommandExecutionError
# Define the module's virtual name
__virtualname__ = 'acl'
def __virtual__():
'''
Only load the module if getfacl is installed
'''
if salt.utils.path.which('getfacl'):
return __virtualname__
return (False, 'The linux_acl execution module cannot be loaded: the getfacl binary is not in the path.')
def version():
'''
Return facl version from getfacl --version
CLI Example:
.. code-block:: bash
salt '*' acl.version
'''
cmd = 'getfacl --version'
out = __salt__['cmd.run'](cmd).splitlines()
ret = out[0].split()
return ret[1].strip()
def _raise_on_no_files(*args):
if not args:
raise CommandExecutionError('You need to specify at least one file or directory to work with!')
def getfacl(*args, **kwargs):
'''
Return (extremely verbose) map of FACLs on specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.getfacl /tmp/house/kitchen
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.getfacl /tmp/house/kitchen /tmp/house/livingroom recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
ret = {}
cmd = 'getfacl --absolute-names'
if recursive:
cmd += ' -R'
for dentry in args:
cmd += ' "{0}"'.format(dentry)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
dentry = ''
for line in out:
if not line:
continue
elif line.startswith('getfacl'):
continue
elif line.startswith('#'):
comps = line.replace('# ', '').split(': ')
if comps[0] == 'file':
dentry = comps[1]
ret[dentry] = {'comment': {},
'user': [],
'group': []}
ret[dentry]['comment'][comps[0]] = comps[1]
if comps[0] == 'flags':
flags = list(comps[1])
if flags[0] == 's':
ret[dentry]['suid'] = True
if flags[1] == 's':
ret[dentry]['sgid'] = True
if flags[2] == 't':
ret[dentry]['sticky'] = True
else:
vals = _parse_acl(acl=line,
user=ret[dentry]['comment']['owner'],
group=ret[dentry]['comment']['group'])
acl_type = vals['type']
del vals['type']
for entity in ('user', 'group'):
if entity in vals:
usergroup = vals[entity]
del vals[entity]
if acl_type == 'acl':
ret[dentry][entity].append({usergroup: vals})
elif acl_type == 'default':
if 'defaults' not in ret[dentry]:
ret[dentry]['defaults'] = {}
if entity not in ret[dentry]['defaults']:
ret[dentry]['defaults'][entity] = []
ret[dentry]['defaults'][entity].append({usergroup: vals})
for entity in ('other', 'mask'):
if entity in vals:
del vals[entity]
if acl_type == 'acl':
ret[dentry][entity] = [{"": vals}]
elif acl_type == 'default':
if 'defaults' not in ret[dentry]:
ret[dentry]['defaults'] = {}
ret[dentry]['defaults'][entity] = [{"": vals}]
return ret
def _parse_acl(acl, user, group):
'''
Parse a single ACL rule
'''
comps = acl.split(':')
vals = {}
# What type of rule is this?
vals['type'] = 'acl'
if comps[0] == 'default':
vals['type'] = 'default'
comps.pop(0)
# If a user is not specified, use the owner of the file
if comps[0] == 'user' and not comps[1]:
comps[1] = user
elif comps[0] == 'group' and not comps[1]:
comps[1] = group
vals[comps[0]] = comps[1]
# Set the permissions fields
octal = 0
vals['permissions'] = {}
if 'r' in comps[-1]:
octal += 4
vals['permissions']['read'] = True
else:
vals['permissions']['read'] = False
if 'w' in comps[-1]:
octal += 2
vals['permissions']['write'] = True
else:
vals['permissions']['write'] = False
if 'x' in comps[-1]:
octal += 1
vals['permissions']['execute'] = True
else:
vals['permissions']['execute'] = False
vals['octal'] = octal
return vals
def wipefacls(*args, **kwargs):
'''
Remove all FACLs from the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.wipefacls /tmp/house/kitchen
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.wipefacls /tmp/house/kitchen /tmp/house/livingroom recursive=True
'''
recursive = kwargs.pop('recursive', False)
_raise_on_no_files(*args)
cmd = 'setfacl -b'
if recursive:
cmd += ' -R'
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False)
return True
def _acl_prefix(acl_type):
prefix = ''
if acl_type.startswith('d'):
prefix = 'd:'
acl_type = acl_type.replace('default:', '')
acl_type = acl_type.replace('d:', '')
if acl_type == 'user' or acl_type == 'u':
prefix += 'u'
elif acl_type == 'group' or acl_type == 'g':
prefix += 'g'
elif acl_type == 'mask' or acl_type == 'm':
prefix += 'm'
return prefix
def modfacl(acl_type, acl_name='', perms='', *args, **kwargs):
'''
Add or modify a FACL for the specified file(s)
CLI Examples:
.. code-block:: bash
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen
salt '*' acl.modfacl default:group mygroup rx /tmp/house/kitchen
salt '*' acl.modfacl d:u myuser 7 /tmp/house/kitchen
salt '*' acl.modfacl g mygroup 0 /tmp/house/kitchen /tmp/house/livingroom
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen recursive=True
salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen raise_err=True
'''
recursive = kwargs.pop('recursive', False)
raise_err = kwargs.pop('raise_err', False)
_raise_on_no_files(*args)
cmd = 'setfacl'
if recursive:
cmd += ' -R' # -R must come first as -m needs the acl_* arguments that come later
cmd += ' -m'
cmd = '{0} {1}:{2}:{3}'.format(cmd, _acl_prefix(acl_type), acl_name, perms)
for dentry in args:
cmd += ' "{0}"'.format(dentry)
__salt__['cmd.run'](cmd, python_shell=False, raise_err=raise_err)
return True
|
saltstack/salt
|
salt/states/influxdb_user.py
|
present
|
python
|
def present(name,
passwd,
admin=False,
grants=None,
**client_args):
'''
Ensure that given user is present.
name
Name of the user to manage
passwd
Password of the user
admin : False
Whether the user should have cluster administration
privileges or not.
grants
Optional - Dict of database:privilege items associated with
the user. Example:
grants:
foo_db: read
bar_db: all
**Example:**
.. code-block:: yaml
example user present in influxdb:
influxdb_user.present:
- name: example
- passwd: somepassword
- admin: False
- grants:
foo_db: read
bar_db: all
'''
create = False
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'User {0} is present and up to date'.format(name)}
if not __salt__['influxdb.user_exists'](name, **client_args):
create = True
if __opts__['test']:
ret['comment'] = 'User {0} will be created'.format(name)
ret['result'] = None
return ret
else:
if not __salt__['influxdb.create_user'](
name, passwd, admin=admin, **client_args):
ret['comment'] = 'Failed to create user {0}'.format(name)
ret['result'] = False
return ret
else:
user = __salt__['influxdb.user_info'](name, **client_args)
if user['admin'] != admin:
if not __opts__['test']:
if admin:
__salt__['influxdb.grant_admin_privileges'](
name, **client_args)
else:
__salt__['influxdb.revoke_admin_privileges'](
name, **client_args)
if admin != __salt__['influxdb.user_info'](
name, **client_args)['admin']:
ret['comment'] = 'Failed to set admin privilege to ' \
'user {0}'.format(name)
ret['result'] = False
return ret
ret['changes']['Admin privileges'] = admin
if grants:
db_privileges = __salt__['influxdb.list_privileges'](
name, **client_args)
for database, privilege in grants.items():
privilege = privilege.lower()
if privilege != db_privileges.get(database, privilege):
if not __opts__['test']:
__salt__['influxdb.revoke_privilege'](
database, 'all', name, **client_args)
del db_privileges[database]
if database not in db_privileges:
ret['changes']['Grant on database {0} to user {1}'.format(
database, name)] = privilege
if not __opts__['test']:
__salt__['influxdb.grant_privilege'](
database, privilege, name, **client_args)
if ret['changes']:
if create:
ret['comment'] = 'Created user {0}'.format(name)
ret['changes'][name] = 'User created'
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User {0} will be updated with the ' \
'following changes:'.format(name)
for k, v in ret['changes'].items():
ret['comment'] += '\n{0} => {1}'.format(k, v)
ret['changes'] = {}
else:
ret['comment'] = 'Updated user {0}'.format(name)
return ret
|
Ensure that given user is present.
name
Name of the user to manage
passwd
Password of the user
admin : False
Whether the user should have cluster administration
privileges or not.
grants
Optional - Dict of database:privilege items associated with
the user. Example:
grants:
foo_db: read
bar_db: all
**Example:**
.. code-block:: yaml
example user present in influxdb:
influxdb_user.present:
- name: example
- passwd: somepassword
- admin: False
- grants:
foo_db: read
bar_db: all
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/influxdb_user.py#L22-L131
| null |
# -*- coding: utf-8 -*-
'''
Management of InfluxDB users
============================
(compatible with InfluxDB version 0.9+)
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
def __virtual__():
'''
Only load if the influxdb module is available
'''
if 'influxdb.db_exists' in __salt__:
return 'influxdb_user'
return False
def absent(name, **client_args):
'''
Ensure that given user is absent.
name
The name of the user to manage
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'User {0} is not present'.format(name)}
if __salt__['influxdb.user_exists'](name, **client_args):
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User {0} will be removed'.format(name)
return ret
else:
if __salt__['influxdb.remove_user'](name, **client_args):
ret['comment'] = 'Removed user {0}'.format(name)
ret['changes'][name] = 'removed'
return ret
else:
ret['comment'] = 'Failed to remove user {0}'.format(name)
ret['result'] = False
return ret
return ret
|
saltstack/salt
|
salt/modules/cimc.py
|
activate_backup_image
|
python
|
def activate_backup_image(reset=False):
'''
Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True
'''
dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True:
r = "yes"
inconfig = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""".format(r)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L55-L83
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Cisco UCS compatibility to Salt
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
Configuration
=============
This module accepts connection configuration details either as
parameters, or as configuration settings in pillar as a Salt proxy.
Options passed into opts will be ignored if options are passed into pillar.
.. seealso::
:py:mod:`Cisco UCS Proxy Module <salt.proxy.cimc>`
About
=====
This execution module was designed to handle connections to a Cisco UCS server.
This module adds support to send connections directly to the device through the
rest API.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.platform
import salt.proxy.cimc
log = logging.getLogger(__name__)
__virtualname__ = 'cimc'
def __virtual__():
'''
Will load for the cimc proxy minions.
'''
try:
if salt.utils.platform.is_proxy() and \
__opts__['proxy']['proxytype'] == 'cimc':
return __virtualname__
except KeyError:
pass
return False, 'The cimc execution module can only be loaded for cimc proxy minions.'
def create_user(uid=None, username=None, password=None, priv=None):
'''
Create a CIMC user with username and password.
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
'''
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if not username:
raise salt.exceptions.CommandExecutionError("The username must be specified.")
if not password:
raise salt.exceptions.CommandExecutionError("The password must be specified.")
if not priv:
raise salt.exceptions.CommandExecutionError("The privilege level must be specified.")
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}" accountStatus="active" name="{1}" priv="{2}"
pwd="{3}" dn="sys/user-ext/user-{0}"/>""".format(uid,
username,
priv,
password)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def get_bios_defaults():
'''
Get the default values of BIOS tokens.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_defaults
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosPlatformDefaults', True)
return ret
def get_bios_settings():
'''
Get the C240 server BIOS token values.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosSettings', True)
return ret
def get_boot_order():
'''
Retrieves the configured boot order table.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_boot_order
'''
ret = __proxy__['cimc.get_config_resolver_class']('lsbootDef', True)
return ret
def get_cpu_details():
'''
Get the CPU product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_cpu_details
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogCpu', True)
return ret
def get_disks():
'''
Get the HDD product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogHdd', True)
return ret
def get_ethernet_interfaces():
'''
Get the adapter Ethernet interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ethernet_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostEthIf', True)
return ret
def get_fibre_channel_interfaces():
'''
Get the adapter fibre channel interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_fibre_channel_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostFcIf', True)
return ret
def get_firmware():
'''
Retrieves the current running firmware versions of server components.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_firmware
'''
ret = __proxy__['cimc.get_config_resolver_class']('firmwareRunning', False)
return ret
def get_hostname():
'''
Retrieves the hostname from the device.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_hostname
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', True)
try:
return ret['outConfigs']['mgmtIf'][0]['hostname']
except Exception as err:
return "Unable to retrieve hostname"
def get_ldap():
'''
Retrieves LDAP server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ldap
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaLdap', True)
return ret
def get_management_interface():
'''
Retrieve the management interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_management_interface
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', False)
return ret
def get_memory_token():
'''
Get the memory RAS BIOS token.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_token
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfSelectMemoryRASConfiguration', False)
return ret
def get_memory_unit():
'''
Get the IMM/Memory unit product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_unit
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogDimm', True)
return ret
def get_network_adapters():
'''
Get the list of network adapaters and configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_network_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('networkAdapterEthIf', True)
return ret
def get_ntp():
'''
Retrieves the current running NTP configuration.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ntp
'''
ret = __proxy__['cimc.get_config_resolver_class']('commNtpProvider', False)
return ret
def get_pci_adapters():
'''
Get the PCI adapter product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogPCIAdapter', True)
return ret
def get_power_configuration():
'''
Get the configuration of the power settings from the device. This is only available
on some C-Series servers.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_configuration
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfResumeOnACPowerLoss', True)
return ret
def get_power_supplies():
'''
Retrieves the power supply unit details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_supplies
'''
ret = __proxy__['cimc.get_config_resolver_class']('equipmentPsu', False)
return ret
def get_snmp_config():
'''
Get the snmp configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_snmp_config
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSnmp', False)
return ret
def get_syslog():
'''
Get the Syslog client-server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslogClient', False)
return ret
def get_syslog_settings():
'''
Get the Syslog configuration settings from the system.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslog', False)
return ret
def get_system_info():
'''
Get the system information.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_system_info
'''
ret = __proxy__['cimc.get_config_resolver_class']('computeRackUnit', False)
return ret
def get_users():
'''
Get the CIMC users.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_users
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaUser', False)
return ret
def get_vic_adapters():
'''
Get the VIC adapter general profile details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorGenProfile', True)
return ret
def get_vic_uplinks():
'''
Get the VIC adapter uplink port details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_uplinks
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorExtEthIf', True)
return ret
def mount_share(name=None,
remote_share=None,
remote_file=None,
mount_type="nfs",
username=None,
password=None):
'''
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media mounts can be scripted/automated
No vKVM requirements for media connection
Multiple share types supported
Connections supported through all CIMC interfaces
Note: CIMC Mounted vMedia is enabled through BIOS configuration.
Args:
name(str): The name of the volume on the CIMC device.
remote_share(str): The file share link that will be used to mount the share. This can be NFS, CIFS, or WWW. This
must be the directory path and not the full path to the remote file.
remote_file(str): The name of the remote file to mount. It must reside within remote_share.
mount_type(str): The type of share to mount. Valid options are nfs, cifs, and www.
username(str): An optional requirement to pass credentials to the remote share. If not provided, an
unauthenticated connection attempt will be made.
password(str): An optional requirement to pass a password to the remote share. If not provided, an
unauthenticated connection attempt will be made.
CLI Example:
.. code-block:: bash
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso username=bob password=badpassword
'''
if not name:
raise salt.exceptions.CommandExecutionError("The share name must be specified.")
if not remote_share:
raise salt.exceptions.CommandExecutionError("The remote share path must be specified.")
if not remote_file:
raise salt.exceptions.CommandExecutionError("The remote file name must be specified.")
if username and password:
mount_options = " mountOptions='username={0},password={1}'".format(username, password)
else:
mount_options = ""
dn = 'sys/svc-ext/vmedia-svc/vmmap-{0}'.format(name)
inconfig = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{0}' map='{1}'{2}
remoteFile='{3}' remoteShare='{4}' status='created'
volumeName='Win12' />""".format(name, mount_type, mount_options, remote_file, remote_share)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def reboot():
'''
Power cycling the server.
CLI Example:
.. code-block:: bash
salt '*' cimc.reboot
'''
dn = "sys/rack-unit-1"
inconfig = """<computeRackUnit adminPower="cycle-immediate" dn="sys/rack-unit-1"></computeRackUnit>"""
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_hostname(hostname=None):
'''
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
'''
if not hostname:
raise salt.exceptions.CommandExecutionError("Hostname option must be provided.")
dn = "sys/rack-unit-1/mgmt/if-1"
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{0}" ></mgmtIf>""".format(hostname)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
try:
if ret['outConfig']['mgmtIf'][0]['status'] == 'modified':
return True
else:
return False
except Exception as err:
return False
def set_logging_levels(remote=None, local=None):
'''
Sets the logging levels of the CIMC devices. The logging levels must match
the following options: emergency, alert, critical, error, warning, notice,
informational, debug.
.. versionadded:: 2019.2.0
Args:
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_logging_levels remote=error local=notice
'''
logging_options = ['emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'informational',
'debug']
query = ""
if remote:
if remote in logging_options:
query += ' remoteSeverity="{0}"'.format(remote)
else:
raise salt.exceptions.CommandExecutionError("Remote Severity option is not valid.")
if local:
if local in logging_options:
query += ' localSeverity="{0}"'.format(local)
else:
raise salt.exceptions.CommandExecutionError("Local Severity option is not valid.")
dn = "sys/svc-ext/syslog"
inconfig = """<commSyslog dn="sys/svc-ext/syslog"{0} ></commSyslog>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_ntp_server(server1='', server2='', server3='', server4=''):
'''
Sets the NTP servers configuration. This will also enable the client NTP service.
Args:
server1(str): The first IP address or FQDN of the NTP servers.
server2(str): The second IP address or FQDN of the NTP servers.
server3(str): The third IP address or FQDN of the NTP servers.
server4(str): The fourth IP address or FQDN of the NTP servers.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_ntp_server 10.10.10.1
salt '*' cimc.set_ntp_server 10.10.10.1 foo.bar.com
'''
dn = "sys/svc-ext/ntp-svc"
inconfig = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{0}" ntpServer2="{1}"
ntpServer3="{2}" ntpServer4="{3}"/>""".format(server1, server2, server3, server4)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_power_configuration stay-off
salt '*' cimc.set_power_configuration reset fixed 0
'''
query = ""
if policy == "reset":
query = ' vpResumeOnACPowerLoss="reset"'
if delayType:
if delayType == "fixed":
query += ' delayType="fixed"'
if delayValue:
query += ' delay="{0}"'.format(delayValue)
elif delayType == "random":
query += ' delayType="random"'
else:
raise salt.exceptions.CommandExecutionError("Invalid delay type entered.")
elif policy == "stay-off":
query = ' vpResumeOnACPowerLoss="reset"'
elif policy == "last-state":
query = ' vpResumeOnACPowerLoss="last-state"'
else:
raise salt.exceptions.CommandExecutionError("The power state must be specified.")
dn = "sys/rack-unit-1/board/Resume-on-AC-power-loss"
inconfig = """<biosVfResumeOnACPowerLoss
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{0}>
</biosVfResumeOnACPowerLoss>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_syslog_server(server=None, type="primary"):
'''
Set the SYSLOG server on the host.
Args:
server(str): The hostname or IP address of the SYSLOG server.
type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_syslog_server foo.bar.com
salt '*' cimc.set_syslog_server foo.bar.com primary
salt '*' cimc.set_syslog_server foo.bar.com secondary
'''
if not server:
raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.")
if type == "primary":
dn = "sys/svc-ext/syslog/client-primary"
inconfig = """<commSyslogClient name='primary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-primary'> </commSyslogClient>""".format(server)
elif type == "secondary":
dn = "sys/svc-ext/syslog/client-secondary"
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-secondary'> </commSyslogClient>""".format(server)
else:
raise salt.exceptions.CommandExecutionError("The SYSLOG type must be either primary or secondary.")
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
status(str): The account status of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
'''
conf = ""
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if status:
conf += ' accountStatus="{0}"'.format(status)
if username:
conf += ' name="{0}"'.format(username)
if priv:
conf += ' priv="{0}"'.format(priv)
if password:
conf += ' pwd="{0}"'.format(password)
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}"{1} dn="sys/user-ext/user-{0}"/>""".format(uid,
conf)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_bios(server=None, path=None):
'''
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/bios/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/bios/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-bios' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_cimc(server=None, path=None):
'''
Update the CIMC firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the CIMC image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_cimc foo.bar.com HP-SL2.bin
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/mgmt/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/mgmt/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-controller' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
saltstack/salt
|
salt/modules/cimc.py
|
create_user
|
python
|
def create_user(uid=None, username=None, password=None, priv=None):
'''
Create a CIMC user with username and password.
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
'''
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if not username:
raise salt.exceptions.CommandExecutionError("The username must be specified.")
if not password:
raise salt.exceptions.CommandExecutionError("The password must be specified.")
if not priv:
raise salt.exceptions.CommandExecutionError("The privilege level must be specified.")
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}" accountStatus="active" name="{1}" priv="{2}"
pwd="{3}" dn="sys/user-ext/user-{0}"/>""".format(uid,
username,
priv,
password)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
Create a CIMC user with username and password.
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L86-L129
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Cisco UCS compatibility to Salt
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
Configuration
=============
This module accepts connection configuration details either as
parameters, or as configuration settings in pillar as a Salt proxy.
Options passed into opts will be ignored if options are passed into pillar.
.. seealso::
:py:mod:`Cisco UCS Proxy Module <salt.proxy.cimc>`
About
=====
This execution module was designed to handle connections to a Cisco UCS server.
This module adds support to send connections directly to the device through the
rest API.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.platform
import salt.proxy.cimc
log = logging.getLogger(__name__)
__virtualname__ = 'cimc'
def __virtual__():
'''
Will load for the cimc proxy minions.
'''
try:
if salt.utils.platform.is_proxy() and \
__opts__['proxy']['proxytype'] == 'cimc':
return __virtualname__
except KeyError:
pass
return False, 'The cimc execution module can only be loaded for cimc proxy minions.'
def activate_backup_image(reset=False):
'''
Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True
'''
dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True:
r = "yes"
inconfig = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""".format(r)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def get_bios_defaults():
'''
Get the default values of BIOS tokens.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_defaults
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosPlatformDefaults', True)
return ret
def get_bios_settings():
'''
Get the C240 server BIOS token values.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosSettings', True)
return ret
def get_boot_order():
'''
Retrieves the configured boot order table.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_boot_order
'''
ret = __proxy__['cimc.get_config_resolver_class']('lsbootDef', True)
return ret
def get_cpu_details():
'''
Get the CPU product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_cpu_details
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogCpu', True)
return ret
def get_disks():
'''
Get the HDD product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogHdd', True)
return ret
def get_ethernet_interfaces():
'''
Get the adapter Ethernet interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ethernet_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostEthIf', True)
return ret
def get_fibre_channel_interfaces():
'''
Get the adapter fibre channel interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_fibre_channel_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostFcIf', True)
return ret
def get_firmware():
'''
Retrieves the current running firmware versions of server components.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_firmware
'''
ret = __proxy__['cimc.get_config_resolver_class']('firmwareRunning', False)
return ret
def get_hostname():
'''
Retrieves the hostname from the device.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_hostname
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', True)
try:
return ret['outConfigs']['mgmtIf'][0]['hostname']
except Exception as err:
return "Unable to retrieve hostname"
def get_ldap():
'''
Retrieves LDAP server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ldap
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaLdap', True)
return ret
def get_management_interface():
'''
Retrieve the management interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_management_interface
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', False)
return ret
def get_memory_token():
'''
Get the memory RAS BIOS token.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_token
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfSelectMemoryRASConfiguration', False)
return ret
def get_memory_unit():
'''
Get the IMM/Memory unit product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_unit
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogDimm', True)
return ret
def get_network_adapters():
'''
Get the list of network adapaters and configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_network_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('networkAdapterEthIf', True)
return ret
def get_ntp():
'''
Retrieves the current running NTP configuration.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ntp
'''
ret = __proxy__['cimc.get_config_resolver_class']('commNtpProvider', False)
return ret
def get_pci_adapters():
'''
Get the PCI adapter product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogPCIAdapter', True)
return ret
def get_power_configuration():
'''
Get the configuration of the power settings from the device. This is only available
on some C-Series servers.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_configuration
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfResumeOnACPowerLoss', True)
return ret
def get_power_supplies():
'''
Retrieves the power supply unit details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_supplies
'''
ret = __proxy__['cimc.get_config_resolver_class']('equipmentPsu', False)
return ret
def get_snmp_config():
'''
Get the snmp configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_snmp_config
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSnmp', False)
return ret
def get_syslog():
'''
Get the Syslog client-server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslogClient', False)
return ret
def get_syslog_settings():
'''
Get the Syslog configuration settings from the system.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslog', False)
return ret
def get_system_info():
'''
Get the system information.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_system_info
'''
ret = __proxy__['cimc.get_config_resolver_class']('computeRackUnit', False)
return ret
def get_users():
'''
Get the CIMC users.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_users
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaUser', False)
return ret
def get_vic_adapters():
'''
Get the VIC adapter general profile details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorGenProfile', True)
return ret
def get_vic_uplinks():
'''
Get the VIC adapter uplink port details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_uplinks
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorExtEthIf', True)
return ret
def mount_share(name=None,
remote_share=None,
remote_file=None,
mount_type="nfs",
username=None,
password=None):
'''
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media mounts can be scripted/automated
No vKVM requirements for media connection
Multiple share types supported
Connections supported through all CIMC interfaces
Note: CIMC Mounted vMedia is enabled through BIOS configuration.
Args:
name(str): The name of the volume on the CIMC device.
remote_share(str): The file share link that will be used to mount the share. This can be NFS, CIFS, or WWW. This
must be the directory path and not the full path to the remote file.
remote_file(str): The name of the remote file to mount. It must reside within remote_share.
mount_type(str): The type of share to mount. Valid options are nfs, cifs, and www.
username(str): An optional requirement to pass credentials to the remote share. If not provided, an
unauthenticated connection attempt will be made.
password(str): An optional requirement to pass a password to the remote share. If not provided, an
unauthenticated connection attempt will be made.
CLI Example:
.. code-block:: bash
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso username=bob password=badpassword
'''
if not name:
raise salt.exceptions.CommandExecutionError("The share name must be specified.")
if not remote_share:
raise salt.exceptions.CommandExecutionError("The remote share path must be specified.")
if not remote_file:
raise salt.exceptions.CommandExecutionError("The remote file name must be specified.")
if username and password:
mount_options = " mountOptions='username={0},password={1}'".format(username, password)
else:
mount_options = ""
dn = 'sys/svc-ext/vmedia-svc/vmmap-{0}'.format(name)
inconfig = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{0}' map='{1}'{2}
remoteFile='{3}' remoteShare='{4}' status='created'
volumeName='Win12' />""".format(name, mount_type, mount_options, remote_file, remote_share)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def reboot():
'''
Power cycling the server.
CLI Example:
.. code-block:: bash
salt '*' cimc.reboot
'''
dn = "sys/rack-unit-1"
inconfig = """<computeRackUnit adminPower="cycle-immediate" dn="sys/rack-unit-1"></computeRackUnit>"""
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_hostname(hostname=None):
'''
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
'''
if not hostname:
raise salt.exceptions.CommandExecutionError("Hostname option must be provided.")
dn = "sys/rack-unit-1/mgmt/if-1"
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{0}" ></mgmtIf>""".format(hostname)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
try:
if ret['outConfig']['mgmtIf'][0]['status'] == 'modified':
return True
else:
return False
except Exception as err:
return False
def set_logging_levels(remote=None, local=None):
'''
Sets the logging levels of the CIMC devices. The logging levels must match
the following options: emergency, alert, critical, error, warning, notice,
informational, debug.
.. versionadded:: 2019.2.0
Args:
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_logging_levels remote=error local=notice
'''
logging_options = ['emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'informational',
'debug']
query = ""
if remote:
if remote in logging_options:
query += ' remoteSeverity="{0}"'.format(remote)
else:
raise salt.exceptions.CommandExecutionError("Remote Severity option is not valid.")
if local:
if local in logging_options:
query += ' localSeverity="{0}"'.format(local)
else:
raise salt.exceptions.CommandExecutionError("Local Severity option is not valid.")
dn = "sys/svc-ext/syslog"
inconfig = """<commSyslog dn="sys/svc-ext/syslog"{0} ></commSyslog>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_ntp_server(server1='', server2='', server3='', server4=''):
'''
Sets the NTP servers configuration. This will also enable the client NTP service.
Args:
server1(str): The first IP address or FQDN of the NTP servers.
server2(str): The second IP address or FQDN of the NTP servers.
server3(str): The third IP address or FQDN of the NTP servers.
server4(str): The fourth IP address or FQDN of the NTP servers.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_ntp_server 10.10.10.1
salt '*' cimc.set_ntp_server 10.10.10.1 foo.bar.com
'''
dn = "sys/svc-ext/ntp-svc"
inconfig = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{0}" ntpServer2="{1}"
ntpServer3="{2}" ntpServer4="{3}"/>""".format(server1, server2, server3, server4)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_power_configuration stay-off
salt '*' cimc.set_power_configuration reset fixed 0
'''
query = ""
if policy == "reset":
query = ' vpResumeOnACPowerLoss="reset"'
if delayType:
if delayType == "fixed":
query += ' delayType="fixed"'
if delayValue:
query += ' delay="{0}"'.format(delayValue)
elif delayType == "random":
query += ' delayType="random"'
else:
raise salt.exceptions.CommandExecutionError("Invalid delay type entered.")
elif policy == "stay-off":
query = ' vpResumeOnACPowerLoss="reset"'
elif policy == "last-state":
query = ' vpResumeOnACPowerLoss="last-state"'
else:
raise salt.exceptions.CommandExecutionError("The power state must be specified.")
dn = "sys/rack-unit-1/board/Resume-on-AC-power-loss"
inconfig = """<biosVfResumeOnACPowerLoss
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{0}>
</biosVfResumeOnACPowerLoss>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_syslog_server(server=None, type="primary"):
'''
Set the SYSLOG server on the host.
Args:
server(str): The hostname or IP address of the SYSLOG server.
type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_syslog_server foo.bar.com
salt '*' cimc.set_syslog_server foo.bar.com primary
salt '*' cimc.set_syslog_server foo.bar.com secondary
'''
if not server:
raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.")
if type == "primary":
dn = "sys/svc-ext/syslog/client-primary"
inconfig = """<commSyslogClient name='primary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-primary'> </commSyslogClient>""".format(server)
elif type == "secondary":
dn = "sys/svc-ext/syslog/client-secondary"
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-secondary'> </commSyslogClient>""".format(server)
else:
raise salt.exceptions.CommandExecutionError("The SYSLOG type must be either primary or secondary.")
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
status(str): The account status of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
'''
conf = ""
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if status:
conf += ' accountStatus="{0}"'.format(status)
if username:
conf += ' name="{0}"'.format(username)
if priv:
conf += ' priv="{0}"'.format(priv)
if password:
conf += ' pwd="{0}"'.format(password)
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}"{1} dn="sys/user-ext/user-{0}"/>""".format(uid,
conf)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_bios(server=None, path=None):
'''
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/bios/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/bios/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-bios' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_cimc(server=None, path=None):
'''
Update the CIMC firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the CIMC image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_cimc foo.bar.com HP-SL2.bin
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/mgmt/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/mgmt/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-controller' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
saltstack/salt
|
salt/modules/cimc.py
|
mount_share
|
python
|
def mount_share(name=None,
remote_share=None,
remote_file=None,
mount_type="nfs",
username=None,
password=None):
'''
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media mounts can be scripted/automated
No vKVM requirements for media connection
Multiple share types supported
Connections supported through all CIMC interfaces
Note: CIMC Mounted vMedia is enabled through BIOS configuration.
Args:
name(str): The name of the volume on the CIMC device.
remote_share(str): The file share link that will be used to mount the share. This can be NFS, CIFS, or WWW. This
must be the directory path and not the full path to the remote file.
remote_file(str): The name of the remote file to mount. It must reside within remote_share.
mount_type(str): The type of share to mount. Valid options are nfs, cifs, and www.
username(str): An optional requirement to pass credentials to the remote share. If not provided, an
unauthenticated connection attempt will be made.
password(str): An optional requirement to pass a password to the remote share. If not provided, an
unauthenticated connection attempt will be made.
CLI Example:
.. code-block:: bash
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso username=bob password=badpassword
'''
if not name:
raise salt.exceptions.CommandExecutionError("The share name must be specified.")
if not remote_share:
raise salt.exceptions.CommandExecutionError("The remote share path must be specified.")
if not remote_file:
raise salt.exceptions.CommandExecutionError("The remote file name must be specified.")
if username and password:
mount_options = " mountOptions='username={0},password={1}'".format(username, password)
else:
mount_options = ""
dn = 'sys/svc-ext/vmedia-svc/vmmap-{0}'.format(name)
inconfig = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{0}' map='{1}'{2}
remoteFile='{3}' remoteShare='{4}' status='created'
volumeName='Win12' />""".format(name, mount_type, mount_options, remote_file, remote_share)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media mounts can be scripted/automated
No vKVM requirements for media connection
Multiple share types supported
Connections supported through all CIMC interfaces
Note: CIMC Mounted vMedia is enabled through BIOS configuration.
Args:
name(str): The name of the volume on the CIMC device.
remote_share(str): The file share link that will be used to mount the share. This can be NFS, CIFS, or WWW. This
must be the directory path and not the full path to the remote file.
remote_file(str): The name of the remote file to mount. It must reside within remote_share.
mount_type(str): The type of share to mount. Valid options are nfs, cifs, and www.
username(str): An optional requirement to pass credentials to the remote share. If not provided, an
unauthenticated connection attempt will be made.
password(str): An optional requirement to pass a password to the remote share. If not provided, an
unauthenticated connection attempt will be made.
CLI Example:
.. code-block:: bash
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso username=bob password=badpassword
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L542-L608
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Cisco UCS compatibility to Salt
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
Configuration
=============
This module accepts connection configuration details either as
parameters, or as configuration settings in pillar as a Salt proxy.
Options passed into opts will be ignored if options are passed into pillar.
.. seealso::
:py:mod:`Cisco UCS Proxy Module <salt.proxy.cimc>`
About
=====
This execution module was designed to handle connections to a Cisco UCS server.
This module adds support to send connections directly to the device through the
rest API.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.platform
import salt.proxy.cimc
log = logging.getLogger(__name__)
__virtualname__ = 'cimc'
def __virtual__():
'''
Will load for the cimc proxy minions.
'''
try:
if salt.utils.platform.is_proxy() and \
__opts__['proxy']['proxytype'] == 'cimc':
return __virtualname__
except KeyError:
pass
return False, 'The cimc execution module can only be loaded for cimc proxy minions.'
def activate_backup_image(reset=False):
'''
Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True
'''
dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True:
r = "yes"
inconfig = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""".format(r)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def create_user(uid=None, username=None, password=None, priv=None):
'''
Create a CIMC user with username and password.
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
'''
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if not username:
raise salt.exceptions.CommandExecutionError("The username must be specified.")
if not password:
raise salt.exceptions.CommandExecutionError("The password must be specified.")
if not priv:
raise salt.exceptions.CommandExecutionError("The privilege level must be specified.")
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}" accountStatus="active" name="{1}" priv="{2}"
pwd="{3}" dn="sys/user-ext/user-{0}"/>""".format(uid,
username,
priv,
password)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def get_bios_defaults():
'''
Get the default values of BIOS tokens.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_defaults
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosPlatformDefaults', True)
return ret
def get_bios_settings():
'''
Get the C240 server BIOS token values.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosSettings', True)
return ret
def get_boot_order():
'''
Retrieves the configured boot order table.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_boot_order
'''
ret = __proxy__['cimc.get_config_resolver_class']('lsbootDef', True)
return ret
def get_cpu_details():
'''
Get the CPU product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_cpu_details
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogCpu', True)
return ret
def get_disks():
'''
Get the HDD product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogHdd', True)
return ret
def get_ethernet_interfaces():
'''
Get the adapter Ethernet interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ethernet_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostEthIf', True)
return ret
def get_fibre_channel_interfaces():
'''
Get the adapter fibre channel interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_fibre_channel_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostFcIf', True)
return ret
def get_firmware():
'''
Retrieves the current running firmware versions of server components.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_firmware
'''
ret = __proxy__['cimc.get_config_resolver_class']('firmwareRunning', False)
return ret
def get_hostname():
'''
Retrieves the hostname from the device.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_hostname
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', True)
try:
return ret['outConfigs']['mgmtIf'][0]['hostname']
except Exception as err:
return "Unable to retrieve hostname"
def get_ldap():
'''
Retrieves LDAP server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ldap
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaLdap', True)
return ret
def get_management_interface():
'''
Retrieve the management interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_management_interface
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', False)
return ret
def get_memory_token():
'''
Get the memory RAS BIOS token.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_token
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfSelectMemoryRASConfiguration', False)
return ret
def get_memory_unit():
'''
Get the IMM/Memory unit product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_unit
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogDimm', True)
return ret
def get_network_adapters():
'''
Get the list of network adapaters and configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_network_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('networkAdapterEthIf', True)
return ret
def get_ntp():
'''
Retrieves the current running NTP configuration.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ntp
'''
ret = __proxy__['cimc.get_config_resolver_class']('commNtpProvider', False)
return ret
def get_pci_adapters():
'''
Get the PCI adapter product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogPCIAdapter', True)
return ret
def get_power_configuration():
'''
Get the configuration of the power settings from the device. This is only available
on some C-Series servers.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_configuration
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfResumeOnACPowerLoss', True)
return ret
def get_power_supplies():
'''
Retrieves the power supply unit details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_supplies
'''
ret = __proxy__['cimc.get_config_resolver_class']('equipmentPsu', False)
return ret
def get_snmp_config():
'''
Get the snmp configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_snmp_config
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSnmp', False)
return ret
def get_syslog():
'''
Get the Syslog client-server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslogClient', False)
return ret
def get_syslog_settings():
'''
Get the Syslog configuration settings from the system.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslog', False)
return ret
def get_system_info():
'''
Get the system information.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_system_info
'''
ret = __proxy__['cimc.get_config_resolver_class']('computeRackUnit', False)
return ret
def get_users():
'''
Get the CIMC users.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_users
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaUser', False)
return ret
def get_vic_adapters():
'''
Get the VIC adapter general profile details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorGenProfile', True)
return ret
def get_vic_uplinks():
'''
Get the VIC adapter uplink port details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_uplinks
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorExtEthIf', True)
return ret
def reboot():
'''
Power cycling the server.
CLI Example:
.. code-block:: bash
salt '*' cimc.reboot
'''
dn = "sys/rack-unit-1"
inconfig = """<computeRackUnit adminPower="cycle-immediate" dn="sys/rack-unit-1"></computeRackUnit>"""
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_hostname(hostname=None):
'''
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
'''
if not hostname:
raise salt.exceptions.CommandExecutionError("Hostname option must be provided.")
dn = "sys/rack-unit-1/mgmt/if-1"
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{0}" ></mgmtIf>""".format(hostname)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
try:
if ret['outConfig']['mgmtIf'][0]['status'] == 'modified':
return True
else:
return False
except Exception as err:
return False
def set_logging_levels(remote=None, local=None):
'''
Sets the logging levels of the CIMC devices. The logging levels must match
the following options: emergency, alert, critical, error, warning, notice,
informational, debug.
.. versionadded:: 2019.2.0
Args:
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_logging_levels remote=error local=notice
'''
logging_options = ['emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'informational',
'debug']
query = ""
if remote:
if remote in logging_options:
query += ' remoteSeverity="{0}"'.format(remote)
else:
raise salt.exceptions.CommandExecutionError("Remote Severity option is not valid.")
if local:
if local in logging_options:
query += ' localSeverity="{0}"'.format(local)
else:
raise salt.exceptions.CommandExecutionError("Local Severity option is not valid.")
dn = "sys/svc-ext/syslog"
inconfig = """<commSyslog dn="sys/svc-ext/syslog"{0} ></commSyslog>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_ntp_server(server1='', server2='', server3='', server4=''):
'''
Sets the NTP servers configuration. This will also enable the client NTP service.
Args:
server1(str): The first IP address or FQDN of the NTP servers.
server2(str): The second IP address or FQDN of the NTP servers.
server3(str): The third IP address or FQDN of the NTP servers.
server4(str): The fourth IP address or FQDN of the NTP servers.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_ntp_server 10.10.10.1
salt '*' cimc.set_ntp_server 10.10.10.1 foo.bar.com
'''
dn = "sys/svc-ext/ntp-svc"
inconfig = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{0}" ntpServer2="{1}"
ntpServer3="{2}" ntpServer4="{3}"/>""".format(server1, server2, server3, server4)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_power_configuration stay-off
salt '*' cimc.set_power_configuration reset fixed 0
'''
query = ""
if policy == "reset":
query = ' vpResumeOnACPowerLoss="reset"'
if delayType:
if delayType == "fixed":
query += ' delayType="fixed"'
if delayValue:
query += ' delay="{0}"'.format(delayValue)
elif delayType == "random":
query += ' delayType="random"'
else:
raise salt.exceptions.CommandExecutionError("Invalid delay type entered.")
elif policy == "stay-off":
query = ' vpResumeOnACPowerLoss="reset"'
elif policy == "last-state":
query = ' vpResumeOnACPowerLoss="last-state"'
else:
raise salt.exceptions.CommandExecutionError("The power state must be specified.")
dn = "sys/rack-unit-1/board/Resume-on-AC-power-loss"
inconfig = """<biosVfResumeOnACPowerLoss
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{0}>
</biosVfResumeOnACPowerLoss>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_syslog_server(server=None, type="primary"):
'''
Set the SYSLOG server on the host.
Args:
server(str): The hostname or IP address of the SYSLOG server.
type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_syslog_server foo.bar.com
salt '*' cimc.set_syslog_server foo.bar.com primary
salt '*' cimc.set_syslog_server foo.bar.com secondary
'''
if not server:
raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.")
if type == "primary":
dn = "sys/svc-ext/syslog/client-primary"
inconfig = """<commSyslogClient name='primary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-primary'> </commSyslogClient>""".format(server)
elif type == "secondary":
dn = "sys/svc-ext/syslog/client-secondary"
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-secondary'> </commSyslogClient>""".format(server)
else:
raise salt.exceptions.CommandExecutionError("The SYSLOG type must be either primary or secondary.")
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
status(str): The account status of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
'''
conf = ""
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if status:
conf += ' accountStatus="{0}"'.format(status)
if username:
conf += ' name="{0}"'.format(username)
if priv:
conf += ' priv="{0}"'.format(priv)
if password:
conf += ' pwd="{0}"'.format(password)
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}"{1} dn="sys/user-ext/user-{0}"/>""".format(uid,
conf)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_bios(server=None, path=None):
'''
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/bios/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/bios/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-bios' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_cimc(server=None, path=None):
'''
Update the CIMC firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the CIMC image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_cimc foo.bar.com HP-SL2.bin
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/mgmt/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/mgmt/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-controller' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
saltstack/salt
|
salt/modules/cimc.py
|
set_hostname
|
python
|
def set_hostname(hostname=None):
'''
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
'''
if not hostname:
raise salt.exceptions.CommandExecutionError("Hostname option must be provided.")
dn = "sys/rack-unit-1/mgmt/if-1"
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{0}" ></mgmtIf>""".format(hostname)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
try:
if ret['outConfig']['mgmtIf'][0]['status'] == 'modified':
return True
else:
return False
except Exception as err:
return False
|
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L632-L662
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Cisco UCS compatibility to Salt
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
Configuration
=============
This module accepts connection configuration details either as
parameters, or as configuration settings in pillar as a Salt proxy.
Options passed into opts will be ignored if options are passed into pillar.
.. seealso::
:py:mod:`Cisco UCS Proxy Module <salt.proxy.cimc>`
About
=====
This execution module was designed to handle connections to a Cisco UCS server.
This module adds support to send connections directly to the device through the
rest API.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.platform
import salt.proxy.cimc
log = logging.getLogger(__name__)
__virtualname__ = 'cimc'
def __virtual__():
'''
Will load for the cimc proxy minions.
'''
try:
if salt.utils.platform.is_proxy() and \
__opts__['proxy']['proxytype'] == 'cimc':
return __virtualname__
except KeyError:
pass
return False, 'The cimc execution module can only be loaded for cimc proxy minions.'
def activate_backup_image(reset=False):
'''
Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True
'''
dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True:
r = "yes"
inconfig = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""".format(r)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def create_user(uid=None, username=None, password=None, priv=None):
'''
Create a CIMC user with username and password.
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
'''
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if not username:
raise salt.exceptions.CommandExecutionError("The username must be specified.")
if not password:
raise salt.exceptions.CommandExecutionError("The password must be specified.")
if not priv:
raise salt.exceptions.CommandExecutionError("The privilege level must be specified.")
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}" accountStatus="active" name="{1}" priv="{2}"
pwd="{3}" dn="sys/user-ext/user-{0}"/>""".format(uid,
username,
priv,
password)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def get_bios_defaults():
'''
Get the default values of BIOS tokens.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_defaults
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosPlatformDefaults', True)
return ret
def get_bios_settings():
'''
Get the C240 server BIOS token values.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosSettings', True)
return ret
def get_boot_order():
'''
Retrieves the configured boot order table.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_boot_order
'''
ret = __proxy__['cimc.get_config_resolver_class']('lsbootDef', True)
return ret
def get_cpu_details():
'''
Get the CPU product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_cpu_details
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogCpu', True)
return ret
def get_disks():
'''
Get the HDD product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogHdd', True)
return ret
def get_ethernet_interfaces():
'''
Get the adapter Ethernet interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ethernet_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostEthIf', True)
return ret
def get_fibre_channel_interfaces():
'''
Get the adapter fibre channel interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_fibre_channel_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostFcIf', True)
return ret
def get_firmware():
'''
Retrieves the current running firmware versions of server components.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_firmware
'''
ret = __proxy__['cimc.get_config_resolver_class']('firmwareRunning', False)
return ret
def get_hostname():
'''
Retrieves the hostname from the device.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_hostname
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', True)
try:
return ret['outConfigs']['mgmtIf'][0]['hostname']
except Exception as err:
return "Unable to retrieve hostname"
def get_ldap():
'''
Retrieves LDAP server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ldap
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaLdap', True)
return ret
def get_management_interface():
'''
Retrieve the management interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_management_interface
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', False)
return ret
def get_memory_token():
'''
Get the memory RAS BIOS token.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_token
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfSelectMemoryRASConfiguration', False)
return ret
def get_memory_unit():
'''
Get the IMM/Memory unit product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_unit
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogDimm', True)
return ret
def get_network_adapters():
'''
Get the list of network adapaters and configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_network_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('networkAdapterEthIf', True)
return ret
def get_ntp():
'''
Retrieves the current running NTP configuration.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ntp
'''
ret = __proxy__['cimc.get_config_resolver_class']('commNtpProvider', False)
return ret
def get_pci_adapters():
'''
Get the PCI adapter product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogPCIAdapter', True)
return ret
def get_power_configuration():
'''
Get the configuration of the power settings from the device. This is only available
on some C-Series servers.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_configuration
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfResumeOnACPowerLoss', True)
return ret
def get_power_supplies():
'''
Retrieves the power supply unit details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_supplies
'''
ret = __proxy__['cimc.get_config_resolver_class']('equipmentPsu', False)
return ret
def get_snmp_config():
'''
Get the snmp configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_snmp_config
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSnmp', False)
return ret
def get_syslog():
'''
Get the Syslog client-server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslogClient', False)
return ret
def get_syslog_settings():
'''
Get the Syslog configuration settings from the system.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslog', False)
return ret
def get_system_info():
'''
Get the system information.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_system_info
'''
ret = __proxy__['cimc.get_config_resolver_class']('computeRackUnit', False)
return ret
def get_users():
'''
Get the CIMC users.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_users
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaUser', False)
return ret
def get_vic_adapters():
'''
Get the VIC adapter general profile details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorGenProfile', True)
return ret
def get_vic_uplinks():
'''
Get the VIC adapter uplink port details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_uplinks
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorExtEthIf', True)
return ret
def mount_share(name=None,
remote_share=None,
remote_file=None,
mount_type="nfs",
username=None,
password=None):
'''
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media mounts can be scripted/automated
No vKVM requirements for media connection
Multiple share types supported
Connections supported through all CIMC interfaces
Note: CIMC Mounted vMedia is enabled through BIOS configuration.
Args:
name(str): The name of the volume on the CIMC device.
remote_share(str): The file share link that will be used to mount the share. This can be NFS, CIFS, or WWW. This
must be the directory path and not the full path to the remote file.
remote_file(str): The name of the remote file to mount. It must reside within remote_share.
mount_type(str): The type of share to mount. Valid options are nfs, cifs, and www.
username(str): An optional requirement to pass credentials to the remote share. If not provided, an
unauthenticated connection attempt will be made.
password(str): An optional requirement to pass a password to the remote share. If not provided, an
unauthenticated connection attempt will be made.
CLI Example:
.. code-block:: bash
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso username=bob password=badpassword
'''
if not name:
raise salt.exceptions.CommandExecutionError("The share name must be specified.")
if not remote_share:
raise salt.exceptions.CommandExecutionError("The remote share path must be specified.")
if not remote_file:
raise salt.exceptions.CommandExecutionError("The remote file name must be specified.")
if username and password:
mount_options = " mountOptions='username={0},password={1}'".format(username, password)
else:
mount_options = ""
dn = 'sys/svc-ext/vmedia-svc/vmmap-{0}'.format(name)
inconfig = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{0}' map='{1}'{2}
remoteFile='{3}' remoteShare='{4}' status='created'
volumeName='Win12' />""".format(name, mount_type, mount_options, remote_file, remote_share)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def reboot():
'''
Power cycling the server.
CLI Example:
.. code-block:: bash
salt '*' cimc.reboot
'''
dn = "sys/rack-unit-1"
inconfig = """<computeRackUnit adminPower="cycle-immediate" dn="sys/rack-unit-1"></computeRackUnit>"""
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_logging_levels(remote=None, local=None):
'''
Sets the logging levels of the CIMC devices. The logging levels must match
the following options: emergency, alert, critical, error, warning, notice,
informational, debug.
.. versionadded:: 2019.2.0
Args:
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_logging_levels remote=error local=notice
'''
logging_options = ['emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'informational',
'debug']
query = ""
if remote:
if remote in logging_options:
query += ' remoteSeverity="{0}"'.format(remote)
else:
raise salt.exceptions.CommandExecutionError("Remote Severity option is not valid.")
if local:
if local in logging_options:
query += ' localSeverity="{0}"'.format(local)
else:
raise salt.exceptions.CommandExecutionError("Local Severity option is not valid.")
dn = "sys/svc-ext/syslog"
inconfig = """<commSyslog dn="sys/svc-ext/syslog"{0} ></commSyslog>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_ntp_server(server1='', server2='', server3='', server4=''):
'''
Sets the NTP servers configuration. This will also enable the client NTP service.
Args:
server1(str): The first IP address or FQDN of the NTP servers.
server2(str): The second IP address or FQDN of the NTP servers.
server3(str): The third IP address or FQDN of the NTP servers.
server4(str): The fourth IP address or FQDN of the NTP servers.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_ntp_server 10.10.10.1
salt '*' cimc.set_ntp_server 10.10.10.1 foo.bar.com
'''
dn = "sys/svc-ext/ntp-svc"
inconfig = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{0}" ntpServer2="{1}"
ntpServer3="{2}" ntpServer4="{3}"/>""".format(server1, server2, server3, server4)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_power_configuration stay-off
salt '*' cimc.set_power_configuration reset fixed 0
'''
query = ""
if policy == "reset":
query = ' vpResumeOnACPowerLoss="reset"'
if delayType:
if delayType == "fixed":
query += ' delayType="fixed"'
if delayValue:
query += ' delay="{0}"'.format(delayValue)
elif delayType == "random":
query += ' delayType="random"'
else:
raise salt.exceptions.CommandExecutionError("Invalid delay type entered.")
elif policy == "stay-off":
query = ' vpResumeOnACPowerLoss="reset"'
elif policy == "last-state":
query = ' vpResumeOnACPowerLoss="last-state"'
else:
raise salt.exceptions.CommandExecutionError("The power state must be specified.")
dn = "sys/rack-unit-1/board/Resume-on-AC-power-loss"
inconfig = """<biosVfResumeOnACPowerLoss
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{0}>
</biosVfResumeOnACPowerLoss>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_syslog_server(server=None, type="primary"):
'''
Set the SYSLOG server on the host.
Args:
server(str): The hostname or IP address of the SYSLOG server.
type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_syslog_server foo.bar.com
salt '*' cimc.set_syslog_server foo.bar.com primary
salt '*' cimc.set_syslog_server foo.bar.com secondary
'''
if not server:
raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.")
if type == "primary":
dn = "sys/svc-ext/syslog/client-primary"
inconfig = """<commSyslogClient name='primary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-primary'> </commSyslogClient>""".format(server)
elif type == "secondary":
dn = "sys/svc-ext/syslog/client-secondary"
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-secondary'> </commSyslogClient>""".format(server)
else:
raise salt.exceptions.CommandExecutionError("The SYSLOG type must be either primary or secondary.")
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
status(str): The account status of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
'''
conf = ""
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if status:
conf += ' accountStatus="{0}"'.format(status)
if username:
conf += ' name="{0}"'.format(username)
if priv:
conf += ' priv="{0}"'.format(priv)
if password:
conf += ' pwd="{0}"'.format(password)
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}"{1} dn="sys/user-ext/user-{0}"/>""".format(uid,
conf)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_bios(server=None, path=None):
'''
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/bios/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/bios/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-bios' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_cimc(server=None, path=None):
'''
Update the CIMC firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the CIMC image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_cimc foo.bar.com HP-SL2.bin
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/mgmt/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/mgmt/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-controller' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
saltstack/salt
|
salt/modules/cimc.py
|
set_logging_levels
|
python
|
def set_logging_levels(remote=None, local=None):
'''
Sets the logging levels of the CIMC devices. The logging levels must match
the following options: emergency, alert, critical, error, warning, notice,
informational, debug.
.. versionadded:: 2019.2.0
Args:
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_logging_levels remote=error local=notice
'''
logging_options = ['emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'informational',
'debug']
query = ""
if remote:
if remote in logging_options:
query += ' remoteSeverity="{0}"'.format(remote)
else:
raise salt.exceptions.CommandExecutionError("Remote Severity option is not valid.")
if local:
if local in logging_options:
query += ' localSeverity="{0}"'.format(local)
else:
raise salt.exceptions.CommandExecutionError("Local Severity option is not valid.")
dn = "sys/svc-ext/syslog"
inconfig = """<commSyslog dn="sys/svc-ext/syslog"{0} ></commSyslog>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
Sets the logging levels of the CIMC devices. The logging levels must match
the following options: emergency, alert, critical, error, warning, notice,
informational, debug.
.. versionadded:: 2019.2.0
Args:
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_logging_levels remote=error local=notice
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L665-L714
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Cisco UCS compatibility to Salt
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
Configuration
=============
This module accepts connection configuration details either as
parameters, or as configuration settings in pillar as a Salt proxy.
Options passed into opts will be ignored if options are passed into pillar.
.. seealso::
:py:mod:`Cisco UCS Proxy Module <salt.proxy.cimc>`
About
=====
This execution module was designed to handle connections to a Cisco UCS server.
This module adds support to send connections directly to the device through the
rest API.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.platform
import salt.proxy.cimc
log = logging.getLogger(__name__)
__virtualname__ = 'cimc'
def __virtual__():
'''
Will load for the cimc proxy minions.
'''
try:
if salt.utils.platform.is_proxy() and \
__opts__['proxy']['proxytype'] == 'cimc':
return __virtualname__
except KeyError:
pass
return False, 'The cimc execution module can only be loaded for cimc proxy minions.'
def activate_backup_image(reset=False):
'''
Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True
'''
dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True:
r = "yes"
inconfig = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""".format(r)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def create_user(uid=None, username=None, password=None, priv=None):
'''
Create a CIMC user with username and password.
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
'''
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if not username:
raise salt.exceptions.CommandExecutionError("The username must be specified.")
if not password:
raise salt.exceptions.CommandExecutionError("The password must be specified.")
if not priv:
raise salt.exceptions.CommandExecutionError("The privilege level must be specified.")
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}" accountStatus="active" name="{1}" priv="{2}"
pwd="{3}" dn="sys/user-ext/user-{0}"/>""".format(uid,
username,
priv,
password)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def get_bios_defaults():
'''
Get the default values of BIOS tokens.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_defaults
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosPlatformDefaults', True)
return ret
def get_bios_settings():
'''
Get the C240 server BIOS token values.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosSettings', True)
return ret
def get_boot_order():
'''
Retrieves the configured boot order table.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_boot_order
'''
ret = __proxy__['cimc.get_config_resolver_class']('lsbootDef', True)
return ret
def get_cpu_details():
'''
Get the CPU product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_cpu_details
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogCpu', True)
return ret
def get_disks():
'''
Get the HDD product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogHdd', True)
return ret
def get_ethernet_interfaces():
'''
Get the adapter Ethernet interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ethernet_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostEthIf', True)
return ret
def get_fibre_channel_interfaces():
'''
Get the adapter fibre channel interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_fibre_channel_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostFcIf', True)
return ret
def get_firmware():
'''
Retrieves the current running firmware versions of server components.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_firmware
'''
ret = __proxy__['cimc.get_config_resolver_class']('firmwareRunning', False)
return ret
def get_hostname():
'''
Retrieves the hostname from the device.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_hostname
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', True)
try:
return ret['outConfigs']['mgmtIf'][0]['hostname']
except Exception as err:
return "Unable to retrieve hostname"
def get_ldap():
'''
Retrieves LDAP server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ldap
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaLdap', True)
return ret
def get_management_interface():
'''
Retrieve the management interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_management_interface
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', False)
return ret
def get_memory_token():
'''
Get the memory RAS BIOS token.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_token
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfSelectMemoryRASConfiguration', False)
return ret
def get_memory_unit():
'''
Get the IMM/Memory unit product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_unit
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogDimm', True)
return ret
def get_network_adapters():
'''
Get the list of network adapaters and configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_network_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('networkAdapterEthIf', True)
return ret
def get_ntp():
'''
Retrieves the current running NTP configuration.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ntp
'''
ret = __proxy__['cimc.get_config_resolver_class']('commNtpProvider', False)
return ret
def get_pci_adapters():
'''
Get the PCI adapter product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogPCIAdapter', True)
return ret
def get_power_configuration():
'''
Get the configuration of the power settings from the device. This is only available
on some C-Series servers.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_configuration
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfResumeOnACPowerLoss', True)
return ret
def get_power_supplies():
'''
Retrieves the power supply unit details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_supplies
'''
ret = __proxy__['cimc.get_config_resolver_class']('equipmentPsu', False)
return ret
def get_snmp_config():
'''
Get the snmp configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_snmp_config
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSnmp', False)
return ret
def get_syslog():
'''
Get the Syslog client-server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslogClient', False)
return ret
def get_syslog_settings():
'''
Get the Syslog configuration settings from the system.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslog', False)
return ret
def get_system_info():
'''
Get the system information.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_system_info
'''
ret = __proxy__['cimc.get_config_resolver_class']('computeRackUnit', False)
return ret
def get_users():
'''
Get the CIMC users.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_users
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaUser', False)
return ret
def get_vic_adapters():
'''
Get the VIC adapter general profile details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorGenProfile', True)
return ret
def get_vic_uplinks():
'''
Get the VIC adapter uplink port details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_uplinks
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorExtEthIf', True)
return ret
def mount_share(name=None,
remote_share=None,
remote_file=None,
mount_type="nfs",
username=None,
password=None):
'''
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media mounts can be scripted/automated
No vKVM requirements for media connection
Multiple share types supported
Connections supported through all CIMC interfaces
Note: CIMC Mounted vMedia is enabled through BIOS configuration.
Args:
name(str): The name of the volume on the CIMC device.
remote_share(str): The file share link that will be used to mount the share. This can be NFS, CIFS, or WWW. This
must be the directory path and not the full path to the remote file.
remote_file(str): The name of the remote file to mount. It must reside within remote_share.
mount_type(str): The type of share to mount. Valid options are nfs, cifs, and www.
username(str): An optional requirement to pass credentials to the remote share. If not provided, an
unauthenticated connection attempt will be made.
password(str): An optional requirement to pass a password to the remote share. If not provided, an
unauthenticated connection attempt will be made.
CLI Example:
.. code-block:: bash
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso username=bob password=badpassword
'''
if not name:
raise salt.exceptions.CommandExecutionError("The share name must be specified.")
if not remote_share:
raise salt.exceptions.CommandExecutionError("The remote share path must be specified.")
if not remote_file:
raise salt.exceptions.CommandExecutionError("The remote file name must be specified.")
if username and password:
mount_options = " mountOptions='username={0},password={1}'".format(username, password)
else:
mount_options = ""
dn = 'sys/svc-ext/vmedia-svc/vmmap-{0}'.format(name)
inconfig = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{0}' map='{1}'{2}
remoteFile='{3}' remoteShare='{4}' status='created'
volumeName='Win12' />""".format(name, mount_type, mount_options, remote_file, remote_share)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def reboot():
'''
Power cycling the server.
CLI Example:
.. code-block:: bash
salt '*' cimc.reboot
'''
dn = "sys/rack-unit-1"
inconfig = """<computeRackUnit adminPower="cycle-immediate" dn="sys/rack-unit-1"></computeRackUnit>"""
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_hostname(hostname=None):
'''
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
'''
if not hostname:
raise salt.exceptions.CommandExecutionError("Hostname option must be provided.")
dn = "sys/rack-unit-1/mgmt/if-1"
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{0}" ></mgmtIf>""".format(hostname)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
try:
if ret['outConfig']['mgmtIf'][0]['status'] == 'modified':
return True
else:
return False
except Exception as err:
return False
def set_ntp_server(server1='', server2='', server3='', server4=''):
'''
Sets the NTP servers configuration. This will also enable the client NTP service.
Args:
server1(str): The first IP address or FQDN of the NTP servers.
server2(str): The second IP address or FQDN of the NTP servers.
server3(str): The third IP address or FQDN of the NTP servers.
server4(str): The fourth IP address or FQDN of the NTP servers.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_ntp_server 10.10.10.1
salt '*' cimc.set_ntp_server 10.10.10.1 foo.bar.com
'''
dn = "sys/svc-ext/ntp-svc"
inconfig = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{0}" ntpServer2="{1}"
ntpServer3="{2}" ntpServer4="{3}"/>""".format(server1, server2, server3, server4)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_power_configuration stay-off
salt '*' cimc.set_power_configuration reset fixed 0
'''
query = ""
if policy == "reset":
query = ' vpResumeOnACPowerLoss="reset"'
if delayType:
if delayType == "fixed":
query += ' delayType="fixed"'
if delayValue:
query += ' delay="{0}"'.format(delayValue)
elif delayType == "random":
query += ' delayType="random"'
else:
raise salt.exceptions.CommandExecutionError("Invalid delay type entered.")
elif policy == "stay-off":
query = ' vpResumeOnACPowerLoss="reset"'
elif policy == "last-state":
query = ' vpResumeOnACPowerLoss="last-state"'
else:
raise salt.exceptions.CommandExecutionError("The power state must be specified.")
dn = "sys/rack-unit-1/board/Resume-on-AC-power-loss"
inconfig = """<biosVfResumeOnACPowerLoss
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{0}>
</biosVfResumeOnACPowerLoss>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_syslog_server(server=None, type="primary"):
'''
Set the SYSLOG server on the host.
Args:
server(str): The hostname or IP address of the SYSLOG server.
type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_syslog_server foo.bar.com
salt '*' cimc.set_syslog_server foo.bar.com primary
salt '*' cimc.set_syslog_server foo.bar.com secondary
'''
if not server:
raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.")
if type == "primary":
dn = "sys/svc-ext/syslog/client-primary"
inconfig = """<commSyslogClient name='primary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-primary'> </commSyslogClient>""".format(server)
elif type == "secondary":
dn = "sys/svc-ext/syslog/client-secondary"
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-secondary'> </commSyslogClient>""".format(server)
else:
raise salt.exceptions.CommandExecutionError("The SYSLOG type must be either primary or secondary.")
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
status(str): The account status of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
'''
conf = ""
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if status:
conf += ' accountStatus="{0}"'.format(status)
if username:
conf += ' name="{0}"'.format(username)
if priv:
conf += ' priv="{0}"'.format(priv)
if password:
conf += ' pwd="{0}"'.format(password)
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}"{1} dn="sys/user-ext/user-{0}"/>""".format(uid,
conf)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_bios(server=None, path=None):
'''
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/bios/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/bios/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-bios' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_cimc(server=None, path=None):
'''
Update the CIMC firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the CIMC image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_cimc foo.bar.com HP-SL2.bin
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/mgmt/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/mgmt/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-controller' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
saltstack/salt
|
salt/modules/cimc.py
|
set_ntp_server
|
python
|
def set_ntp_server(server1='', server2='', server3='', server4=''):
'''
Sets the NTP servers configuration. This will also enable the client NTP service.
Args:
server1(str): The first IP address or FQDN of the NTP servers.
server2(str): The second IP address or FQDN of the NTP servers.
server3(str): The third IP address or FQDN of the NTP servers.
server4(str): The fourth IP address or FQDN of the NTP servers.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_ntp_server 10.10.10.1
salt '*' cimc.set_ntp_server 10.10.10.1 foo.bar.com
'''
dn = "sys/svc-ext/ntp-svc"
inconfig = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{0}" ntpServer2="{1}"
ntpServer3="{2}" ntpServer4="{3}"/>""".format(server1, server2, server3, server4)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
Sets the NTP servers configuration. This will also enable the client NTP service.
Args:
server1(str): The first IP address or FQDN of the NTP servers.
server2(str): The second IP address or FQDN of the NTP servers.
server3(str): The third IP address or FQDN of the NTP servers.
server4(str): The fourth IP address or FQDN of the NTP servers.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_ntp_server 10.10.10.1
salt '*' cimc.set_ntp_server 10.10.10.1 foo.bar.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L717-L746
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Cisco UCS compatibility to Salt
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
Configuration
=============
This module accepts connection configuration details either as
parameters, or as configuration settings in pillar as a Salt proxy.
Options passed into opts will be ignored if options are passed into pillar.
.. seealso::
:py:mod:`Cisco UCS Proxy Module <salt.proxy.cimc>`
About
=====
This execution module was designed to handle connections to a Cisco UCS server.
This module adds support to send connections directly to the device through the
rest API.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.platform
import salt.proxy.cimc
log = logging.getLogger(__name__)
__virtualname__ = 'cimc'
def __virtual__():
'''
Will load for the cimc proxy minions.
'''
try:
if salt.utils.platform.is_proxy() and \
__opts__['proxy']['proxytype'] == 'cimc':
return __virtualname__
except KeyError:
pass
return False, 'The cimc execution module can only be loaded for cimc proxy minions.'
def activate_backup_image(reset=False):
'''
Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True
'''
dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True:
r = "yes"
inconfig = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""".format(r)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def create_user(uid=None, username=None, password=None, priv=None):
'''
Create a CIMC user with username and password.
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
'''
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if not username:
raise salt.exceptions.CommandExecutionError("The username must be specified.")
if not password:
raise salt.exceptions.CommandExecutionError("The password must be specified.")
if not priv:
raise salt.exceptions.CommandExecutionError("The privilege level must be specified.")
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}" accountStatus="active" name="{1}" priv="{2}"
pwd="{3}" dn="sys/user-ext/user-{0}"/>""".format(uid,
username,
priv,
password)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def get_bios_defaults():
'''
Get the default values of BIOS tokens.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_defaults
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosPlatformDefaults', True)
return ret
def get_bios_settings():
'''
Get the C240 server BIOS token values.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosSettings', True)
return ret
def get_boot_order():
'''
Retrieves the configured boot order table.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_boot_order
'''
ret = __proxy__['cimc.get_config_resolver_class']('lsbootDef', True)
return ret
def get_cpu_details():
'''
Get the CPU product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_cpu_details
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogCpu', True)
return ret
def get_disks():
'''
Get the HDD product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogHdd', True)
return ret
def get_ethernet_interfaces():
'''
Get the adapter Ethernet interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ethernet_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostEthIf', True)
return ret
def get_fibre_channel_interfaces():
'''
Get the adapter fibre channel interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_fibre_channel_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostFcIf', True)
return ret
def get_firmware():
'''
Retrieves the current running firmware versions of server components.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_firmware
'''
ret = __proxy__['cimc.get_config_resolver_class']('firmwareRunning', False)
return ret
def get_hostname():
'''
Retrieves the hostname from the device.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_hostname
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', True)
try:
return ret['outConfigs']['mgmtIf'][0]['hostname']
except Exception as err:
return "Unable to retrieve hostname"
def get_ldap():
'''
Retrieves LDAP server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ldap
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaLdap', True)
return ret
def get_management_interface():
'''
Retrieve the management interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_management_interface
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', False)
return ret
def get_memory_token():
'''
Get the memory RAS BIOS token.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_token
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfSelectMemoryRASConfiguration', False)
return ret
def get_memory_unit():
'''
Get the IMM/Memory unit product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_unit
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogDimm', True)
return ret
def get_network_adapters():
'''
Get the list of network adapaters and configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_network_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('networkAdapterEthIf', True)
return ret
def get_ntp():
'''
Retrieves the current running NTP configuration.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ntp
'''
ret = __proxy__['cimc.get_config_resolver_class']('commNtpProvider', False)
return ret
def get_pci_adapters():
'''
Get the PCI adapter product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogPCIAdapter', True)
return ret
def get_power_configuration():
'''
Get the configuration of the power settings from the device. This is only available
on some C-Series servers.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_configuration
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfResumeOnACPowerLoss', True)
return ret
def get_power_supplies():
'''
Retrieves the power supply unit details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_supplies
'''
ret = __proxy__['cimc.get_config_resolver_class']('equipmentPsu', False)
return ret
def get_snmp_config():
'''
Get the snmp configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_snmp_config
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSnmp', False)
return ret
def get_syslog():
'''
Get the Syslog client-server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslogClient', False)
return ret
def get_syslog_settings():
'''
Get the Syslog configuration settings from the system.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslog', False)
return ret
def get_system_info():
'''
Get the system information.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_system_info
'''
ret = __proxy__['cimc.get_config_resolver_class']('computeRackUnit', False)
return ret
def get_users():
'''
Get the CIMC users.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_users
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaUser', False)
return ret
def get_vic_adapters():
'''
Get the VIC adapter general profile details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorGenProfile', True)
return ret
def get_vic_uplinks():
'''
Get the VIC adapter uplink port details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_uplinks
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorExtEthIf', True)
return ret
def mount_share(name=None,
remote_share=None,
remote_file=None,
mount_type="nfs",
username=None,
password=None):
'''
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media mounts can be scripted/automated
No vKVM requirements for media connection
Multiple share types supported
Connections supported through all CIMC interfaces
Note: CIMC Mounted vMedia is enabled through BIOS configuration.
Args:
name(str): The name of the volume on the CIMC device.
remote_share(str): The file share link that will be used to mount the share. This can be NFS, CIFS, or WWW. This
must be the directory path and not the full path to the remote file.
remote_file(str): The name of the remote file to mount. It must reside within remote_share.
mount_type(str): The type of share to mount. Valid options are nfs, cifs, and www.
username(str): An optional requirement to pass credentials to the remote share. If not provided, an
unauthenticated connection attempt will be made.
password(str): An optional requirement to pass a password to the remote share. If not provided, an
unauthenticated connection attempt will be made.
CLI Example:
.. code-block:: bash
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso username=bob password=badpassword
'''
if not name:
raise salt.exceptions.CommandExecutionError("The share name must be specified.")
if not remote_share:
raise salt.exceptions.CommandExecutionError("The remote share path must be specified.")
if not remote_file:
raise salt.exceptions.CommandExecutionError("The remote file name must be specified.")
if username and password:
mount_options = " mountOptions='username={0},password={1}'".format(username, password)
else:
mount_options = ""
dn = 'sys/svc-ext/vmedia-svc/vmmap-{0}'.format(name)
inconfig = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{0}' map='{1}'{2}
remoteFile='{3}' remoteShare='{4}' status='created'
volumeName='Win12' />""".format(name, mount_type, mount_options, remote_file, remote_share)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def reboot():
'''
Power cycling the server.
CLI Example:
.. code-block:: bash
salt '*' cimc.reboot
'''
dn = "sys/rack-unit-1"
inconfig = """<computeRackUnit adminPower="cycle-immediate" dn="sys/rack-unit-1"></computeRackUnit>"""
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_hostname(hostname=None):
'''
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
'''
if not hostname:
raise salt.exceptions.CommandExecutionError("Hostname option must be provided.")
dn = "sys/rack-unit-1/mgmt/if-1"
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{0}" ></mgmtIf>""".format(hostname)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
try:
if ret['outConfig']['mgmtIf'][0]['status'] == 'modified':
return True
else:
return False
except Exception as err:
return False
def set_logging_levels(remote=None, local=None):
'''
Sets the logging levels of the CIMC devices. The logging levels must match
the following options: emergency, alert, critical, error, warning, notice,
informational, debug.
.. versionadded:: 2019.2.0
Args:
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_logging_levels remote=error local=notice
'''
logging_options = ['emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'informational',
'debug']
query = ""
if remote:
if remote in logging_options:
query += ' remoteSeverity="{0}"'.format(remote)
else:
raise salt.exceptions.CommandExecutionError("Remote Severity option is not valid.")
if local:
if local in logging_options:
query += ' localSeverity="{0}"'.format(local)
else:
raise salt.exceptions.CommandExecutionError("Local Severity option is not valid.")
dn = "sys/svc-ext/syslog"
inconfig = """<commSyslog dn="sys/svc-ext/syslog"{0} ></commSyslog>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_power_configuration stay-off
salt '*' cimc.set_power_configuration reset fixed 0
'''
query = ""
if policy == "reset":
query = ' vpResumeOnACPowerLoss="reset"'
if delayType:
if delayType == "fixed":
query += ' delayType="fixed"'
if delayValue:
query += ' delay="{0}"'.format(delayValue)
elif delayType == "random":
query += ' delayType="random"'
else:
raise salt.exceptions.CommandExecutionError("Invalid delay type entered.")
elif policy == "stay-off":
query = ' vpResumeOnACPowerLoss="reset"'
elif policy == "last-state":
query = ' vpResumeOnACPowerLoss="last-state"'
else:
raise salt.exceptions.CommandExecutionError("The power state must be specified.")
dn = "sys/rack-unit-1/board/Resume-on-AC-power-loss"
inconfig = """<biosVfResumeOnACPowerLoss
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{0}>
</biosVfResumeOnACPowerLoss>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_syslog_server(server=None, type="primary"):
'''
Set the SYSLOG server on the host.
Args:
server(str): The hostname or IP address of the SYSLOG server.
type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_syslog_server foo.bar.com
salt '*' cimc.set_syslog_server foo.bar.com primary
salt '*' cimc.set_syslog_server foo.bar.com secondary
'''
if not server:
raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.")
if type == "primary":
dn = "sys/svc-ext/syslog/client-primary"
inconfig = """<commSyslogClient name='primary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-primary'> </commSyslogClient>""".format(server)
elif type == "secondary":
dn = "sys/svc-ext/syslog/client-secondary"
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-secondary'> </commSyslogClient>""".format(server)
else:
raise salt.exceptions.CommandExecutionError("The SYSLOG type must be either primary or secondary.")
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
status(str): The account status of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
'''
conf = ""
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if status:
conf += ' accountStatus="{0}"'.format(status)
if username:
conf += ' name="{0}"'.format(username)
if priv:
conf += ' priv="{0}"'.format(priv)
if password:
conf += ' pwd="{0}"'.format(password)
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}"{1} dn="sys/user-ext/user-{0}"/>""".format(uid,
conf)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_bios(server=None, path=None):
'''
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/bios/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/bios/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-bios' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_cimc(server=None, path=None):
'''
Update the CIMC firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the CIMC image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_cimc foo.bar.com HP-SL2.bin
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/mgmt/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/mgmt/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-controller' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
saltstack/salt
|
salt/modules/cimc.py
|
set_power_configuration
|
python
|
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_power_configuration stay-off
salt '*' cimc.set_power_configuration reset fixed 0
'''
query = ""
if policy == "reset":
query = ' vpResumeOnACPowerLoss="reset"'
if delayType:
if delayType == "fixed":
query += ' delayType="fixed"'
if delayValue:
query += ' delay="{0}"'.format(delayValue)
elif delayType == "random":
query += ' delayType="random"'
else:
raise salt.exceptions.CommandExecutionError("Invalid delay type entered.")
elif policy == "stay-off":
query = ' vpResumeOnACPowerLoss="reset"'
elif policy == "last-state":
query = ' vpResumeOnACPowerLoss="last-state"'
else:
raise salt.exceptions.CommandExecutionError("The power state must be specified.")
dn = "sys/rack-unit-1/board/Resume-on-AC-power-loss"
inconfig = """<biosVfResumeOnACPowerLoss
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{0}>
</biosVfResumeOnACPowerLoss>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_power_configuration stay-off
salt '*' cimc.set_power_configuration reset fixed 0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L749-L817
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Cisco UCS compatibility to Salt
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
Configuration
=============
This module accepts connection configuration details either as
parameters, or as configuration settings in pillar as a Salt proxy.
Options passed into opts will be ignored if options are passed into pillar.
.. seealso::
:py:mod:`Cisco UCS Proxy Module <salt.proxy.cimc>`
About
=====
This execution module was designed to handle connections to a Cisco UCS server.
This module adds support to send connections directly to the device through the
rest API.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.platform
import salt.proxy.cimc
log = logging.getLogger(__name__)
__virtualname__ = 'cimc'
def __virtual__():
'''
Will load for the cimc proxy minions.
'''
try:
if salt.utils.platform.is_proxy() and \
__opts__['proxy']['proxytype'] == 'cimc':
return __virtualname__
except KeyError:
pass
return False, 'The cimc execution module can only be loaded for cimc proxy minions.'
def activate_backup_image(reset=False):
'''
Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True
'''
dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True:
r = "yes"
inconfig = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""".format(r)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def create_user(uid=None, username=None, password=None, priv=None):
'''
Create a CIMC user with username and password.
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
'''
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if not username:
raise salt.exceptions.CommandExecutionError("The username must be specified.")
if not password:
raise salt.exceptions.CommandExecutionError("The password must be specified.")
if not priv:
raise salt.exceptions.CommandExecutionError("The privilege level must be specified.")
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}" accountStatus="active" name="{1}" priv="{2}"
pwd="{3}" dn="sys/user-ext/user-{0}"/>""".format(uid,
username,
priv,
password)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def get_bios_defaults():
'''
Get the default values of BIOS tokens.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_defaults
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosPlatformDefaults', True)
return ret
def get_bios_settings():
'''
Get the C240 server BIOS token values.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosSettings', True)
return ret
def get_boot_order():
'''
Retrieves the configured boot order table.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_boot_order
'''
ret = __proxy__['cimc.get_config_resolver_class']('lsbootDef', True)
return ret
def get_cpu_details():
'''
Get the CPU product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_cpu_details
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogCpu', True)
return ret
def get_disks():
'''
Get the HDD product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogHdd', True)
return ret
def get_ethernet_interfaces():
'''
Get the adapter Ethernet interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ethernet_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostEthIf', True)
return ret
def get_fibre_channel_interfaces():
'''
Get the adapter fibre channel interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_fibre_channel_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostFcIf', True)
return ret
def get_firmware():
'''
Retrieves the current running firmware versions of server components.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_firmware
'''
ret = __proxy__['cimc.get_config_resolver_class']('firmwareRunning', False)
return ret
def get_hostname():
'''
Retrieves the hostname from the device.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_hostname
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', True)
try:
return ret['outConfigs']['mgmtIf'][0]['hostname']
except Exception as err:
return "Unable to retrieve hostname"
def get_ldap():
'''
Retrieves LDAP server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ldap
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaLdap', True)
return ret
def get_management_interface():
'''
Retrieve the management interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_management_interface
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', False)
return ret
def get_memory_token():
'''
Get the memory RAS BIOS token.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_token
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfSelectMemoryRASConfiguration', False)
return ret
def get_memory_unit():
'''
Get the IMM/Memory unit product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_unit
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogDimm', True)
return ret
def get_network_adapters():
'''
Get the list of network adapaters and configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_network_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('networkAdapterEthIf', True)
return ret
def get_ntp():
'''
Retrieves the current running NTP configuration.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ntp
'''
ret = __proxy__['cimc.get_config_resolver_class']('commNtpProvider', False)
return ret
def get_pci_adapters():
'''
Get the PCI adapter product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogPCIAdapter', True)
return ret
def get_power_configuration():
'''
Get the configuration of the power settings from the device. This is only available
on some C-Series servers.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_configuration
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfResumeOnACPowerLoss', True)
return ret
def get_power_supplies():
'''
Retrieves the power supply unit details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_supplies
'''
ret = __proxy__['cimc.get_config_resolver_class']('equipmentPsu', False)
return ret
def get_snmp_config():
'''
Get the snmp configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_snmp_config
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSnmp', False)
return ret
def get_syslog():
'''
Get the Syslog client-server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslogClient', False)
return ret
def get_syslog_settings():
'''
Get the Syslog configuration settings from the system.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslog', False)
return ret
def get_system_info():
'''
Get the system information.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_system_info
'''
ret = __proxy__['cimc.get_config_resolver_class']('computeRackUnit', False)
return ret
def get_users():
'''
Get the CIMC users.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_users
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaUser', False)
return ret
def get_vic_adapters():
'''
Get the VIC adapter general profile details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorGenProfile', True)
return ret
def get_vic_uplinks():
'''
Get the VIC adapter uplink port details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_uplinks
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorExtEthIf', True)
return ret
def mount_share(name=None,
remote_share=None,
remote_file=None,
mount_type="nfs",
username=None,
password=None):
'''
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media mounts can be scripted/automated
No vKVM requirements for media connection
Multiple share types supported
Connections supported through all CIMC interfaces
Note: CIMC Mounted vMedia is enabled through BIOS configuration.
Args:
name(str): The name of the volume on the CIMC device.
remote_share(str): The file share link that will be used to mount the share. This can be NFS, CIFS, or WWW. This
must be the directory path and not the full path to the remote file.
remote_file(str): The name of the remote file to mount. It must reside within remote_share.
mount_type(str): The type of share to mount. Valid options are nfs, cifs, and www.
username(str): An optional requirement to pass credentials to the remote share. If not provided, an
unauthenticated connection attempt will be made.
password(str): An optional requirement to pass a password to the remote share. If not provided, an
unauthenticated connection attempt will be made.
CLI Example:
.. code-block:: bash
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso username=bob password=badpassword
'''
if not name:
raise salt.exceptions.CommandExecutionError("The share name must be specified.")
if not remote_share:
raise salt.exceptions.CommandExecutionError("The remote share path must be specified.")
if not remote_file:
raise salt.exceptions.CommandExecutionError("The remote file name must be specified.")
if username and password:
mount_options = " mountOptions='username={0},password={1}'".format(username, password)
else:
mount_options = ""
dn = 'sys/svc-ext/vmedia-svc/vmmap-{0}'.format(name)
inconfig = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{0}' map='{1}'{2}
remoteFile='{3}' remoteShare='{4}' status='created'
volumeName='Win12' />""".format(name, mount_type, mount_options, remote_file, remote_share)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def reboot():
'''
Power cycling the server.
CLI Example:
.. code-block:: bash
salt '*' cimc.reboot
'''
dn = "sys/rack-unit-1"
inconfig = """<computeRackUnit adminPower="cycle-immediate" dn="sys/rack-unit-1"></computeRackUnit>"""
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_hostname(hostname=None):
'''
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
'''
if not hostname:
raise salt.exceptions.CommandExecutionError("Hostname option must be provided.")
dn = "sys/rack-unit-1/mgmt/if-1"
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{0}" ></mgmtIf>""".format(hostname)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
try:
if ret['outConfig']['mgmtIf'][0]['status'] == 'modified':
return True
else:
return False
except Exception as err:
return False
def set_logging_levels(remote=None, local=None):
'''
Sets the logging levels of the CIMC devices. The logging levels must match
the following options: emergency, alert, critical, error, warning, notice,
informational, debug.
.. versionadded:: 2019.2.0
Args:
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_logging_levels remote=error local=notice
'''
logging_options = ['emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'informational',
'debug']
query = ""
if remote:
if remote in logging_options:
query += ' remoteSeverity="{0}"'.format(remote)
else:
raise salt.exceptions.CommandExecutionError("Remote Severity option is not valid.")
if local:
if local in logging_options:
query += ' localSeverity="{0}"'.format(local)
else:
raise salt.exceptions.CommandExecutionError("Local Severity option is not valid.")
dn = "sys/svc-ext/syslog"
inconfig = """<commSyslog dn="sys/svc-ext/syslog"{0} ></commSyslog>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_ntp_server(server1='', server2='', server3='', server4=''):
'''
Sets the NTP servers configuration. This will also enable the client NTP service.
Args:
server1(str): The first IP address or FQDN of the NTP servers.
server2(str): The second IP address or FQDN of the NTP servers.
server3(str): The third IP address or FQDN of the NTP servers.
server4(str): The fourth IP address or FQDN of the NTP servers.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_ntp_server 10.10.10.1
salt '*' cimc.set_ntp_server 10.10.10.1 foo.bar.com
'''
dn = "sys/svc-ext/ntp-svc"
inconfig = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{0}" ntpServer2="{1}"
ntpServer3="{2}" ntpServer4="{3}"/>""".format(server1, server2, server3, server4)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_syslog_server(server=None, type="primary"):
'''
Set the SYSLOG server on the host.
Args:
server(str): The hostname or IP address of the SYSLOG server.
type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_syslog_server foo.bar.com
salt '*' cimc.set_syslog_server foo.bar.com primary
salt '*' cimc.set_syslog_server foo.bar.com secondary
'''
if not server:
raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.")
if type == "primary":
dn = "sys/svc-ext/syslog/client-primary"
inconfig = """<commSyslogClient name='primary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-primary'> </commSyslogClient>""".format(server)
elif type == "secondary":
dn = "sys/svc-ext/syslog/client-secondary"
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-secondary'> </commSyslogClient>""".format(server)
else:
raise salt.exceptions.CommandExecutionError("The SYSLOG type must be either primary or secondary.")
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
status(str): The account status of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
'''
conf = ""
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if status:
conf += ' accountStatus="{0}"'.format(status)
if username:
conf += ' name="{0}"'.format(username)
if priv:
conf += ' priv="{0}"'.format(priv)
if password:
conf += ' pwd="{0}"'.format(password)
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}"{1} dn="sys/user-ext/user-{0}"/>""".format(uid,
conf)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_bios(server=None, path=None):
'''
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/bios/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/bios/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-bios' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_cimc(server=None, path=None):
'''
Update the CIMC firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the CIMC image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_cimc foo.bar.com HP-SL2.bin
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/mgmt/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/mgmt/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-controller' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
saltstack/salt
|
salt/modules/cimc.py
|
set_syslog_server
|
python
|
def set_syslog_server(server=None, type="primary"):
'''
Set the SYSLOG server on the host.
Args:
server(str): The hostname or IP address of the SYSLOG server.
type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_syslog_server foo.bar.com
salt '*' cimc.set_syslog_server foo.bar.com primary
salt '*' cimc.set_syslog_server foo.bar.com secondary
'''
if not server:
raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.")
if type == "primary":
dn = "sys/svc-ext/syslog/client-primary"
inconfig = """<commSyslogClient name='primary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-primary'> </commSyslogClient>""".format(server)
elif type == "secondary":
dn = "sys/svc-ext/syslog/client-secondary"
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-secondary'> </commSyslogClient>""".format(server)
else:
raise salt.exceptions.CommandExecutionError("The SYSLOG type must be either primary or secondary.")
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
Set the SYSLOG server on the host.
Args:
server(str): The hostname or IP address of the SYSLOG server.
type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_syslog_server foo.bar.com
salt '*' cimc.set_syslog_server foo.bar.com primary
salt '*' cimc.set_syslog_server foo.bar.com secondary
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L820-L857
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Cisco UCS compatibility to Salt
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
Configuration
=============
This module accepts connection configuration details either as
parameters, or as configuration settings in pillar as a Salt proxy.
Options passed into opts will be ignored if options are passed into pillar.
.. seealso::
:py:mod:`Cisco UCS Proxy Module <salt.proxy.cimc>`
About
=====
This execution module was designed to handle connections to a Cisco UCS server.
This module adds support to send connections directly to the device through the
rest API.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.platform
import salt.proxy.cimc
log = logging.getLogger(__name__)
__virtualname__ = 'cimc'
def __virtual__():
'''
Will load for the cimc proxy minions.
'''
try:
if salt.utils.platform.is_proxy() and \
__opts__['proxy']['proxytype'] == 'cimc':
return __virtualname__
except KeyError:
pass
return False, 'The cimc execution module can only be loaded for cimc proxy minions.'
def activate_backup_image(reset=False):
'''
Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True
'''
dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True:
r = "yes"
inconfig = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""".format(r)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def create_user(uid=None, username=None, password=None, priv=None):
'''
Create a CIMC user with username and password.
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
'''
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if not username:
raise salt.exceptions.CommandExecutionError("The username must be specified.")
if not password:
raise salt.exceptions.CommandExecutionError("The password must be specified.")
if not priv:
raise salt.exceptions.CommandExecutionError("The privilege level must be specified.")
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}" accountStatus="active" name="{1}" priv="{2}"
pwd="{3}" dn="sys/user-ext/user-{0}"/>""".format(uid,
username,
priv,
password)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def get_bios_defaults():
'''
Get the default values of BIOS tokens.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_defaults
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosPlatformDefaults', True)
return ret
def get_bios_settings():
'''
Get the C240 server BIOS token values.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosSettings', True)
return ret
def get_boot_order():
'''
Retrieves the configured boot order table.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_boot_order
'''
ret = __proxy__['cimc.get_config_resolver_class']('lsbootDef', True)
return ret
def get_cpu_details():
'''
Get the CPU product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_cpu_details
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogCpu', True)
return ret
def get_disks():
'''
Get the HDD product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogHdd', True)
return ret
def get_ethernet_interfaces():
'''
Get the adapter Ethernet interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ethernet_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostEthIf', True)
return ret
def get_fibre_channel_interfaces():
'''
Get the adapter fibre channel interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_fibre_channel_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostFcIf', True)
return ret
def get_firmware():
'''
Retrieves the current running firmware versions of server components.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_firmware
'''
ret = __proxy__['cimc.get_config_resolver_class']('firmwareRunning', False)
return ret
def get_hostname():
'''
Retrieves the hostname from the device.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_hostname
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', True)
try:
return ret['outConfigs']['mgmtIf'][0]['hostname']
except Exception as err:
return "Unable to retrieve hostname"
def get_ldap():
'''
Retrieves LDAP server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ldap
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaLdap', True)
return ret
def get_management_interface():
'''
Retrieve the management interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_management_interface
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', False)
return ret
def get_memory_token():
'''
Get the memory RAS BIOS token.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_token
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfSelectMemoryRASConfiguration', False)
return ret
def get_memory_unit():
'''
Get the IMM/Memory unit product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_unit
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogDimm', True)
return ret
def get_network_adapters():
'''
Get the list of network adapaters and configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_network_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('networkAdapterEthIf', True)
return ret
def get_ntp():
'''
Retrieves the current running NTP configuration.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ntp
'''
ret = __proxy__['cimc.get_config_resolver_class']('commNtpProvider', False)
return ret
def get_pci_adapters():
'''
Get the PCI adapter product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogPCIAdapter', True)
return ret
def get_power_configuration():
'''
Get the configuration of the power settings from the device. This is only available
on some C-Series servers.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_configuration
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfResumeOnACPowerLoss', True)
return ret
def get_power_supplies():
'''
Retrieves the power supply unit details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_supplies
'''
ret = __proxy__['cimc.get_config_resolver_class']('equipmentPsu', False)
return ret
def get_snmp_config():
'''
Get the snmp configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_snmp_config
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSnmp', False)
return ret
def get_syslog():
'''
Get the Syslog client-server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslogClient', False)
return ret
def get_syslog_settings():
'''
Get the Syslog configuration settings from the system.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslog', False)
return ret
def get_system_info():
'''
Get the system information.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_system_info
'''
ret = __proxy__['cimc.get_config_resolver_class']('computeRackUnit', False)
return ret
def get_users():
'''
Get the CIMC users.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_users
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaUser', False)
return ret
def get_vic_adapters():
'''
Get the VIC adapter general profile details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorGenProfile', True)
return ret
def get_vic_uplinks():
'''
Get the VIC adapter uplink port details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_uplinks
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorExtEthIf', True)
return ret
def mount_share(name=None,
remote_share=None,
remote_file=None,
mount_type="nfs",
username=None,
password=None):
'''
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media mounts can be scripted/automated
No vKVM requirements for media connection
Multiple share types supported
Connections supported through all CIMC interfaces
Note: CIMC Mounted vMedia is enabled through BIOS configuration.
Args:
name(str): The name of the volume on the CIMC device.
remote_share(str): The file share link that will be used to mount the share. This can be NFS, CIFS, or WWW. This
must be the directory path and not the full path to the remote file.
remote_file(str): The name of the remote file to mount. It must reside within remote_share.
mount_type(str): The type of share to mount. Valid options are nfs, cifs, and www.
username(str): An optional requirement to pass credentials to the remote share. If not provided, an
unauthenticated connection attempt will be made.
password(str): An optional requirement to pass a password to the remote share. If not provided, an
unauthenticated connection attempt will be made.
CLI Example:
.. code-block:: bash
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso username=bob password=badpassword
'''
if not name:
raise salt.exceptions.CommandExecutionError("The share name must be specified.")
if not remote_share:
raise salt.exceptions.CommandExecutionError("The remote share path must be specified.")
if not remote_file:
raise salt.exceptions.CommandExecutionError("The remote file name must be specified.")
if username and password:
mount_options = " mountOptions='username={0},password={1}'".format(username, password)
else:
mount_options = ""
dn = 'sys/svc-ext/vmedia-svc/vmmap-{0}'.format(name)
inconfig = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{0}' map='{1}'{2}
remoteFile='{3}' remoteShare='{4}' status='created'
volumeName='Win12' />""".format(name, mount_type, mount_options, remote_file, remote_share)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def reboot():
'''
Power cycling the server.
CLI Example:
.. code-block:: bash
salt '*' cimc.reboot
'''
dn = "sys/rack-unit-1"
inconfig = """<computeRackUnit adminPower="cycle-immediate" dn="sys/rack-unit-1"></computeRackUnit>"""
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_hostname(hostname=None):
'''
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
'''
if not hostname:
raise salt.exceptions.CommandExecutionError("Hostname option must be provided.")
dn = "sys/rack-unit-1/mgmt/if-1"
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{0}" ></mgmtIf>""".format(hostname)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
try:
if ret['outConfig']['mgmtIf'][0]['status'] == 'modified':
return True
else:
return False
except Exception as err:
return False
def set_logging_levels(remote=None, local=None):
'''
Sets the logging levels of the CIMC devices. The logging levels must match
the following options: emergency, alert, critical, error, warning, notice,
informational, debug.
.. versionadded:: 2019.2.0
Args:
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_logging_levels remote=error local=notice
'''
logging_options = ['emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'informational',
'debug']
query = ""
if remote:
if remote in logging_options:
query += ' remoteSeverity="{0}"'.format(remote)
else:
raise salt.exceptions.CommandExecutionError("Remote Severity option is not valid.")
if local:
if local in logging_options:
query += ' localSeverity="{0}"'.format(local)
else:
raise salt.exceptions.CommandExecutionError("Local Severity option is not valid.")
dn = "sys/svc-ext/syslog"
inconfig = """<commSyslog dn="sys/svc-ext/syslog"{0} ></commSyslog>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_ntp_server(server1='', server2='', server3='', server4=''):
'''
Sets the NTP servers configuration. This will also enable the client NTP service.
Args:
server1(str): The first IP address or FQDN of the NTP servers.
server2(str): The second IP address or FQDN of the NTP servers.
server3(str): The third IP address or FQDN of the NTP servers.
server4(str): The fourth IP address or FQDN of the NTP servers.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_ntp_server 10.10.10.1
salt '*' cimc.set_ntp_server 10.10.10.1 foo.bar.com
'''
dn = "sys/svc-ext/ntp-svc"
inconfig = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{0}" ntpServer2="{1}"
ntpServer3="{2}" ntpServer4="{3}"/>""".format(server1, server2, server3, server4)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_power_configuration stay-off
salt '*' cimc.set_power_configuration reset fixed 0
'''
query = ""
if policy == "reset":
query = ' vpResumeOnACPowerLoss="reset"'
if delayType:
if delayType == "fixed":
query += ' delayType="fixed"'
if delayValue:
query += ' delay="{0}"'.format(delayValue)
elif delayType == "random":
query += ' delayType="random"'
else:
raise salt.exceptions.CommandExecutionError("Invalid delay type entered.")
elif policy == "stay-off":
query = ' vpResumeOnACPowerLoss="reset"'
elif policy == "last-state":
query = ' vpResumeOnACPowerLoss="last-state"'
else:
raise salt.exceptions.CommandExecutionError("The power state must be specified.")
dn = "sys/rack-unit-1/board/Resume-on-AC-power-loss"
inconfig = """<biosVfResumeOnACPowerLoss
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{0}>
</biosVfResumeOnACPowerLoss>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
status(str): The account status of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
'''
conf = ""
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if status:
conf += ' accountStatus="{0}"'.format(status)
if username:
conf += ' name="{0}"'.format(username)
if priv:
conf += ' priv="{0}"'.format(priv)
if password:
conf += ' pwd="{0}"'.format(password)
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}"{1} dn="sys/user-ext/user-{0}"/>""".format(uid,
conf)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_bios(server=None, path=None):
'''
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/bios/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/bios/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-bios' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_cimc(server=None, path=None):
'''
Update the CIMC firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the CIMC image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_cimc foo.bar.com HP-SL2.bin
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/mgmt/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/mgmt/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-controller' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
saltstack/salt
|
salt/modules/cimc.py
|
set_user
|
python
|
def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
status(str): The account status of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
'''
conf = ""
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if status:
conf += ' accountStatus="{0}"'.format(status)
if username:
conf += ' name="{0}"'.format(username)
if priv:
conf += ' priv="{0}"'.format(priv)
if password:
conf += ' pwd="{0}"'.format(password)
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}"{1} dn="sys/user-ext/user-{0}"/>""".format(uid,
conf)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
status(str): The account status of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L860-L908
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Cisco UCS compatibility to Salt
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
Configuration
=============
This module accepts connection configuration details either as
parameters, or as configuration settings in pillar as a Salt proxy.
Options passed into opts will be ignored if options are passed into pillar.
.. seealso::
:py:mod:`Cisco UCS Proxy Module <salt.proxy.cimc>`
About
=====
This execution module was designed to handle connections to a Cisco UCS server.
This module adds support to send connections directly to the device through the
rest API.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.platform
import salt.proxy.cimc
log = logging.getLogger(__name__)
__virtualname__ = 'cimc'
def __virtual__():
'''
Will load for the cimc proxy minions.
'''
try:
if salt.utils.platform.is_proxy() and \
__opts__['proxy']['proxytype'] == 'cimc':
return __virtualname__
except KeyError:
pass
return False, 'The cimc execution module can only be loaded for cimc proxy minions.'
def activate_backup_image(reset=False):
'''
Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True
'''
dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True:
r = "yes"
inconfig = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""".format(r)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def create_user(uid=None, username=None, password=None, priv=None):
'''
Create a CIMC user with username and password.
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
'''
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if not username:
raise salt.exceptions.CommandExecutionError("The username must be specified.")
if not password:
raise salt.exceptions.CommandExecutionError("The password must be specified.")
if not priv:
raise salt.exceptions.CommandExecutionError("The privilege level must be specified.")
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}" accountStatus="active" name="{1}" priv="{2}"
pwd="{3}" dn="sys/user-ext/user-{0}"/>""".format(uid,
username,
priv,
password)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def get_bios_defaults():
'''
Get the default values of BIOS tokens.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_defaults
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosPlatformDefaults', True)
return ret
def get_bios_settings():
'''
Get the C240 server BIOS token values.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosSettings', True)
return ret
def get_boot_order():
'''
Retrieves the configured boot order table.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_boot_order
'''
ret = __proxy__['cimc.get_config_resolver_class']('lsbootDef', True)
return ret
def get_cpu_details():
'''
Get the CPU product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_cpu_details
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogCpu', True)
return ret
def get_disks():
'''
Get the HDD product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogHdd', True)
return ret
def get_ethernet_interfaces():
'''
Get the adapter Ethernet interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ethernet_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostEthIf', True)
return ret
def get_fibre_channel_interfaces():
'''
Get the adapter fibre channel interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_fibre_channel_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostFcIf', True)
return ret
def get_firmware():
'''
Retrieves the current running firmware versions of server components.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_firmware
'''
ret = __proxy__['cimc.get_config_resolver_class']('firmwareRunning', False)
return ret
def get_hostname():
'''
Retrieves the hostname from the device.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_hostname
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', True)
try:
return ret['outConfigs']['mgmtIf'][0]['hostname']
except Exception as err:
return "Unable to retrieve hostname"
def get_ldap():
'''
Retrieves LDAP server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ldap
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaLdap', True)
return ret
def get_management_interface():
'''
Retrieve the management interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_management_interface
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', False)
return ret
def get_memory_token():
'''
Get the memory RAS BIOS token.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_token
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfSelectMemoryRASConfiguration', False)
return ret
def get_memory_unit():
'''
Get the IMM/Memory unit product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_unit
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogDimm', True)
return ret
def get_network_adapters():
'''
Get the list of network adapaters and configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_network_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('networkAdapterEthIf', True)
return ret
def get_ntp():
'''
Retrieves the current running NTP configuration.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ntp
'''
ret = __proxy__['cimc.get_config_resolver_class']('commNtpProvider', False)
return ret
def get_pci_adapters():
'''
Get the PCI adapter product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogPCIAdapter', True)
return ret
def get_power_configuration():
'''
Get the configuration of the power settings from the device. This is only available
on some C-Series servers.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_configuration
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfResumeOnACPowerLoss', True)
return ret
def get_power_supplies():
'''
Retrieves the power supply unit details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_supplies
'''
ret = __proxy__['cimc.get_config_resolver_class']('equipmentPsu', False)
return ret
def get_snmp_config():
'''
Get the snmp configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_snmp_config
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSnmp', False)
return ret
def get_syslog():
'''
Get the Syslog client-server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslogClient', False)
return ret
def get_syslog_settings():
'''
Get the Syslog configuration settings from the system.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslog', False)
return ret
def get_system_info():
'''
Get the system information.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_system_info
'''
ret = __proxy__['cimc.get_config_resolver_class']('computeRackUnit', False)
return ret
def get_users():
'''
Get the CIMC users.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_users
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaUser', False)
return ret
def get_vic_adapters():
'''
Get the VIC adapter general profile details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorGenProfile', True)
return ret
def get_vic_uplinks():
'''
Get the VIC adapter uplink port details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_uplinks
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorExtEthIf', True)
return ret
def mount_share(name=None,
remote_share=None,
remote_file=None,
mount_type="nfs",
username=None,
password=None):
'''
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media mounts can be scripted/automated
No vKVM requirements for media connection
Multiple share types supported
Connections supported through all CIMC interfaces
Note: CIMC Mounted vMedia is enabled through BIOS configuration.
Args:
name(str): The name of the volume on the CIMC device.
remote_share(str): The file share link that will be used to mount the share. This can be NFS, CIFS, or WWW. This
must be the directory path and not the full path to the remote file.
remote_file(str): The name of the remote file to mount. It must reside within remote_share.
mount_type(str): The type of share to mount. Valid options are nfs, cifs, and www.
username(str): An optional requirement to pass credentials to the remote share. If not provided, an
unauthenticated connection attempt will be made.
password(str): An optional requirement to pass a password to the remote share. If not provided, an
unauthenticated connection attempt will be made.
CLI Example:
.. code-block:: bash
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso username=bob password=badpassword
'''
if not name:
raise salt.exceptions.CommandExecutionError("The share name must be specified.")
if not remote_share:
raise salt.exceptions.CommandExecutionError("The remote share path must be specified.")
if not remote_file:
raise salt.exceptions.CommandExecutionError("The remote file name must be specified.")
if username and password:
mount_options = " mountOptions='username={0},password={1}'".format(username, password)
else:
mount_options = ""
dn = 'sys/svc-ext/vmedia-svc/vmmap-{0}'.format(name)
inconfig = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{0}' map='{1}'{2}
remoteFile='{3}' remoteShare='{4}' status='created'
volumeName='Win12' />""".format(name, mount_type, mount_options, remote_file, remote_share)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def reboot():
'''
Power cycling the server.
CLI Example:
.. code-block:: bash
salt '*' cimc.reboot
'''
dn = "sys/rack-unit-1"
inconfig = """<computeRackUnit adminPower="cycle-immediate" dn="sys/rack-unit-1"></computeRackUnit>"""
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_hostname(hostname=None):
'''
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
'''
if not hostname:
raise salt.exceptions.CommandExecutionError("Hostname option must be provided.")
dn = "sys/rack-unit-1/mgmt/if-1"
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{0}" ></mgmtIf>""".format(hostname)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
try:
if ret['outConfig']['mgmtIf'][0]['status'] == 'modified':
return True
else:
return False
except Exception as err:
return False
def set_logging_levels(remote=None, local=None):
'''
Sets the logging levels of the CIMC devices. The logging levels must match
the following options: emergency, alert, critical, error, warning, notice,
informational, debug.
.. versionadded:: 2019.2.0
Args:
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_logging_levels remote=error local=notice
'''
logging_options = ['emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'informational',
'debug']
query = ""
if remote:
if remote in logging_options:
query += ' remoteSeverity="{0}"'.format(remote)
else:
raise salt.exceptions.CommandExecutionError("Remote Severity option is not valid.")
if local:
if local in logging_options:
query += ' localSeverity="{0}"'.format(local)
else:
raise salt.exceptions.CommandExecutionError("Local Severity option is not valid.")
dn = "sys/svc-ext/syslog"
inconfig = """<commSyslog dn="sys/svc-ext/syslog"{0} ></commSyslog>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_ntp_server(server1='', server2='', server3='', server4=''):
'''
Sets the NTP servers configuration. This will also enable the client NTP service.
Args:
server1(str): The first IP address or FQDN of the NTP servers.
server2(str): The second IP address or FQDN of the NTP servers.
server3(str): The third IP address or FQDN of the NTP servers.
server4(str): The fourth IP address or FQDN of the NTP servers.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_ntp_server 10.10.10.1
salt '*' cimc.set_ntp_server 10.10.10.1 foo.bar.com
'''
dn = "sys/svc-ext/ntp-svc"
inconfig = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{0}" ntpServer2="{1}"
ntpServer3="{2}" ntpServer4="{3}"/>""".format(server1, server2, server3, server4)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_power_configuration stay-off
salt '*' cimc.set_power_configuration reset fixed 0
'''
query = ""
if policy == "reset":
query = ' vpResumeOnACPowerLoss="reset"'
if delayType:
if delayType == "fixed":
query += ' delayType="fixed"'
if delayValue:
query += ' delay="{0}"'.format(delayValue)
elif delayType == "random":
query += ' delayType="random"'
else:
raise salt.exceptions.CommandExecutionError("Invalid delay type entered.")
elif policy == "stay-off":
query = ' vpResumeOnACPowerLoss="reset"'
elif policy == "last-state":
query = ' vpResumeOnACPowerLoss="last-state"'
else:
raise salt.exceptions.CommandExecutionError("The power state must be specified.")
dn = "sys/rack-unit-1/board/Resume-on-AC-power-loss"
inconfig = """<biosVfResumeOnACPowerLoss
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{0}>
</biosVfResumeOnACPowerLoss>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_syslog_server(server=None, type="primary"):
'''
Set the SYSLOG server on the host.
Args:
server(str): The hostname or IP address of the SYSLOG server.
type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_syslog_server foo.bar.com
salt '*' cimc.set_syslog_server foo.bar.com primary
salt '*' cimc.set_syslog_server foo.bar.com secondary
'''
if not server:
raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.")
if type == "primary":
dn = "sys/svc-ext/syslog/client-primary"
inconfig = """<commSyslogClient name='primary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-primary'> </commSyslogClient>""".format(server)
elif type == "secondary":
dn = "sys/svc-ext/syslog/client-secondary"
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-secondary'> </commSyslogClient>""".format(server)
else:
raise salt.exceptions.CommandExecutionError("The SYSLOG type must be either primary or secondary.")
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_bios(server=None, path=None):
'''
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/bios/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/bios/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-bios' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_cimc(server=None, path=None):
'''
Update the CIMC firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the CIMC image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_cimc foo.bar.com HP-SL2.bin
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/mgmt/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/mgmt/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-controller' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
saltstack/salt
|
salt/modules/cimc.py
|
tftp_update_bios
|
python
|
def tftp_update_bios(server=None, path=None):
'''
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/bios/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/bios/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-bios' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L911-L942
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Cisco UCS compatibility to Salt
:codeauthor: ``Spencer Ervin <spencer_ervin@hotmail.com>``
:maturity: new
:depends: none
:platform: unix
Configuration
=============
This module accepts connection configuration details either as
parameters, or as configuration settings in pillar as a Salt proxy.
Options passed into opts will be ignored if options are passed into pillar.
.. seealso::
:py:mod:`Cisco UCS Proxy Module <salt.proxy.cimc>`
About
=====
This execution module was designed to handle connections to a Cisco UCS server.
This module adds support to send connections directly to the device through the
rest API.
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.platform
import salt.proxy.cimc
log = logging.getLogger(__name__)
__virtualname__ = 'cimc'
def __virtual__():
'''
Will load for the cimc proxy minions.
'''
try:
if salt.utils.platform.is_proxy() and \
__opts__['proxy']['proxytype'] == 'cimc':
return __virtualname__
except KeyError:
pass
return False, 'The cimc execution module can only be loaded for cimc proxy minions.'
def activate_backup_image(reset=False):
'''
Activates the firmware backup image.
CLI Example:
Args:
reset(bool): Reset the CIMC device on activate.
.. code-block:: bash
salt '*' cimc.activate_backup_image
salt '*' cimc.activate_backup_image reset=True
'''
dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined"
r = "no"
if reset is True:
r = "yes"
inconfig = """<firmwareBootUnit dn='sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined'
adminState='trigger' image='backup' resetOnActivate='{0}' />""".format(r)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def create_user(uid=None, username=None, password=None, priv=None):
'''
Create a CIMC user with username and password.
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
'''
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if not username:
raise salt.exceptions.CommandExecutionError("The username must be specified.")
if not password:
raise salt.exceptions.CommandExecutionError("The password must be specified.")
if not priv:
raise salt.exceptions.CommandExecutionError("The privilege level must be specified.")
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}" accountStatus="active" name="{1}" priv="{2}"
pwd="{3}" dn="sys/user-ext/user-{0}"/>""".format(uid,
username,
priv,
password)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def get_bios_defaults():
'''
Get the default values of BIOS tokens.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_defaults
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosPlatformDefaults', True)
return ret
def get_bios_settings():
'''
Get the C240 server BIOS token values.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_bios_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosSettings', True)
return ret
def get_boot_order():
'''
Retrieves the configured boot order table.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_boot_order
'''
ret = __proxy__['cimc.get_config_resolver_class']('lsbootDef', True)
return ret
def get_cpu_details():
'''
Get the CPU product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_cpu_details
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogCpu', True)
return ret
def get_disks():
'''
Get the HDD product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogHdd', True)
return ret
def get_ethernet_interfaces():
'''
Get the adapter Ethernet interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ethernet_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostEthIf', True)
return ret
def get_fibre_channel_interfaces():
'''
Get the adapter fibre channel interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_fibre_channel_interfaces
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorHostFcIf', True)
return ret
def get_firmware():
'''
Retrieves the current running firmware versions of server components.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_firmware
'''
ret = __proxy__['cimc.get_config_resolver_class']('firmwareRunning', False)
return ret
def get_hostname():
'''
Retrieves the hostname from the device.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_hostname
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', True)
try:
return ret['outConfigs']['mgmtIf'][0]['hostname']
except Exception as err:
return "Unable to retrieve hostname"
def get_ldap():
'''
Retrieves LDAP server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ldap
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaLdap', True)
return ret
def get_management_interface():
'''
Retrieve the management interface details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_management_interface
'''
ret = __proxy__['cimc.get_config_resolver_class']('mgmtIf', False)
return ret
def get_memory_token():
'''
Get the memory RAS BIOS token.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_token
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfSelectMemoryRASConfiguration', False)
return ret
def get_memory_unit():
'''
Get the IMM/Memory unit product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_memory_unit
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogDimm', True)
return ret
def get_network_adapters():
'''
Get the list of network adapaters and configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_network_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('networkAdapterEthIf', True)
return ret
def get_ntp():
'''
Retrieves the current running NTP configuration.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_ntp
'''
ret = __proxy__['cimc.get_config_resolver_class']('commNtpProvider', False)
return ret
def get_pci_adapters():
'''
Get the PCI adapter product ID details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_disks
'''
ret = __proxy__['cimc.get_config_resolver_class']('pidCatalogPCIAdapter', True)
return ret
def get_power_configuration():
'''
Get the configuration of the power settings from the device. This is only available
on some C-Series servers.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_configuration
'''
ret = __proxy__['cimc.get_config_resolver_class']('biosVfResumeOnACPowerLoss', True)
return ret
def get_power_supplies():
'''
Retrieves the power supply unit details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_power_supplies
'''
ret = __proxy__['cimc.get_config_resolver_class']('equipmentPsu', False)
return ret
def get_snmp_config():
'''
Get the snmp configuration details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_snmp_config
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSnmp', False)
return ret
def get_syslog():
'''
Get the Syslog client-server details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslogClient', False)
return ret
def get_syslog_settings():
'''
Get the Syslog configuration settings from the system.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cimc.get_syslog_settings
'''
ret = __proxy__['cimc.get_config_resolver_class']('commSyslog', False)
return ret
def get_system_info():
'''
Get the system information.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_system_info
'''
ret = __proxy__['cimc.get_config_resolver_class']('computeRackUnit', False)
return ret
def get_users():
'''
Get the CIMC users.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_users
'''
ret = __proxy__['cimc.get_config_resolver_class']('aaaUser', False)
return ret
def get_vic_adapters():
'''
Get the VIC adapter general profile details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_adapters
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorGenProfile', True)
return ret
def get_vic_uplinks():
'''
Get the VIC adapter uplink port details.
CLI Example:
.. code-block:: bash
salt '*' cimc.get_vic_uplinks
'''
ret = __proxy__['cimc.get_config_resolver_class']('adaptorExtEthIf', True)
return ret
def mount_share(name=None,
remote_share=None,
remote_file=None,
mount_type="nfs",
username=None,
password=None):
'''
Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater.
The remote share can be either NFS, CIFS, or WWW.
Some of the advantages of CIMC Mounted vMedia include:
Communication between mounted media and target stays local (inside datacenter)
Media mounts can be scripted/automated
No vKVM requirements for media connection
Multiple share types supported
Connections supported through all CIMC interfaces
Note: CIMC Mounted vMedia is enabled through BIOS configuration.
Args:
name(str): The name of the volume on the CIMC device.
remote_share(str): The file share link that will be used to mount the share. This can be NFS, CIFS, or WWW. This
must be the directory path and not the full path to the remote file.
remote_file(str): The name of the remote file to mount. It must reside within remote_share.
mount_type(str): The type of share to mount. Valid options are nfs, cifs, and www.
username(str): An optional requirement to pass credentials to the remote share. If not provided, an
unauthenticated connection attempt will be made.
password(str): An optional requirement to pass a password to the remote share. If not provided, an
unauthenticated connection attempt will be made.
CLI Example:
.. code-block:: bash
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso
salt '*' cimc.mount_share name=WIN7 remote_share=10.xxx.27.xxx:/nfs remote_file=sl1huu.iso username=bob password=badpassword
'''
if not name:
raise salt.exceptions.CommandExecutionError("The share name must be specified.")
if not remote_share:
raise salt.exceptions.CommandExecutionError("The remote share path must be specified.")
if not remote_file:
raise salt.exceptions.CommandExecutionError("The remote file name must be specified.")
if username and password:
mount_options = " mountOptions='username={0},password={1}'".format(username, password)
else:
mount_options = ""
dn = 'sys/svc-ext/vmedia-svc/vmmap-{0}'.format(name)
inconfig = """<commVMediaMap dn='sys/svc-ext/vmedia-svc/vmmap-{0}' map='{1}'{2}
remoteFile='{3}' remoteShare='{4}' status='created'
volumeName='Win12' />""".format(name, mount_type, mount_options, remote_file, remote_share)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def reboot():
'''
Power cycling the server.
CLI Example:
.. code-block:: bash
salt '*' cimc.reboot
'''
dn = "sys/rack-unit-1"
inconfig = """<computeRackUnit adminPower="cycle-immediate" dn="sys/rack-unit-1"></computeRackUnit>"""
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_hostname(hostname=None):
'''
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
'''
if not hostname:
raise salt.exceptions.CommandExecutionError("Hostname option must be provided.")
dn = "sys/rack-unit-1/mgmt/if-1"
inconfig = """<mgmtIf dn="sys/rack-unit-1/mgmt/if-1" hostname="{0}" ></mgmtIf>""".format(hostname)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
try:
if ret['outConfig']['mgmtIf'][0]['status'] == 'modified':
return True
else:
return False
except Exception as err:
return False
def set_logging_levels(remote=None, local=None):
'''
Sets the logging levels of the CIMC devices. The logging levels must match
the following options: emergency, alert, critical, error, warning, notice,
informational, debug.
.. versionadded:: 2019.2.0
Args:
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_logging_levels remote=error local=notice
'''
logging_options = ['emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'informational',
'debug']
query = ""
if remote:
if remote in logging_options:
query += ' remoteSeverity="{0}"'.format(remote)
else:
raise salt.exceptions.CommandExecutionError("Remote Severity option is not valid.")
if local:
if local in logging_options:
query += ' localSeverity="{0}"'.format(local)
else:
raise salt.exceptions.CommandExecutionError("Local Severity option is not valid.")
dn = "sys/svc-ext/syslog"
inconfig = """<commSyslog dn="sys/svc-ext/syslog"{0} ></commSyslog>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_ntp_server(server1='', server2='', server3='', server4=''):
'''
Sets the NTP servers configuration. This will also enable the client NTP service.
Args:
server1(str): The first IP address or FQDN of the NTP servers.
server2(str): The second IP address or FQDN of the NTP servers.
server3(str): The third IP address or FQDN of the NTP servers.
server4(str): The fourth IP address or FQDN of the NTP servers.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_ntp_server 10.10.10.1
salt '*' cimc.set_ntp_server 10.10.10.1 foo.bar.com
'''
dn = "sys/svc-ext/ntp-svc"
inconfig = """<commNtpProvider dn="sys/svc-ext/ntp-svc" ntpEnable="yes" ntpServer1="{0}" ntpServer2="{1}"
ntpServer3="{2}" ntpServer4="{3}"/>""".format(server1, server2, server3, server4)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_power_configuration stay-off
salt '*' cimc.set_power_configuration reset fixed 0
'''
query = ""
if policy == "reset":
query = ' vpResumeOnACPowerLoss="reset"'
if delayType:
if delayType == "fixed":
query += ' delayType="fixed"'
if delayValue:
query += ' delay="{0}"'.format(delayValue)
elif delayType == "random":
query += ' delayType="random"'
else:
raise salt.exceptions.CommandExecutionError("Invalid delay type entered.")
elif policy == "stay-off":
query = ' vpResumeOnACPowerLoss="reset"'
elif policy == "last-state":
query = ' vpResumeOnACPowerLoss="last-state"'
else:
raise salt.exceptions.CommandExecutionError("The power state must be specified.")
dn = "sys/rack-unit-1/board/Resume-on-AC-power-loss"
inconfig = """<biosVfResumeOnACPowerLoss
dn="sys/rack-unit-1/board/Resume-on-AC-power-loss"{0}>
</biosVfResumeOnACPowerLoss>""".format(query)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_syslog_server(server=None, type="primary"):
'''
Set the SYSLOG server on the host.
Args:
server(str): The hostname or IP address of the SYSLOG server.
type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_syslog_server foo.bar.com
salt '*' cimc.set_syslog_server foo.bar.com primary
salt '*' cimc.set_syslog_server foo.bar.com secondary
'''
if not server:
raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.")
if type == "primary":
dn = "sys/svc-ext/syslog/client-primary"
inconfig = """<commSyslogClient name='primary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-primary'> </commSyslogClient>""".format(server)
elif type == "secondary":
dn = "sys/svc-ext/syslog/client-secondary"
inconfig = """<commSyslogClient name='secondary' adminState='enabled' hostname='{0}'
dn='sys/svc-ext/syslog/client-secondary'> </commSyslogClient>""".format(server)
else:
raise salt.exceptions.CommandExecutionError("The SYSLOG type must be either primary or secondary.")
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
status(str): The account status of the user.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
'''
conf = ""
if not uid:
raise salt.exceptions.CommandExecutionError("The user ID must be specified.")
if status:
conf += ' accountStatus="{0}"'.format(status)
if username:
conf += ' name="{0}"'.format(username)
if priv:
conf += ' priv="{0}"'.format(priv)
if password:
conf += ' pwd="{0}"'.format(password)
dn = "sys/user-ext/user-{0}".format(uid)
inconfig = """<aaaUser id="{0}"{1} dn="sys/user-ext/user-{0}"/>""".format(uid,
conf)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
def tftp_update_cimc(server=None, path=None):
'''
Update the CIMC firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the CIMC image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_cimc foo.bar.com HP-SL2.bin
'''
if not server:
raise salt.exceptions.CommandExecutionError("The server name must be specified.")
if not path:
raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.")
dn = "sys/rack-unit-1/mgmt/fw-updatable"
inconfig = """<firmwareUpdatable adminState='trigger' dn='sys/rack-unit-1/mgmt/fw-updatable'
protocol='tftp' remoteServer='{0}' remotePath='{1}'
type='blade-controller' />""".format(server, path)
ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)
return ret
|
saltstack/salt
|
salt/states/consul.py
|
_acl_changes
|
python
|
def _acl_changes(name, id=None, type=None, rules=None, consul_url=None, token=None):
'''
return True if the acl need to be update, False if it doesn't need to be update
'''
info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)
if info['res'] and info['data'][0]['Name'] != name:
return True
elif info['res'] and info['data'][0]['Rules'] != rules:
return True
elif info['res'] and info['data'][0]['Type'] != type:
return True
else:
return False
|
return True if the acl need to be update, False if it doesn't need to be update
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/consul.py#L24-L37
| null |
# -*- coding: utf-8 -*-
'''
Consul Management
=================
The consul module is used to create and manage Consul ACLs
.. code-block:: yaml
acl_present:
consul.acl_present:
- id: 38AC8470-4A83-4140-8DFD-F924CD32917F
- name: acl_name
- rules: node "" {policy = "write"} service "" {policy = "read"} key "_rexec" {policy = "write"}
- type: client
- consul_url: http://localhost:8500
acl_delete:
consul.acl_absent:
- id: 38AC8470-4A83-4140-8DFD-F924CD32917F
'''
def _acl_exists(name=None, id=None, token=None, consul_url=None):
'''
Check the acl exists by using the name or the ID,
name is ignored if ID is specified,
if only Name is used the ID associated with it is returned
'''
ret = {'result': False, 'id': None}
if id:
info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)
elif name:
info = __salt__['consul.acl_list'](token=token, consul_url=consul_url)
else:
return ret
if info.get('data'):
for acl in info['data']:
if id and acl['ID'] == id:
ret['result'] = True
ret['id'] = id
elif name and acl['Name'] == name:
ret['result'] = True
ret['id'] = acl['ID']
return ret
def acl_present(name, id=None, token=None, type="client", rules="", consul_url='http://localhost:8500'):
'''
Ensure the ACL is present
name
Specifies a human-friendly name for the ACL token.
id
Specifies the ID of the ACL.
type: client
Specifies the type of ACL token. Valid values are: client and management.
rules
Specifies rules for this ACL token.
consul_url : http://locahost:8500
consul URL to query
.. note::
For more information https://www.consul.io/api/acl.html#create-acl-token, https://www.consul.io/api/acl.html#update-acl-token
'''
ret = {
'name': name,
'changes': {},
'result': True,
'comment': 'ACL "{0}" exists and is up to date'.format(name)}
exists = _acl_exists(name, id, token, consul_url)
if not exists['result']:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl doesn't exist, it will be created"
return ret
create = __salt__['consul.acl_create'](name=name, id=id, token=token, type=type, rules=rules, consul_url=consul_url)
if create['res']:
ret['result'] = True
ret['comment'] = "the acl has been created"
elif not create['res']:
ret['result'] = False
ret['comment'] = "failed to create the acl"
elif exists['result']:
changes = _acl_changes(name=name, id=exists['id'], token=token, type=type, rules=rules, consul_url=consul_url)
if changes:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl exists and will be updated"
return ret
update = __salt__['consul.acl_update'](name=name, id=exists['id'], token=token, type=type, rules=rules, consul_url=consul_url)
if update['res']:
ret['result'] = True
ret['comment'] = "the acl has been updated"
elif not update['res']:
ret['result'] = False
ret['comment'] = "failed to update the acl"
return ret
def acl_absent(name, id=None, token=None, consul_url='http://localhost:8500'):
'''
Ensure the ACL is absent
name
Specifies a human-friendly name for the ACL token.
id
Specifies the ID of the ACL.
token
token to authenticate you Consul query
consul_url : http://locahost:8500
consul URL to query
.. note::
For more information https://www.consul.io/api/acl.html#delete-acl-token
'''
ret = {
'name': id,
'changes': {},
'result': True,
'comment': 'ACL "{0}" does not exist'.format(id)}
exists = _acl_exists(name, id, token, consul_url)
if exists['result']:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl exists, it will be deleted"
return ret
delete = __salt__['consul.acl_delete'](id=exists['id'], token=token, consul_url=consul_url)
if delete['res']:
ret['result'] = True
ret['comment'] = "the acl has been deleted"
elif not delete['res']:
ret['result'] = False
ret['comment'] = "failed to delete the acl"
return ret
|
saltstack/salt
|
salt/states/consul.py
|
_acl_exists
|
python
|
def _acl_exists(name=None, id=None, token=None, consul_url=None):
'''
Check the acl exists by using the name or the ID,
name is ignored if ID is specified,
if only Name is used the ID associated with it is returned
'''
ret = {'result': False, 'id': None}
if id:
info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)
elif name:
info = __salt__['consul.acl_list'](token=token, consul_url=consul_url)
else:
return ret
if info.get('data'):
for acl in info['data']:
if id and acl['ID'] == id:
ret['result'] = True
ret['id'] = id
elif name and acl['Name'] == name:
ret['result'] = True
ret['id'] = acl['ID']
return ret
|
Check the acl exists by using the name or the ID,
name is ignored if ID is specified,
if only Name is used the ID associated with it is returned
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/consul.py#L40-L65
| null |
# -*- coding: utf-8 -*-
'''
Consul Management
=================
The consul module is used to create and manage Consul ACLs
.. code-block:: yaml
acl_present:
consul.acl_present:
- id: 38AC8470-4A83-4140-8DFD-F924CD32917F
- name: acl_name
- rules: node "" {policy = "write"} service "" {policy = "read"} key "_rexec" {policy = "write"}
- type: client
- consul_url: http://localhost:8500
acl_delete:
consul.acl_absent:
- id: 38AC8470-4A83-4140-8DFD-F924CD32917F
'''
def _acl_changes(name, id=None, type=None, rules=None, consul_url=None, token=None):
'''
return True if the acl need to be update, False if it doesn't need to be update
'''
info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)
if info['res'] and info['data'][0]['Name'] != name:
return True
elif info['res'] and info['data'][0]['Rules'] != rules:
return True
elif info['res'] and info['data'][0]['Type'] != type:
return True
else:
return False
def acl_present(name, id=None, token=None, type="client", rules="", consul_url='http://localhost:8500'):
'''
Ensure the ACL is present
name
Specifies a human-friendly name for the ACL token.
id
Specifies the ID of the ACL.
type: client
Specifies the type of ACL token. Valid values are: client and management.
rules
Specifies rules for this ACL token.
consul_url : http://locahost:8500
consul URL to query
.. note::
For more information https://www.consul.io/api/acl.html#create-acl-token, https://www.consul.io/api/acl.html#update-acl-token
'''
ret = {
'name': name,
'changes': {},
'result': True,
'comment': 'ACL "{0}" exists and is up to date'.format(name)}
exists = _acl_exists(name, id, token, consul_url)
if not exists['result']:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl doesn't exist, it will be created"
return ret
create = __salt__['consul.acl_create'](name=name, id=id, token=token, type=type, rules=rules, consul_url=consul_url)
if create['res']:
ret['result'] = True
ret['comment'] = "the acl has been created"
elif not create['res']:
ret['result'] = False
ret['comment'] = "failed to create the acl"
elif exists['result']:
changes = _acl_changes(name=name, id=exists['id'], token=token, type=type, rules=rules, consul_url=consul_url)
if changes:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl exists and will be updated"
return ret
update = __salt__['consul.acl_update'](name=name, id=exists['id'], token=token, type=type, rules=rules, consul_url=consul_url)
if update['res']:
ret['result'] = True
ret['comment'] = "the acl has been updated"
elif not update['res']:
ret['result'] = False
ret['comment'] = "failed to update the acl"
return ret
def acl_absent(name, id=None, token=None, consul_url='http://localhost:8500'):
'''
Ensure the ACL is absent
name
Specifies a human-friendly name for the ACL token.
id
Specifies the ID of the ACL.
token
token to authenticate you Consul query
consul_url : http://locahost:8500
consul URL to query
.. note::
For more information https://www.consul.io/api/acl.html#delete-acl-token
'''
ret = {
'name': id,
'changes': {},
'result': True,
'comment': 'ACL "{0}" does not exist'.format(id)}
exists = _acl_exists(name, id, token, consul_url)
if exists['result']:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl exists, it will be deleted"
return ret
delete = __salt__['consul.acl_delete'](id=exists['id'], token=token, consul_url=consul_url)
if delete['res']:
ret['result'] = True
ret['comment'] = "the acl has been deleted"
elif not delete['res']:
ret['result'] = False
ret['comment'] = "failed to delete the acl"
return ret
|
saltstack/salt
|
salt/states/consul.py
|
acl_present
|
python
|
def acl_present(name, id=None, token=None, type="client", rules="", consul_url='http://localhost:8500'):
'''
Ensure the ACL is present
name
Specifies a human-friendly name for the ACL token.
id
Specifies the ID of the ACL.
type: client
Specifies the type of ACL token. Valid values are: client and management.
rules
Specifies rules for this ACL token.
consul_url : http://locahost:8500
consul URL to query
.. note::
For more information https://www.consul.io/api/acl.html#create-acl-token, https://www.consul.io/api/acl.html#update-acl-token
'''
ret = {
'name': name,
'changes': {},
'result': True,
'comment': 'ACL "{0}" exists and is up to date'.format(name)}
exists = _acl_exists(name, id, token, consul_url)
if not exists['result']:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl doesn't exist, it will be created"
return ret
create = __salt__['consul.acl_create'](name=name, id=id, token=token, type=type, rules=rules, consul_url=consul_url)
if create['res']:
ret['result'] = True
ret['comment'] = "the acl has been created"
elif not create['res']:
ret['result'] = False
ret['comment'] = "failed to create the acl"
elif exists['result']:
changes = _acl_changes(name=name, id=exists['id'], token=token, type=type, rules=rules, consul_url=consul_url)
if changes:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl exists and will be updated"
return ret
update = __salt__['consul.acl_update'](name=name, id=exists['id'], token=token, type=type, rules=rules, consul_url=consul_url)
if update['res']:
ret['result'] = True
ret['comment'] = "the acl has been updated"
elif not update['res']:
ret['result'] = False
ret['comment'] = "failed to update the acl"
return ret
|
Ensure the ACL is present
name
Specifies a human-friendly name for the ACL token.
id
Specifies the ID of the ACL.
type: client
Specifies the type of ACL token. Valid values are: client and management.
rules
Specifies rules for this ACL token.
consul_url : http://locahost:8500
consul URL to query
.. note::
For more information https://www.consul.io/api/acl.html#create-acl-token, https://www.consul.io/api/acl.html#update-acl-token
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/consul.py#L68-L128
|
[
"def _acl_changes(name, id=None, type=None, rules=None, consul_url=None, token=None):\n '''\n return True if the acl need to be update, False if it doesn't need to be update\n '''\n info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)\n\n if info['res'] and info['data'][0]['Name'] != name:\n return True\n elif info['res'] and info['data'][0]['Rules'] != rules:\n return True\n elif info['res'] and info['data'][0]['Type'] != type:\n return True\n else:\n return False\n",
"def _acl_exists(name=None, id=None, token=None, consul_url=None):\n '''\n Check the acl exists by using the name or the ID,\n name is ignored if ID is specified,\n if only Name is used the ID associated with it is returned\n '''\n\n ret = {'result': False, 'id': None}\n\n if id:\n info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)\n elif name:\n info = __salt__['consul.acl_list'](token=token, consul_url=consul_url)\n else:\n return ret\n\n if info.get('data'):\n for acl in info['data']:\n if id and acl['ID'] == id:\n ret['result'] = True\n ret['id'] = id\n elif name and acl['Name'] == name:\n ret['result'] = True\n ret['id'] = acl['ID']\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Consul Management
=================
The consul module is used to create and manage Consul ACLs
.. code-block:: yaml
acl_present:
consul.acl_present:
- id: 38AC8470-4A83-4140-8DFD-F924CD32917F
- name: acl_name
- rules: node "" {policy = "write"} service "" {policy = "read"} key "_rexec" {policy = "write"}
- type: client
- consul_url: http://localhost:8500
acl_delete:
consul.acl_absent:
- id: 38AC8470-4A83-4140-8DFD-F924CD32917F
'''
def _acl_changes(name, id=None, type=None, rules=None, consul_url=None, token=None):
'''
return True if the acl need to be update, False if it doesn't need to be update
'''
info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)
if info['res'] and info['data'][0]['Name'] != name:
return True
elif info['res'] and info['data'][0]['Rules'] != rules:
return True
elif info['res'] and info['data'][0]['Type'] != type:
return True
else:
return False
def _acl_exists(name=None, id=None, token=None, consul_url=None):
'''
Check the acl exists by using the name or the ID,
name is ignored if ID is specified,
if only Name is used the ID associated with it is returned
'''
ret = {'result': False, 'id': None}
if id:
info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)
elif name:
info = __salt__['consul.acl_list'](token=token, consul_url=consul_url)
else:
return ret
if info.get('data'):
for acl in info['data']:
if id and acl['ID'] == id:
ret['result'] = True
ret['id'] = id
elif name and acl['Name'] == name:
ret['result'] = True
ret['id'] = acl['ID']
return ret
def acl_absent(name, id=None, token=None, consul_url='http://localhost:8500'):
'''
Ensure the ACL is absent
name
Specifies a human-friendly name for the ACL token.
id
Specifies the ID of the ACL.
token
token to authenticate you Consul query
consul_url : http://locahost:8500
consul URL to query
.. note::
For more information https://www.consul.io/api/acl.html#delete-acl-token
'''
ret = {
'name': id,
'changes': {},
'result': True,
'comment': 'ACL "{0}" does not exist'.format(id)}
exists = _acl_exists(name, id, token, consul_url)
if exists['result']:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl exists, it will be deleted"
return ret
delete = __salt__['consul.acl_delete'](id=exists['id'], token=token, consul_url=consul_url)
if delete['res']:
ret['result'] = True
ret['comment'] = "the acl has been deleted"
elif not delete['res']:
ret['result'] = False
ret['comment'] = "failed to delete the acl"
return ret
|
saltstack/salt
|
salt/states/consul.py
|
acl_absent
|
python
|
def acl_absent(name, id=None, token=None, consul_url='http://localhost:8500'):
'''
Ensure the ACL is absent
name
Specifies a human-friendly name for the ACL token.
id
Specifies the ID of the ACL.
token
token to authenticate you Consul query
consul_url : http://locahost:8500
consul URL to query
.. note::
For more information https://www.consul.io/api/acl.html#delete-acl-token
'''
ret = {
'name': id,
'changes': {},
'result': True,
'comment': 'ACL "{0}" does not exist'.format(id)}
exists = _acl_exists(name, id, token, consul_url)
if exists['result']:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl exists, it will be deleted"
return ret
delete = __salt__['consul.acl_delete'](id=exists['id'], token=token, consul_url=consul_url)
if delete['res']:
ret['result'] = True
ret['comment'] = "the acl has been deleted"
elif not delete['res']:
ret['result'] = False
ret['comment'] = "failed to delete the acl"
return ret
|
Ensure the ACL is absent
name
Specifies a human-friendly name for the ACL token.
id
Specifies the ID of the ACL.
token
token to authenticate you Consul query
consul_url : http://locahost:8500
consul URL to query
.. note::
For more information https://www.consul.io/api/acl.html#delete-acl-token
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/consul.py#L131-L172
|
[
"def _acl_exists(name=None, id=None, token=None, consul_url=None):\n '''\n Check the acl exists by using the name or the ID,\n name is ignored if ID is specified,\n if only Name is used the ID associated with it is returned\n '''\n\n ret = {'result': False, 'id': None}\n\n if id:\n info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)\n elif name:\n info = __salt__['consul.acl_list'](token=token, consul_url=consul_url)\n else:\n return ret\n\n if info.get('data'):\n for acl in info['data']:\n if id and acl['ID'] == id:\n ret['result'] = True\n ret['id'] = id\n elif name and acl['Name'] == name:\n ret['result'] = True\n ret['id'] = acl['ID']\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Consul Management
=================
The consul module is used to create and manage Consul ACLs
.. code-block:: yaml
acl_present:
consul.acl_present:
- id: 38AC8470-4A83-4140-8DFD-F924CD32917F
- name: acl_name
- rules: node "" {policy = "write"} service "" {policy = "read"} key "_rexec" {policy = "write"}
- type: client
- consul_url: http://localhost:8500
acl_delete:
consul.acl_absent:
- id: 38AC8470-4A83-4140-8DFD-F924CD32917F
'''
def _acl_changes(name, id=None, type=None, rules=None, consul_url=None, token=None):
'''
return True if the acl need to be update, False if it doesn't need to be update
'''
info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)
if info['res'] and info['data'][0]['Name'] != name:
return True
elif info['res'] and info['data'][0]['Rules'] != rules:
return True
elif info['res'] and info['data'][0]['Type'] != type:
return True
else:
return False
def _acl_exists(name=None, id=None, token=None, consul_url=None):
'''
Check the acl exists by using the name or the ID,
name is ignored if ID is specified,
if only Name is used the ID associated with it is returned
'''
ret = {'result': False, 'id': None}
if id:
info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)
elif name:
info = __salt__['consul.acl_list'](token=token, consul_url=consul_url)
else:
return ret
if info.get('data'):
for acl in info['data']:
if id and acl['ID'] == id:
ret['result'] = True
ret['id'] = id
elif name and acl['Name'] == name:
ret['result'] = True
ret['id'] = acl['ID']
return ret
def acl_present(name, id=None, token=None, type="client", rules="", consul_url='http://localhost:8500'):
'''
Ensure the ACL is present
name
Specifies a human-friendly name for the ACL token.
id
Specifies the ID of the ACL.
type: client
Specifies the type of ACL token. Valid values are: client and management.
rules
Specifies rules for this ACL token.
consul_url : http://locahost:8500
consul URL to query
.. note::
For more information https://www.consul.io/api/acl.html#create-acl-token, https://www.consul.io/api/acl.html#update-acl-token
'''
ret = {
'name': name,
'changes': {},
'result': True,
'comment': 'ACL "{0}" exists and is up to date'.format(name)}
exists = _acl_exists(name, id, token, consul_url)
if not exists['result']:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl doesn't exist, it will be created"
return ret
create = __salt__['consul.acl_create'](name=name, id=id, token=token, type=type, rules=rules, consul_url=consul_url)
if create['res']:
ret['result'] = True
ret['comment'] = "the acl has been created"
elif not create['res']:
ret['result'] = False
ret['comment'] = "failed to create the acl"
elif exists['result']:
changes = _acl_changes(name=name, id=exists['id'], token=token, type=type, rules=rules, consul_url=consul_url)
if changes:
if __opts__['test']:
ret['result'] = None
ret['comment'] = "the acl exists and will be updated"
return ret
update = __salt__['consul.acl_update'](name=name, id=exists['id'], token=token, type=type, rules=rules, consul_url=consul_url)
if update['res']:
ret['result'] = True
ret['comment'] = "the acl has been updated"
elif not update['res']:
ret['result'] = False
ret['comment'] = "failed to update the acl"
return ret
|
saltstack/salt
|
salt/grains/nvme.py
|
nvme_nqn
|
python
|
def nvme_nqn():
'''
Return NVMe NQN
'''
grains = {}
grains['nvme_nqn'] = False
if salt.utils.platform.is_linux():
grains['nvme_nqn'] = _linux_nqn()
return grains
|
Return NVMe NQN
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/nvme.py#L36-L44
|
[
"def _linux_nqn():\n '''\n Return NVMe NQN from a Linux host.\n '''\n ret = []\n\n initiator = '/etc/nvme/hostnqn'\n try:\n with salt.utils.files.fopen(initiator, 'r') as _nvme:\n for line in _nvme:\n line = line.strip()\n if line.startswith('nqn.'):\n ret.append(line)\n except IOError as ex:\n if ex.errno != errno.ENOENT:\n log.debug(\"Error while accessing '%s': %s\", initiator, ex)\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Grains for NVMe Qualified Names (NQN).
.. versionadded:: Flourine
To enable these grains set `nvme_grains: True`.
.. code-block:: yaml
nvme_grains: True
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
# Import Salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
__virtualname__ = 'nvme'
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
if __opts__.get('nvme_grains', False) is False:
return False
return __virtualname__
def _linux_nqn():
'''
Return NVMe NQN from a Linux host.
'''
ret = []
initiator = '/etc/nvme/hostnqn'
try:
with salt.utils.files.fopen(initiator, 'r') as _nvme:
for line in _nvme:
line = line.strip()
if line.startswith('nqn.'):
ret.append(line)
except IOError as ex:
if ex.errno != errno.ENOENT:
log.debug("Error while accessing '%s': %s", initiator, ex)
return ret
|
saltstack/salt
|
salt/grains/nvme.py
|
_linux_nqn
|
python
|
def _linux_nqn():
'''
Return NVMe NQN from a Linux host.
'''
ret = []
initiator = '/etc/nvme/hostnqn'
try:
with salt.utils.files.fopen(initiator, 'r') as _nvme:
for line in _nvme:
line = line.strip()
if line.startswith('nqn.'):
ret.append(line)
except IOError as ex:
if ex.errno != errno.ENOENT:
log.debug("Error while accessing '%s': %s", initiator, ex)
return ret
|
Return NVMe NQN from a Linux host.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/nvme.py#L47-L64
|
[
"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"
] |
# -*- coding: utf-8 -*-
'''
Grains for NVMe Qualified Names (NQN).
.. versionadded:: Flourine
To enable these grains set `nvme_grains: True`.
.. code-block:: yaml
nvme_grains: True
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
# Import Salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
__virtualname__ = 'nvme'
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
if __opts__.get('nvme_grains', False) is False:
return False
return __virtualname__
def nvme_nqn():
'''
Return NVMe NQN
'''
grains = {}
grains['nvme_nqn'] = False
if salt.utils.platform.is_linux():
grains['nvme_nqn'] = _linux_nqn()
return grains
|
saltstack/salt
|
salt/states/keystore.py
|
managed
|
python
|
def managed(name, passphrase, entries, force_remove=False):
'''
Create or manage a java keystore.
name
The path to the keystore file
passphrase
The password to the keystore
entries
A list containing an alias, certificate, and optional private_key.
The certificate and private_key can be a file or a string
.. code-block:: yaml
- entries:
- alias: hostname2
certificate: /path/to/cert.crt
private_key: /path/to/key.key
- alias: stringhost
certificate: |
-----BEGIN CERTIFICATE-----
MIICEjCCAXsCAg36MA0GCSqGSIb3DQEBBQUAMIGbMQswCQYDVQQGEwJKUDEOMAwG
...
2VguKv4SWjRFoRkIfIlHX0qVviMhSlNy2ioFLy7JcPZb+v3ftDGywUqcBiVDoea0
-----END CERTIFICATE-----
force_remove
If True will cause the state to remove any entries found in the keystore which are not
defined in the state. The default is False.
Example
.. code-block:: yaml
define_keystore:
keystore.managed:
- name: /path/to/keystore
- passphrase: changeit
- force_remove: True
- entries:
- alias: hostname1
certificate: /path/to/cert.crt
- alias: remotehost
certificate: /path/to/cert2.crt
private_key: /path/to/key2.key
- alias: pillarhost
certificate: {{ salt.pillar.get('path:to:cert') }}
'''
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
keep_list = []
old_aliases = []
if force_remove:
if os.path.exists(name):
existing_entries = __salt__['keystore.list'](name, passphrase)
for entry in existing_entries:
old_aliases.append(entry.get('alias'))
log.debug("Existing aliases list: %s", old_aliases)
for entry in entries:
update_entry = True
existing_entry = None
if os.path.exists(name):
if force_remove:
keep_list.append(entry['alias'])
existing_entry = __salt__['keystore.list'](name, passphrase, entry['alias'])
if existing_entry:
existing_sha1 = existing_entry[0]['sha1']
new_sha1 = __salt__['x509.read_certificate'](entry['certificate'])['SHA1 Finger Print']
if existing_sha1 == new_sha1:
update_entry = False
if update_entry:
if __opts__['test']:
ret['result'] = None
if existing_entry:
ret['comment'] += "Alias {0} would have been updated\n".format(entry['alias'])
else:
ret['comment'] += "Alias {0} would have been added\n".format(entry['alias'])
else:
if existing_entry:
result = __salt__['keystore.remove'](entry['alias'], name, passphrase)
result = __salt__['keystore.add'](entry['alias'],
name,
passphrase,
entry['certificate'],
private_key=entry.get('private_key', None)
)
if result:
ret['changes'][entry['alias']] = "Updated"
ret['comment'] += "Alias {0} updated.\n".format(entry['alias'])
else:
result = __salt__['keystore.add'](entry['alias'],
name,
passphrase,
entry['certificate'],
private_key=entry.get('private_key', None)
)
if result:
ret['changes'][entry['alias']] = "Added"
ret['comment'] += "Alias {0} added.\n".format(entry['alias'])
if force_remove:
# Determine which aliases need to be removed
remove_list = list(set(old_aliases) - set(keep_list))
log.debug("Will remove: %s", remove_list)
for alias_name in remove_list:
if __opts__['test']:
ret['comment'] += "Alias {0} would have been removed".format(alias_name)
ret['result'] = None
else:
__salt__['keystore.remove'](alias_name, name, passphrase)
ret['changes'][alias_name] = "Removed"
ret['comment'] += "Alias {0} removed.\n".format(alias_name)
if not ret['changes'] and not ret['comment']:
ret['comment'] = "No changes made.\n"
return ret
|
Create or manage a java keystore.
name
The path to the keystore file
passphrase
The password to the keystore
entries
A list containing an alias, certificate, and optional private_key.
The certificate and private_key can be a file or a string
.. code-block:: yaml
- entries:
- alias: hostname2
certificate: /path/to/cert.crt
private_key: /path/to/key.key
- alias: stringhost
certificate: |
-----BEGIN CERTIFICATE-----
MIICEjCCAXsCAg36MA0GCSqGSIb3DQEBBQUAMIGbMQswCQYDVQQGEwJKUDEOMAwG
...
2VguKv4SWjRFoRkIfIlHX0qVviMhSlNy2ioFLy7JcPZb+v3ftDGywUqcBiVDoea0
-----END CERTIFICATE-----
force_remove
If True will cause the state to remove any entries found in the keystore which are not
defined in the state. The default is False.
Example
.. code-block:: yaml
define_keystore:
keystore.managed:
- name: /path/to/keystore
- passphrase: changeit
- force_remove: True
- entries:
- alias: hostname1
certificate: /path/to/cert.crt
- alias: remotehost
certificate: /path/to/cert2.crt
private_key: /path/to/key2.key
- alias: pillarhost
certificate: {{ salt.pillar.get('path:to:cert') }}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystore.py#L27-L151
| null |
# -*- coding: utf-8 -*-
'''
State management of a java keystore
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
__virtualname__ = 'keystore'
# Init logger
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load this module if the keystore execution module is available
'''
if 'keystore.list' in __salt__:
return __virtualname__
return (False, ('Cannot load the {0} state module: '
'keystore execution module not found'.format(__virtualname__)))
|
saltstack/salt
|
salt/modules/pf.py
|
disable
|
python
|
def disable():
'''
Disable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.disable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -d',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf disabled', 'changes': True}
else:
# If pf was already disabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf not enabled':
ret = {'comment': 'pf already disabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not disable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
Disable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.disable
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pf.py#L68-L96
| null |
# -*- coding: utf-8 -*-
'''
Control the OpenBSD packet filter (PF).
:codeauthor: Jasper Lievisse Adriaanse <j@jasper.la>
.. versionadded:: 2019.2.0
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
import salt.utils.path
from salt.exceptions import (CommandExecutionError, SaltInvocationError)
log = logging.getLogger(__name__)
def __virtual__():
'''
Only works on OpenBSD and FreeBSD for now; other systems with pf (macOS,
FreeBSD, etc) need to be tested before enabling them.
'''
tested_oses = ['FreeBSD', 'OpenBSD']
if __grains__['os'] in tested_oses and salt.utils.path.which('pfctl'):
return True
return (False, 'The pf execution module cannot be loaded: either the '
'OS (' + __grains__['os'] + ') is not tested or the pfctl binary '
'was not found')
def enable():
'''
Enable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.enable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -e',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf enabled', 'changes': True}
else:
# If pf was already enabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf already enabled':
ret = {'comment': 'pf already enabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not enable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def loglevel(level):
'''
Set the debug level which limits the severity of log messages printed by ``pf(4)``.
level:
Log level. Should be one of the following: emerg, alert, crit, err, warning, notice,
info or debug (OpenBSD); or none, urgent, misc, loud (FreeBSD).
CLI example:
.. code-block:: bash
salt '*' pf.loglevel emerg
'''
# There's no way to getting the previous loglevel so imply we've
# always made a change.
ret = {'changes': True}
myos = __grains__['os']
if myos == 'FreeBSD':
all_levels = ['none', 'urgent', 'misc', 'loud']
else:
all_levels = ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug']
if level not in all_levels:
raise SaltInvocationError('Unknown loglevel: {0}'.format(level))
result = __salt__['cmd.run_all']('pfctl -x {0}'.format(level),
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered setting loglevel',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def load(file='/etc/pf.conf', noop=False):
'''
Load a ruleset from the specific file, overwriting the currently loaded ruleset.
file:
Full path to the file containing the ruleset.
noop:
Don't actually load the rules, just parse them.
CLI example:
.. code-block:: bash
salt '*' pf.load /etc/pf.conf.d/lockdown.conf
'''
# We cannot precisely determine if loading the ruleset implied
# any changes so assume it always does.
ret = {'changes': True}
cmd = ['pfctl', '-f', file]
if noop:
ret['changes'] = False
cmd.append('-n')
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem loading the ruleset from {0}'.format(file),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def flush(modifier):
'''
Flush the specified packet filter parameters.
modifier:
Should be one of the following:
- all
- info
- osfp
- rules
- sources
- states
- tables
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.flush states
'''
ret = {}
all_modifiers = ['rules', 'states', 'info', 'osfp', 'all', 'sources', 'tables']
# Accept the following two modifiers to allow for a consistent interface between
# pfctl(8) and Salt.
capital_modifiers = ['Sources', 'Tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -v -F {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
if re.match(r'^0.*', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
raise CommandExecutionError(
'Could not flush {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def table(command, table, **kwargs):
'''
Apply a command on the specified table.
table:
Name of the table.
command:
Command to apply to the table. Supported commands are:
- add
- delete
- expire
- flush
- kill
- replace
- show
- test
- zero
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.table expire table=spam_hosts number=300
salt '*' pf.table add table=local_hosts addresses='["127.0.0.1", "::1"]'
'''
ret = {}
all_commands = ['kill', 'flush', 'add', 'delete', 'expire', 'replace', 'show', 'test', 'zero']
if command not in all_commands:
raise SaltInvocationError('Unknown table command: {0}'.format(command))
cmd = ['pfctl', '-t', table, '-T', command]
if command in ['add', 'delete', 'replace', 'test']:
cmd += kwargs.get('addresses', [])
elif command == 'expire':
number = kwargs.get('number', None)
if not number:
raise SaltInvocationError('need expire_number argument for expire command')
else:
cmd.append(number)
result = __salt__['cmd.run_all'](cmd,
output_level='trace',
python_shell=False)
if result['retcode'] == 0:
if command == 'show':
ret = {'comment': result['stdout'].split()}
elif command == 'test':
ret = {'comment': result['stderr'], 'matches': True}
else:
if re.match(r'^(0.*|no changes)', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
# 'test' returns a non-zero code if the address didn't match, even if
# the command itself ran fine; also set 'matches' to False since not
# everything matched.
if command == 'test' and re.match(r'^\d+/\d+ addresses match.$', result['stderr']):
ret = {'comment': result['stderr'], 'matches': False}
else:
raise CommandExecutionError(
'Could not apply {0} on table {1}'.format(command, table),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def show(modifier):
'''
Show filter parameters.
modifier:
Modifier to apply for filtering. Only a useful subset of what pfctl supports
can be used with Salt.
- rules
- states
- tables
CLI example:
.. code-block:: bash
salt '*' pf.show rules
'''
# By definition showing the parameters makes no changes.
ret = {'changes': False}
capital_modifiers = ['Tables']
all_modifiers = ['rules', 'states', 'tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -s {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret['comment'] = result['stdout'].split('\n')
else:
raise CommandExecutionError(
'Could not show {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
saltstack/salt
|
salt/modules/pf.py
|
loglevel
|
python
|
def loglevel(level):
'''
Set the debug level which limits the severity of log messages printed by ``pf(4)``.
level:
Log level. Should be one of the following: emerg, alert, crit, err, warning, notice,
info or debug (OpenBSD); or none, urgent, misc, loud (FreeBSD).
CLI example:
.. code-block:: bash
salt '*' pf.loglevel emerg
'''
# There's no way to getting the previous loglevel so imply we've
# always made a change.
ret = {'changes': True}
myos = __grains__['os']
if myos == 'FreeBSD':
all_levels = ['none', 'urgent', 'misc', 'loud']
else:
all_levels = ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug']
if level not in all_levels:
raise SaltInvocationError('Unknown loglevel: {0}'.format(level))
result = __salt__['cmd.run_all']('pfctl -x {0}'.format(level),
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered setting loglevel',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
Set the debug level which limits the severity of log messages printed by ``pf(4)``.
level:
Log level. Should be one of the following: emerg, alert, crit, err, warning, notice,
info or debug (OpenBSD); or none, urgent, misc, loud (FreeBSD).
CLI example:
.. code-block:: bash
salt '*' pf.loglevel emerg
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pf.py#L99-L135
| null |
# -*- coding: utf-8 -*-
'''
Control the OpenBSD packet filter (PF).
:codeauthor: Jasper Lievisse Adriaanse <j@jasper.la>
.. versionadded:: 2019.2.0
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
import salt.utils.path
from salt.exceptions import (CommandExecutionError, SaltInvocationError)
log = logging.getLogger(__name__)
def __virtual__():
'''
Only works on OpenBSD and FreeBSD for now; other systems with pf (macOS,
FreeBSD, etc) need to be tested before enabling them.
'''
tested_oses = ['FreeBSD', 'OpenBSD']
if __grains__['os'] in tested_oses and salt.utils.path.which('pfctl'):
return True
return (False, 'The pf execution module cannot be loaded: either the '
'OS (' + __grains__['os'] + ') is not tested or the pfctl binary '
'was not found')
def enable():
'''
Enable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.enable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -e',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf enabled', 'changes': True}
else:
# If pf was already enabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf already enabled':
ret = {'comment': 'pf already enabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not enable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def disable():
'''
Disable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.disable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -d',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf disabled', 'changes': True}
else:
# If pf was already disabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf not enabled':
ret = {'comment': 'pf already disabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not disable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def load(file='/etc/pf.conf', noop=False):
'''
Load a ruleset from the specific file, overwriting the currently loaded ruleset.
file:
Full path to the file containing the ruleset.
noop:
Don't actually load the rules, just parse them.
CLI example:
.. code-block:: bash
salt '*' pf.load /etc/pf.conf.d/lockdown.conf
'''
# We cannot precisely determine if loading the ruleset implied
# any changes so assume it always does.
ret = {'changes': True}
cmd = ['pfctl', '-f', file]
if noop:
ret['changes'] = False
cmd.append('-n')
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem loading the ruleset from {0}'.format(file),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def flush(modifier):
'''
Flush the specified packet filter parameters.
modifier:
Should be one of the following:
- all
- info
- osfp
- rules
- sources
- states
- tables
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.flush states
'''
ret = {}
all_modifiers = ['rules', 'states', 'info', 'osfp', 'all', 'sources', 'tables']
# Accept the following two modifiers to allow for a consistent interface between
# pfctl(8) and Salt.
capital_modifiers = ['Sources', 'Tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -v -F {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
if re.match(r'^0.*', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
raise CommandExecutionError(
'Could not flush {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def table(command, table, **kwargs):
'''
Apply a command on the specified table.
table:
Name of the table.
command:
Command to apply to the table. Supported commands are:
- add
- delete
- expire
- flush
- kill
- replace
- show
- test
- zero
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.table expire table=spam_hosts number=300
salt '*' pf.table add table=local_hosts addresses='["127.0.0.1", "::1"]'
'''
ret = {}
all_commands = ['kill', 'flush', 'add', 'delete', 'expire', 'replace', 'show', 'test', 'zero']
if command not in all_commands:
raise SaltInvocationError('Unknown table command: {0}'.format(command))
cmd = ['pfctl', '-t', table, '-T', command]
if command in ['add', 'delete', 'replace', 'test']:
cmd += kwargs.get('addresses', [])
elif command == 'expire':
number = kwargs.get('number', None)
if not number:
raise SaltInvocationError('need expire_number argument for expire command')
else:
cmd.append(number)
result = __salt__['cmd.run_all'](cmd,
output_level='trace',
python_shell=False)
if result['retcode'] == 0:
if command == 'show':
ret = {'comment': result['stdout'].split()}
elif command == 'test':
ret = {'comment': result['stderr'], 'matches': True}
else:
if re.match(r'^(0.*|no changes)', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
# 'test' returns a non-zero code if the address didn't match, even if
# the command itself ran fine; also set 'matches' to False since not
# everything matched.
if command == 'test' and re.match(r'^\d+/\d+ addresses match.$', result['stderr']):
ret = {'comment': result['stderr'], 'matches': False}
else:
raise CommandExecutionError(
'Could not apply {0} on table {1}'.format(command, table),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def show(modifier):
'''
Show filter parameters.
modifier:
Modifier to apply for filtering. Only a useful subset of what pfctl supports
can be used with Salt.
- rules
- states
- tables
CLI example:
.. code-block:: bash
salt '*' pf.show rules
'''
# By definition showing the parameters makes no changes.
ret = {'changes': False}
capital_modifiers = ['Tables']
all_modifiers = ['rules', 'states', 'tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -s {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret['comment'] = result['stdout'].split('\n')
else:
raise CommandExecutionError(
'Could not show {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
saltstack/salt
|
salt/modules/pf.py
|
load
|
python
|
def load(file='/etc/pf.conf', noop=False):
'''
Load a ruleset from the specific file, overwriting the currently loaded ruleset.
file:
Full path to the file containing the ruleset.
noop:
Don't actually load the rules, just parse them.
CLI example:
.. code-block:: bash
salt '*' pf.load /etc/pf.conf.d/lockdown.conf
'''
# We cannot precisely determine if loading the ruleset implied
# any changes so assume it always does.
ret = {'changes': True}
cmd = ['pfctl', '-f', file]
if noop:
ret['changes'] = False
cmd.append('-n')
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem loading the ruleset from {0}'.format(file),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
Load a ruleset from the specific file, overwriting the currently loaded ruleset.
file:
Full path to the file containing the ruleset.
noop:
Don't actually load the rules, just parse them.
CLI example:
.. code-block:: bash
salt '*' pf.load /etc/pf.conf.d/lockdown.conf
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pf.py#L138-L173
| null |
# -*- coding: utf-8 -*-
'''
Control the OpenBSD packet filter (PF).
:codeauthor: Jasper Lievisse Adriaanse <j@jasper.la>
.. versionadded:: 2019.2.0
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
import salt.utils.path
from salt.exceptions import (CommandExecutionError, SaltInvocationError)
log = logging.getLogger(__name__)
def __virtual__():
'''
Only works on OpenBSD and FreeBSD for now; other systems with pf (macOS,
FreeBSD, etc) need to be tested before enabling them.
'''
tested_oses = ['FreeBSD', 'OpenBSD']
if __grains__['os'] in tested_oses and salt.utils.path.which('pfctl'):
return True
return (False, 'The pf execution module cannot be loaded: either the '
'OS (' + __grains__['os'] + ') is not tested or the pfctl binary '
'was not found')
def enable():
'''
Enable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.enable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -e',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf enabled', 'changes': True}
else:
# If pf was already enabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf already enabled':
ret = {'comment': 'pf already enabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not enable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def disable():
'''
Disable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.disable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -d',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf disabled', 'changes': True}
else:
# If pf was already disabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf not enabled':
ret = {'comment': 'pf already disabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not disable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def loglevel(level):
'''
Set the debug level which limits the severity of log messages printed by ``pf(4)``.
level:
Log level. Should be one of the following: emerg, alert, crit, err, warning, notice,
info or debug (OpenBSD); or none, urgent, misc, loud (FreeBSD).
CLI example:
.. code-block:: bash
salt '*' pf.loglevel emerg
'''
# There's no way to getting the previous loglevel so imply we've
# always made a change.
ret = {'changes': True}
myos = __grains__['os']
if myos == 'FreeBSD':
all_levels = ['none', 'urgent', 'misc', 'loud']
else:
all_levels = ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug']
if level not in all_levels:
raise SaltInvocationError('Unknown loglevel: {0}'.format(level))
result = __salt__['cmd.run_all']('pfctl -x {0}'.format(level),
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered setting loglevel',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def flush(modifier):
'''
Flush the specified packet filter parameters.
modifier:
Should be one of the following:
- all
- info
- osfp
- rules
- sources
- states
- tables
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.flush states
'''
ret = {}
all_modifiers = ['rules', 'states', 'info', 'osfp', 'all', 'sources', 'tables']
# Accept the following two modifiers to allow for a consistent interface between
# pfctl(8) and Salt.
capital_modifiers = ['Sources', 'Tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -v -F {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
if re.match(r'^0.*', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
raise CommandExecutionError(
'Could not flush {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def table(command, table, **kwargs):
'''
Apply a command on the specified table.
table:
Name of the table.
command:
Command to apply to the table. Supported commands are:
- add
- delete
- expire
- flush
- kill
- replace
- show
- test
- zero
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.table expire table=spam_hosts number=300
salt '*' pf.table add table=local_hosts addresses='["127.0.0.1", "::1"]'
'''
ret = {}
all_commands = ['kill', 'flush', 'add', 'delete', 'expire', 'replace', 'show', 'test', 'zero']
if command not in all_commands:
raise SaltInvocationError('Unknown table command: {0}'.format(command))
cmd = ['pfctl', '-t', table, '-T', command]
if command in ['add', 'delete', 'replace', 'test']:
cmd += kwargs.get('addresses', [])
elif command == 'expire':
number = kwargs.get('number', None)
if not number:
raise SaltInvocationError('need expire_number argument for expire command')
else:
cmd.append(number)
result = __salt__['cmd.run_all'](cmd,
output_level='trace',
python_shell=False)
if result['retcode'] == 0:
if command == 'show':
ret = {'comment': result['stdout'].split()}
elif command == 'test':
ret = {'comment': result['stderr'], 'matches': True}
else:
if re.match(r'^(0.*|no changes)', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
# 'test' returns a non-zero code if the address didn't match, even if
# the command itself ran fine; also set 'matches' to False since not
# everything matched.
if command == 'test' and re.match(r'^\d+/\d+ addresses match.$', result['stderr']):
ret = {'comment': result['stderr'], 'matches': False}
else:
raise CommandExecutionError(
'Could not apply {0} on table {1}'.format(command, table),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def show(modifier):
'''
Show filter parameters.
modifier:
Modifier to apply for filtering. Only a useful subset of what pfctl supports
can be used with Salt.
- rules
- states
- tables
CLI example:
.. code-block:: bash
salt '*' pf.show rules
'''
# By definition showing the parameters makes no changes.
ret = {'changes': False}
capital_modifiers = ['Tables']
all_modifiers = ['rules', 'states', 'tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -s {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret['comment'] = result['stdout'].split('\n')
else:
raise CommandExecutionError(
'Could not show {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
saltstack/salt
|
salt/modules/pf.py
|
flush
|
python
|
def flush(modifier):
'''
Flush the specified packet filter parameters.
modifier:
Should be one of the following:
- all
- info
- osfp
- rules
- sources
- states
- tables
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.flush states
'''
ret = {}
all_modifiers = ['rules', 'states', 'info', 'osfp', 'all', 'sources', 'tables']
# Accept the following two modifiers to allow for a consistent interface between
# pfctl(8) and Salt.
capital_modifiers = ['Sources', 'Tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -v -F {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
if re.match(r'^0.*', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
raise CommandExecutionError(
'Could not flush {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
Flush the specified packet filter parameters.
modifier:
Should be one of the following:
- all
- info
- osfp
- rules
- sources
- states
- tables
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.flush states
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pf.py#L176-L232
| null |
# -*- coding: utf-8 -*-
'''
Control the OpenBSD packet filter (PF).
:codeauthor: Jasper Lievisse Adriaanse <j@jasper.la>
.. versionadded:: 2019.2.0
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
import salt.utils.path
from salt.exceptions import (CommandExecutionError, SaltInvocationError)
log = logging.getLogger(__name__)
def __virtual__():
'''
Only works on OpenBSD and FreeBSD for now; other systems with pf (macOS,
FreeBSD, etc) need to be tested before enabling them.
'''
tested_oses = ['FreeBSD', 'OpenBSD']
if __grains__['os'] in tested_oses and salt.utils.path.which('pfctl'):
return True
return (False, 'The pf execution module cannot be loaded: either the '
'OS (' + __grains__['os'] + ') is not tested or the pfctl binary '
'was not found')
def enable():
'''
Enable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.enable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -e',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf enabled', 'changes': True}
else:
# If pf was already enabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf already enabled':
ret = {'comment': 'pf already enabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not enable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def disable():
'''
Disable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.disable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -d',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf disabled', 'changes': True}
else:
# If pf was already disabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf not enabled':
ret = {'comment': 'pf already disabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not disable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def loglevel(level):
'''
Set the debug level which limits the severity of log messages printed by ``pf(4)``.
level:
Log level. Should be one of the following: emerg, alert, crit, err, warning, notice,
info or debug (OpenBSD); or none, urgent, misc, loud (FreeBSD).
CLI example:
.. code-block:: bash
salt '*' pf.loglevel emerg
'''
# There's no way to getting the previous loglevel so imply we've
# always made a change.
ret = {'changes': True}
myos = __grains__['os']
if myos == 'FreeBSD':
all_levels = ['none', 'urgent', 'misc', 'loud']
else:
all_levels = ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug']
if level not in all_levels:
raise SaltInvocationError('Unknown loglevel: {0}'.format(level))
result = __salt__['cmd.run_all']('pfctl -x {0}'.format(level),
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered setting loglevel',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def load(file='/etc/pf.conf', noop=False):
'''
Load a ruleset from the specific file, overwriting the currently loaded ruleset.
file:
Full path to the file containing the ruleset.
noop:
Don't actually load the rules, just parse them.
CLI example:
.. code-block:: bash
salt '*' pf.load /etc/pf.conf.d/lockdown.conf
'''
# We cannot precisely determine if loading the ruleset implied
# any changes so assume it always does.
ret = {'changes': True}
cmd = ['pfctl', '-f', file]
if noop:
ret['changes'] = False
cmd.append('-n')
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem loading the ruleset from {0}'.format(file),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def table(command, table, **kwargs):
'''
Apply a command on the specified table.
table:
Name of the table.
command:
Command to apply to the table. Supported commands are:
- add
- delete
- expire
- flush
- kill
- replace
- show
- test
- zero
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.table expire table=spam_hosts number=300
salt '*' pf.table add table=local_hosts addresses='["127.0.0.1", "::1"]'
'''
ret = {}
all_commands = ['kill', 'flush', 'add', 'delete', 'expire', 'replace', 'show', 'test', 'zero']
if command not in all_commands:
raise SaltInvocationError('Unknown table command: {0}'.format(command))
cmd = ['pfctl', '-t', table, '-T', command]
if command in ['add', 'delete', 'replace', 'test']:
cmd += kwargs.get('addresses', [])
elif command == 'expire':
number = kwargs.get('number', None)
if not number:
raise SaltInvocationError('need expire_number argument for expire command')
else:
cmd.append(number)
result = __salt__['cmd.run_all'](cmd,
output_level='trace',
python_shell=False)
if result['retcode'] == 0:
if command == 'show':
ret = {'comment': result['stdout'].split()}
elif command == 'test':
ret = {'comment': result['stderr'], 'matches': True}
else:
if re.match(r'^(0.*|no changes)', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
# 'test' returns a non-zero code if the address didn't match, even if
# the command itself ran fine; also set 'matches' to False since not
# everything matched.
if command == 'test' and re.match(r'^\d+/\d+ addresses match.$', result['stderr']):
ret = {'comment': result['stderr'], 'matches': False}
else:
raise CommandExecutionError(
'Could not apply {0} on table {1}'.format(command, table),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def show(modifier):
'''
Show filter parameters.
modifier:
Modifier to apply for filtering. Only a useful subset of what pfctl supports
can be used with Salt.
- rules
- states
- tables
CLI example:
.. code-block:: bash
salt '*' pf.show rules
'''
# By definition showing the parameters makes no changes.
ret = {'changes': False}
capital_modifiers = ['Tables']
all_modifiers = ['rules', 'states', 'tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -s {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret['comment'] = result['stdout'].split('\n')
else:
raise CommandExecutionError(
'Could not show {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
saltstack/salt
|
salt/modules/pf.py
|
table
|
python
|
def table(command, table, **kwargs):
'''
Apply a command on the specified table.
table:
Name of the table.
command:
Command to apply to the table. Supported commands are:
- add
- delete
- expire
- flush
- kill
- replace
- show
- test
- zero
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.table expire table=spam_hosts number=300
salt '*' pf.table add table=local_hosts addresses='["127.0.0.1", "::1"]'
'''
ret = {}
all_commands = ['kill', 'flush', 'add', 'delete', 'expire', 'replace', 'show', 'test', 'zero']
if command not in all_commands:
raise SaltInvocationError('Unknown table command: {0}'.format(command))
cmd = ['pfctl', '-t', table, '-T', command]
if command in ['add', 'delete', 'replace', 'test']:
cmd += kwargs.get('addresses', [])
elif command == 'expire':
number = kwargs.get('number', None)
if not number:
raise SaltInvocationError('need expire_number argument for expire command')
else:
cmd.append(number)
result = __salt__['cmd.run_all'](cmd,
output_level='trace',
python_shell=False)
if result['retcode'] == 0:
if command == 'show':
ret = {'comment': result['stdout'].split()}
elif command == 'test':
ret = {'comment': result['stderr'], 'matches': True}
else:
if re.match(r'^(0.*|no changes)', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
# 'test' returns a non-zero code if the address didn't match, even if
# the command itself ran fine; also set 'matches' to False since not
# everything matched.
if command == 'test' and re.match(r'^\d+/\d+ addresses match.$', result['stderr']):
ret = {'comment': result['stderr'], 'matches': False}
else:
raise CommandExecutionError(
'Could not apply {0} on table {1}'.format(command, table),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
Apply a command on the specified table.
table:
Name of the table.
command:
Command to apply to the table. Supported commands are:
- add
- delete
- expire
- flush
- kill
- replace
- show
- test
- zero
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.table expire table=spam_hosts number=300
salt '*' pf.table add table=local_hosts addresses='["127.0.0.1", "::1"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pf.py#L235-L310
| null |
# -*- coding: utf-8 -*-
'''
Control the OpenBSD packet filter (PF).
:codeauthor: Jasper Lievisse Adriaanse <j@jasper.la>
.. versionadded:: 2019.2.0
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
import salt.utils.path
from salt.exceptions import (CommandExecutionError, SaltInvocationError)
log = logging.getLogger(__name__)
def __virtual__():
'''
Only works on OpenBSD and FreeBSD for now; other systems with pf (macOS,
FreeBSD, etc) need to be tested before enabling them.
'''
tested_oses = ['FreeBSD', 'OpenBSD']
if __grains__['os'] in tested_oses and salt.utils.path.which('pfctl'):
return True
return (False, 'The pf execution module cannot be loaded: either the '
'OS (' + __grains__['os'] + ') is not tested or the pfctl binary '
'was not found')
def enable():
'''
Enable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.enable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -e',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf enabled', 'changes': True}
else:
# If pf was already enabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf already enabled':
ret = {'comment': 'pf already enabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not enable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def disable():
'''
Disable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.disable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -d',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf disabled', 'changes': True}
else:
# If pf was already disabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf not enabled':
ret = {'comment': 'pf already disabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not disable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def loglevel(level):
'''
Set the debug level which limits the severity of log messages printed by ``pf(4)``.
level:
Log level. Should be one of the following: emerg, alert, crit, err, warning, notice,
info or debug (OpenBSD); or none, urgent, misc, loud (FreeBSD).
CLI example:
.. code-block:: bash
salt '*' pf.loglevel emerg
'''
# There's no way to getting the previous loglevel so imply we've
# always made a change.
ret = {'changes': True}
myos = __grains__['os']
if myos == 'FreeBSD':
all_levels = ['none', 'urgent', 'misc', 'loud']
else:
all_levels = ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug']
if level not in all_levels:
raise SaltInvocationError('Unknown loglevel: {0}'.format(level))
result = __salt__['cmd.run_all']('pfctl -x {0}'.format(level),
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered setting loglevel',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def load(file='/etc/pf.conf', noop=False):
'''
Load a ruleset from the specific file, overwriting the currently loaded ruleset.
file:
Full path to the file containing the ruleset.
noop:
Don't actually load the rules, just parse them.
CLI example:
.. code-block:: bash
salt '*' pf.load /etc/pf.conf.d/lockdown.conf
'''
# We cannot precisely determine if loading the ruleset implied
# any changes so assume it always does.
ret = {'changes': True}
cmd = ['pfctl', '-f', file]
if noop:
ret['changes'] = False
cmd.append('-n')
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem loading the ruleset from {0}'.format(file),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def flush(modifier):
'''
Flush the specified packet filter parameters.
modifier:
Should be one of the following:
- all
- info
- osfp
- rules
- sources
- states
- tables
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.flush states
'''
ret = {}
all_modifiers = ['rules', 'states', 'info', 'osfp', 'all', 'sources', 'tables']
# Accept the following two modifiers to allow for a consistent interface between
# pfctl(8) and Salt.
capital_modifiers = ['Sources', 'Tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -v -F {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
if re.match(r'^0.*', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
raise CommandExecutionError(
'Could not flush {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def show(modifier):
'''
Show filter parameters.
modifier:
Modifier to apply for filtering. Only a useful subset of what pfctl supports
can be used with Salt.
- rules
- states
- tables
CLI example:
.. code-block:: bash
salt '*' pf.show rules
'''
# By definition showing the parameters makes no changes.
ret = {'changes': False}
capital_modifiers = ['Tables']
all_modifiers = ['rules', 'states', 'tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -s {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret['comment'] = result['stdout'].split('\n')
else:
raise CommandExecutionError(
'Could not show {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
saltstack/salt
|
salt/modules/pf.py
|
show
|
python
|
def show(modifier):
'''
Show filter parameters.
modifier:
Modifier to apply for filtering. Only a useful subset of what pfctl supports
can be used with Salt.
- rules
- states
- tables
CLI example:
.. code-block:: bash
salt '*' pf.show rules
'''
# By definition showing the parameters makes no changes.
ret = {'changes': False}
capital_modifiers = ['Tables']
all_modifiers = ['rules', 'states', 'tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -s {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret['comment'] = result['stdout'].split('\n')
else:
raise CommandExecutionError(
'Could not show {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
Show filter parameters.
modifier:
Modifier to apply for filtering. Only a useful subset of what pfctl supports
can be used with Salt.
- rules
- states
- tables
CLI example:
.. code-block:: bash
salt '*' pf.show rules
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pf.py#L313-L356
| null |
# -*- coding: utf-8 -*-
'''
Control the OpenBSD packet filter (PF).
:codeauthor: Jasper Lievisse Adriaanse <j@jasper.la>
.. versionadded:: 2019.2.0
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
# Import salt libs
import salt.utils.path
from salt.exceptions import (CommandExecutionError, SaltInvocationError)
log = logging.getLogger(__name__)
def __virtual__():
'''
Only works on OpenBSD and FreeBSD for now; other systems with pf (macOS,
FreeBSD, etc) need to be tested before enabling them.
'''
tested_oses = ['FreeBSD', 'OpenBSD']
if __grains__['os'] in tested_oses and salt.utils.path.which('pfctl'):
return True
return (False, 'The pf execution module cannot be loaded: either the '
'OS (' + __grains__['os'] + ') is not tested or the pfctl binary '
'was not found')
def enable():
'''
Enable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.enable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -e',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf enabled', 'changes': True}
else:
# If pf was already enabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf already enabled':
ret = {'comment': 'pf already enabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not enable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def disable():
'''
Disable the Packet Filter.
CLI example:
.. code-block:: bash
salt '*' pf.disable
'''
ret = {}
result = __salt__['cmd.run_all']('pfctl -d',
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
ret = {'comment': 'pf disabled', 'changes': True}
else:
# If pf was already disabled the return code is also non-zero.
# Don't raise an exception in that case.
if result['stderr'] == 'pfctl: pf not enabled':
ret = {'comment': 'pf already disabled', 'changes': False}
else:
raise CommandExecutionError(
'Could not disable pf',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def loglevel(level):
'''
Set the debug level which limits the severity of log messages printed by ``pf(4)``.
level:
Log level. Should be one of the following: emerg, alert, crit, err, warning, notice,
info or debug (OpenBSD); or none, urgent, misc, loud (FreeBSD).
CLI example:
.. code-block:: bash
salt '*' pf.loglevel emerg
'''
# There's no way to getting the previous loglevel so imply we've
# always made a change.
ret = {'changes': True}
myos = __grains__['os']
if myos == 'FreeBSD':
all_levels = ['none', 'urgent', 'misc', 'loud']
else:
all_levels = ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug']
if level not in all_levels:
raise SaltInvocationError('Unknown loglevel: {0}'.format(level))
result = __salt__['cmd.run_all']('pfctl -x {0}'.format(level),
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered setting loglevel',
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def load(file='/etc/pf.conf', noop=False):
'''
Load a ruleset from the specific file, overwriting the currently loaded ruleset.
file:
Full path to the file containing the ruleset.
noop:
Don't actually load the rules, just parse them.
CLI example:
.. code-block:: bash
salt '*' pf.load /etc/pf.conf.d/lockdown.conf
'''
# We cannot precisely determine if loading the ruleset implied
# any changes so assume it always does.
ret = {'changes': True}
cmd = ['pfctl', '-f', file]
if noop:
ret['changes'] = False
cmd.append('-n')
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem loading the ruleset from {0}'.format(file),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def flush(modifier):
'''
Flush the specified packet filter parameters.
modifier:
Should be one of the following:
- all
- info
- osfp
- rules
- sources
- states
- tables
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.flush states
'''
ret = {}
all_modifiers = ['rules', 'states', 'info', 'osfp', 'all', 'sources', 'tables']
# Accept the following two modifiers to allow for a consistent interface between
# pfctl(8) and Salt.
capital_modifiers = ['Sources', 'Tables']
all_modifiers += capital_modifiers
if modifier.title() in capital_modifiers:
modifier = modifier.title()
if modifier not in all_modifiers:
raise SaltInvocationError('Unknown modifier: {0}'.format(modifier))
cmd = 'pfctl -v -F {0}'.format(modifier)
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if result['retcode'] == 0:
if re.match(r'^0.*', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
raise CommandExecutionError(
'Could not flush {0}'.format(modifier),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
def table(command, table, **kwargs):
'''
Apply a command on the specified table.
table:
Name of the table.
command:
Command to apply to the table. Supported commands are:
- add
- delete
- expire
- flush
- kill
- replace
- show
- test
- zero
Please refer to the OpenBSD `pfctl(8) <https://man.openbsd.org/pfctl#T>`_
documentation for a detailed explanation of each command.
CLI example:
.. code-block:: bash
salt '*' pf.table expire table=spam_hosts number=300
salt '*' pf.table add table=local_hosts addresses='["127.0.0.1", "::1"]'
'''
ret = {}
all_commands = ['kill', 'flush', 'add', 'delete', 'expire', 'replace', 'show', 'test', 'zero']
if command not in all_commands:
raise SaltInvocationError('Unknown table command: {0}'.format(command))
cmd = ['pfctl', '-t', table, '-T', command]
if command in ['add', 'delete', 'replace', 'test']:
cmd += kwargs.get('addresses', [])
elif command == 'expire':
number = kwargs.get('number', None)
if not number:
raise SaltInvocationError('need expire_number argument for expire command')
else:
cmd.append(number)
result = __salt__['cmd.run_all'](cmd,
output_level='trace',
python_shell=False)
if result['retcode'] == 0:
if command == 'show':
ret = {'comment': result['stdout'].split()}
elif command == 'test':
ret = {'comment': result['stderr'], 'matches': True}
else:
if re.match(r'^(0.*|no changes)', result['stderr']):
ret['changes'] = False
else:
ret['changes'] = True
ret['comment'] = result['stderr']
else:
# 'test' returns a non-zero code if the address didn't match, even if
# the command itself ran fine; also set 'matches' to False since not
# everything matched.
if command == 'test' and re.match(r'^\d+/\d+ addresses match.$', result['stderr']):
ret = {'comment': result['stderr'], 'matches': False}
else:
raise CommandExecutionError(
'Could not apply {0} on table {1}'.format(command, table),
info={'errors': [result['stderr']], 'changes': False}
)
return ret
|
saltstack/salt
|
salt/states/victorops.py
|
create_event
|
python
|
def create_event(name, message_type, routing_key='everyone', **kwargs):
'''
Create an event on the VictorOps service
.. code-block:: yaml
webserver-warning-message:
victorops.create_event:
- message_type: 'CRITICAL'
- entity_id: 'webserver/diskspace'
- state_message: 'Webserver diskspace is low.'
database-server-warning-message:
victorops.create_event:
- message_type: 'WARNING'
- entity_id: 'db_server/load'
- state_message: 'Database Server load is high.'
- entity_is_host: True
- entity_display_name: 'dbdserver.example.com'
The following parameters are required:
name
This is a short description of the event.
message_type
One of the following values: INFO, WARNING, ACKNOWLEDGEMENT, CRITICAL, RECOVERY.
The following parameters are optional:
routing_key
The key for where messages should be routed. By default, sent to 'everyone' route.
entity_id
The name of alerting entity. If not provided, a random name will be assigned.
timestamp
Timestamp of the alert in seconds since epoch. Defaults to the time the alert is received at VictorOps.
timestamp_fmt
The date format for the timestamp parameter. Defaults to ''%Y-%m-%dT%H:%M:%S'.
state_start_time
The time this entity entered its current state (seconds since epoch). Defaults to the time alert is received.
state_start_time_fmt
The date format for the timestamp parameter. Defaults to '%Y-%m-%dT%H:%M:%S'.
state_message
Any additional status information from the alert item.
entity_is_host
Used within VictorOps to select the appropriate display format for the incident.
entity_display_name
Used within VictorOps to display a human-readable name for the entity.
ack_message
A user entered comment for the acknowledgment.
ack_author
The user that acknowledged the incident.
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'Need to create event: {0}'.format(name)
return ret
res = __salt__['victorops.create_event'](
message_type=message_type,
routing_key=routing_key,
**kwargs
)
if res['result'] == 'success':
ret['result'] = True
ret['comment'] = 'Created event: {0} for entity {1}'.format(name, res['entity_id'])
else:
ret['result'] = False
ret['comment'] = 'Failed to create event: {0}'.format(res['message'])
return ret
|
Create an event on the VictorOps service
.. code-block:: yaml
webserver-warning-message:
victorops.create_event:
- message_type: 'CRITICAL'
- entity_id: 'webserver/diskspace'
- state_message: 'Webserver diskspace is low.'
database-server-warning-message:
victorops.create_event:
- message_type: 'WARNING'
- entity_id: 'db_server/load'
- state_message: 'Database Server load is high.'
- entity_is_host: True
- entity_display_name: 'dbdserver.example.com'
The following parameters are required:
name
This is a short description of the event.
message_type
One of the following values: INFO, WARNING, ACKNOWLEDGEMENT, CRITICAL, RECOVERY.
The following parameters are optional:
routing_key
The key for where messages should be routed. By default, sent to 'everyone' route.
entity_id
The name of alerting entity. If not provided, a random name will be assigned.
timestamp
Timestamp of the alert in seconds since epoch. Defaults to the time the alert is received at VictorOps.
timestamp_fmt
The date format for the timestamp parameter. Defaults to ''%Y-%m-%dT%H:%M:%S'.
state_start_time
The time this entity entered its current state (seconds since epoch). Defaults to the time alert is received.
state_start_time_fmt
The date format for the timestamp parameter. Defaults to '%Y-%m-%dT%H:%M:%S'.
state_message
Any additional status information from the alert item.
entity_is_host
Used within VictorOps to select the appropriate display format for the incident.
entity_display_name
Used within VictorOps to display a human-readable name for the entity.
ack_message
A user entered comment for the acknowledgment.
ack_author
The user that acknowledged the incident.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/victorops.py#L31-L115
| null |
# -*- coding: utf-8 -*-
'''
Create an Event in VictorOps
============================
.. versionadded:: 2015.8.0
This state is useful for creating events on the
VictorOps service during state runs.
.. code-block:: yaml
webserver-warning-message:
victorops.create_event:
- message_type: 'CRITICAL'
- entity_id: 'webserver/diskspace'
- state_message: 'Webserver diskspace is low.'
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
def __virtual__():
'''
Only load if the victorops module is available in __salt__
'''
return 'victorops' if 'victorops.create_event' in __salt__ else False
|
saltstack/salt
|
salt/modules/neutron.py
|
_auth
|
python
|
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
|
Set up neutron credentials
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L99-L153
| null |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
update_quota
|
python
|
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
|
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L212-L245
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_port
|
python
|
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
|
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L322-L345
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
update_port
|
python
|
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
|
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L348-L366
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_network
|
python
|
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
|
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L425-L448
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
update_network
|
python
|
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
|
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L451-L467
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_subnet
|
python
|
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
|
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L525-L544
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
update_subnet
|
python
|
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
|
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L547-L563
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_router
|
python
|
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
|
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L621-L640
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
update_router
|
python
|
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
|
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L643-L668
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
add_interface_router
|
python
|
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
|
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L689-L705
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
remove_interface_router
|
python
|
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
|
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L708-L724
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
add_gateway_router
|
python
|
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
|
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L727-L743
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_floatingip
|
python
|
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
|
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L800-L816
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
update_floatingip
|
python
|
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
|
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L819-L836
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_security_group
|
python
|
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
|
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L893-L910
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
update_security_group
|
python
|
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
|
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L913-L932
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_security_group_rule
|
python
|
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
|
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L989-L1026
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
list_vpnservices
|
python
|
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
|
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L1047-L1062
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
show_vpnservice
|
python
|
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
|
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L1065-L1080
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_vpnservice
|
python
|
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
|
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L1083-L1102
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
update_vpnservice
|
python
|
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
|
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L1105-L1121
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_ipsec_site_connection
|
python
|
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
|
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L1179-L1232
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_ikepolicy
|
python
|
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
|
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L1289-L1318
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_ipsecpolicy
|
python
|
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
|
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L1375-L1404
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
create_firewall_rule
|
python
|
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
|
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L1462-L1489
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/modules/neutron.py
|
update_firewall_rule
|
python
|
def update_firewall_rule(firewall_rule,
protocol=None,
action=None,
name=None,
description=None,
ip_version=None,
source_ip_address=None,
destination_ip_address=None,
source_port=None,
destination_port=None,
shared=None,
enabled=None,
profile=None):
'''
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
'''
conn = _auth(profile)
return conn.update_firewall_rule(firewall_rule, protocol, action, name, description, ip_version,
source_ip_address, destination_ip_address, source_port, destination_port,
shared, enabled)
|
Update a firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.update_firewall_rule firewall_rule protocol=PROTOCOL action=ACTION
name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS
source_port=SOURCE_PORT destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param firewall_rule: ID or name of firewall rule to update.
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None". (Optional)
:param action: Action for the firewall rule, choose "allow" or "deny". (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
:param profile: Profile to build on (Optional)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L1510-L1552
|
[
"def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials['keystone.password']\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n region_name = credentials.get('keystone.region_name', None)\n service_type = credentials.get('keystone.service_type', 'network')\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)\n verify = credentials.get('keystone.verify', True)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password')\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n region_name = __salt__['config.option']('keystone.region_name')\n service_type = __salt__['config.option']('keystone.service_type')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')\n verify = __salt__['config.option']('keystone.verify')\n\n if use_keystoneauth is True:\n project_domain_name = credentials['keystone.project_domain_name']\n user_domain_name = credentials['keystone.user_domain_name']\n\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system,\n 'use_keystoneauth': use_keystoneauth,\n 'verify': verify,\n 'project_domain_name': project_domain_name,\n 'user_domain_name': user_domain_name\n }\n else:\n kwargs = {\n 'username': user,\n 'password': password,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'region_name': region_name,\n 'service_type': service_type,\n 'os_auth_plugin': os_auth_system\n }\n\n return suoneu.SaltNeutron(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Neutron calls
:depends: - neutronclient Python module
:configuration: This module is not usable until the user, password, tenant, and
auth URL are specified either in a pillar or in the minion's config file.
For example::
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
openstack2:
keystone.user: 'admin'
keystone.password: 'password'
keystone.tenant: 'admin'
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
With this configuration in place, any of the neutron functions
can make use of a configuration profile by declaring it explicitly.
For example::
salt '*' neutron.network_list profile=openstack1
To use keystoneauth1 instead of keystoneclient, include the `use_keystoneauth`
option in the pillar or minion config.
.. note:: this is required to use keystone v3 as for authentication.
.. code-block:: yaml
keystone.user: admin
keystone.password: verybadpass
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v3/'
keystone.region_name: 'RegionOne'
keystone.service_type: 'network'
keystone.use_keystoneauth: true
keystone.verify: '/path/to/custom/certs/ca-bundle.crt'
Note: by default the neutron module will attempt to verify its connection
utilizing the system certificates. If you need to verify against another bundle
of CA certificates or want to skip verification altogether you will need to
specify the `verify` option. You can specify True or False to verify (or not)
against system certificates, a path to a bundle or CA certs to check against, or
None to allow keystoneauth to search for the certificates on its own.(defaults to True)
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
try:
import salt.utils.openstack.neutron as suoneu
HAS_NEUTRON = True
except NameError as exc:
HAS_NEUTRON = False
# Get logging started
log = logging.getLogger(__name__)
# Function alias to not shadow built-ins
__func_alias__ = {
'list_': 'list'
}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
return HAS_NEUTRON
__opts__ = {}
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
region_name = credentials.get('keystone.region_name', None)
service_type = credentials.get('keystone.service_type', 'network')
os_auth_system = credentials.get('keystone.os_auth_system', None)
use_keystoneauth = credentials.get('keystone.use_keystoneauth', False)
verify = credentials.get('keystone.verify', True)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password')
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
region_name = __salt__['config.option']('keystone.region_name')
service_type = __salt__['config.option']('keystone.service_type')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
use_keystoneauth = __salt__['config.option']('keystone.use_keystoneauth')
verify = __salt__['config.option']('keystone.verify')
if use_keystoneauth is True:
project_domain_name = credentials['keystone.project_domain_name']
user_domain_name = credentials['keystone.user_domain_name']
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system,
'use_keystoneauth': use_keystoneauth,
'verify': verify,
'project_domain_name': project_domain_name,
'user_domain_name': user_domain_name
}
else:
kwargs = {
'username': user,
'password': password,
'tenant_name': tenant,
'auth_url': auth_url,
'region_name': region_name,
'service_type': service_type,
'os_auth_plugin': os_auth_system
}
return suoneu.SaltNeutron(**kwargs)
def get_quotas_tenant(profile=None):
'''
Fetches tenant info in server's context for following quota operation
CLI Example:
.. code-block:: bash
salt '*' neutron.get_quotas_tenant
salt '*' neutron.get_quotas_tenant profile=openstack1
:param profile: Profile to build on (Optional)
:return: Quotas information
'''
conn = _auth(profile)
return conn.get_quotas_tenant()
def list_quotas(profile=None):
'''
Fetches all tenants quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.list_quotas
salt '*' neutron.list_quotas profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of quotas
'''
conn = _auth(profile)
return conn.list_quotas()
def show_quota(tenant_id, profile=None):
'''
Fetches information of a certain tenant's quotas
CLI Example:
.. code-block:: bash
salt '*' neutron.show_quota tenant-id
salt '*' neutron.show_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant
:param profile: Profile to build on (Optional)
:return: Quota information
'''
conn = _auth(profile)
return conn.show_quota(tenant_id)
def update_quota(tenant_id,
subnet=None,
router=None,
network=None,
floatingip=None,
port=None,
security_group=None,
security_group_rule=None,
profile=None):
'''
Update a tenant's quota
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id subnet=40 router=50
network=10 floatingip=30 port=30
:param tenant_id: ID of tenant
:param subnet: Value of subnet quota (Optional)
:param router: Value of router quota (Optional)
:param network: Value of network quota (Optional)
:param floatingip: Value of floatingip quota (Optional)
:param port: Value of port quota (Optional)
:param security_group: Value of security group (Optional)
:param security_group_rule: Value of security group rule (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated quota
'''
conn = _auth(profile)
return conn.update_quota(tenant_id, subnet, router, network,
floatingip, port, security_group,
security_group_rule)
def delete_quota(tenant_id, profile=None):
'''
Delete the specified tenant's quota value
CLI Example:
.. code-block:: bash
salt '*' neutron.update_quota tenant-id
salt '*' neutron.update_quota tenant-id profile=openstack1
:param tenant_id: ID of tenant to quota delete
:param profile: Profile to build on (Optional)
:return: True(Delete succeed) or False(Delete failed)
'''
conn = _auth(profile)
return conn.delete_quota(tenant_id)
def list_extensions(profile=None):
'''
Fetches a list of all extensions on server side
CLI Example:
.. code-block:: bash
salt '*' neutron.list_extensions
salt '*' neutron.list_extensions profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of extensions
'''
conn = _auth(profile)
return conn.list_extensions()
def list_ports(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ports
salt '*' neutron.list_ports profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of port
'''
conn = _auth(profile)
return conn.list_ports()
def show_port(port, profile=None):
'''
Fetches information of a certain port
CLI Example:
.. code-block:: bash
salt '*' neutron.show_port port-id
salt '*' neutron.show_port port-id profile=openstack1
:param port: ID or name of port to look up
:param profile: Profile to build on (Optional)
:return: Port information
'''
conn = _auth(profile)
return conn.show_port(port)
def create_port(name,
network,
device_id=None,
admin_state_up=True,
profile=None):
'''
Creates a new port
CLI Example:
.. code-block:: bash
salt '*' neutron.create_port network-name port-name
:param name: Name of port to create
:param network: Network name or ID
:param device_id: ID of device (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Created port information
'''
conn = _auth(profile)
return conn.create_port(name, network, device_id, admin_state_up)
def update_port(port, name, admin_state_up=True, profile=None):
'''
Updates a port
CLI Example:
.. code-block:: bash
salt '*' neutron.update_port port-name network-name new-port-name
:param port: Port name or ID
:param name: Name of this port
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated port information
'''
conn = _auth(profile)
return conn.update_port(port, name, admin_state_up)
def delete_port(port, profile=None):
'''
Deletes the specified port
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network port-name
salt '*' neutron.delete_network port-name profile=openstack1
:param port: port name or ID
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_port(port)
def list_networks(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
salt '*' neutron.list_networks profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of network
'''
conn = _auth(profile)
return conn.list_networks()
def show_network(network, profile=None):
'''
Fetches information of a certain network
CLI Example:
.. code-block:: bash
salt '*' neutron.show_network network-name
salt '*' neutron.show_network network-name profile=openstack1
:param network: ID or name of network to look up
:param profile: Profile to build on (Optional)
:return: Network information
'''
conn = _auth(profile)
return conn.show_network(network)
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None):
'''
Creates a new network
CLI Example:
.. code-block:: bash
salt '*' neutron.create_network network-name
salt '*' neutron.create_network network-name profile=openstack1
:param name: Name of network to create
:param admin_state_up: should the state of the network be up?
default: True (Optional)
:param router_ext: True then if create the external network (Optional)
:param network_type: the Type of network that the provider is such as GRE, VXLAN, VLAN, FLAT, or LOCAL (Optional)
:param physical_network: the name of the physical network as neutron knows it (Optional)
:param segmentation_id: the vlan id or GRE id (Optional)
:param shared: is the network shared or not (Optional)
:param profile: Profile to build on (Optional)
:return: Created network information
'''
conn = _auth(profile)
return conn.create_network(name, admin_state_up, router_ext, network_type, physical_network, segmentation_id, shared)
def update_network(network, name, profile=None):
'''
Updates a network
CLI Example:
.. code-block:: bash
salt '*' neutron.update_network network-name new-network-name
:param network: ID or name of network to update
:param name: Name of this network
:param profile: Profile to build on (Optional)
:return: Value of updated network information
'''
conn = _auth(profile)
return conn.update_network(network, name)
def delete_network(network, profile=None):
'''
Deletes the specified network
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_network network-name
salt '*' neutron.delete_network network-name profile=openstack1
:param network: ID or name of network to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_network(network)
def list_subnets(profile=None):
'''
Fetches a list of all networks for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_subnets
salt '*' neutron.list_subnets profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of subnet
'''
conn = _auth(profile)
return conn.list_subnets()
def show_subnet(subnet, profile=None):
'''
Fetches information of a certain subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.show_subnet subnet-name
:param subnet: ID or name of subnet to look up
:param profile: Profile to build on (Optional)
:return: Subnet information
'''
conn = _auth(profile)
return conn.show_subnet(subnet)
def create_subnet(network, cidr, name=None,
ip_version=4, profile=None):
'''
Creates a new subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.create_subnet network-name 192.168.1.0/24
:param network: Network ID or name this subnet belongs to
:param cidr: CIDR of subnet to create (Ex. '192.168.1.0/24')
:param name: Name of the subnet to create (Optional)
:param ip_version: Version to use, default is 4(IPv4) (Optional)
:param profile: Profile to build on (Optional)
:return: Created subnet information
'''
conn = _auth(profile)
return conn.create_subnet(network, cidr, name, ip_version)
def update_subnet(subnet, name, profile=None):
'''
Updates a subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.update_subnet subnet-name new-subnet-name
:param subnet: ID or name of subnet to update
:param name: Name of this subnet
:param profile: Profile to build on (Optional)
:return: Value of updated subnet information
'''
conn = _auth(profile)
return conn.update_subnet(subnet, name)
def delete_subnet(subnet, profile=None):
'''
Deletes the specified subnet
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_subnet subnet-name
salt '*' neutron.delete_subnet subnet-name profile=openstack1
:param subnet: ID or name of subnet to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_subnet(subnet)
def list_routers(profile=None):
'''
Fetches a list of all routers for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
salt '*' neutron.list_routers profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of router
'''
conn = _auth(profile)
return conn.list_routers()
def show_router(router, profile=None):
'''
Fetches information of a certain router
CLI Example:
.. code-block:: bash
salt '*' neutron.show_router router-name
:param router: ID or name of router to look up
:param profile: Profile to build on (Optional)
:return: Router information
'''
conn = _auth(profile)
return conn.show_router(router)
def create_router(name, ext_network=None,
admin_state_up=True, profile=None):
'''
Creates a new router
CLI Example:
.. code-block:: bash
salt '*' neutron.create_router new-router-name
:param name: Name of router to create (must be first)
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default:true (Optional)
:param profile: Profile to build on (Optional)
:return: Created router information
'''
conn = _auth(profile)
return conn.create_router(name, ext_network, admin_state_up)
def update_router(router,
name=None,
admin_state_up=None,
profile=None,
**kwargs):
'''
Updates a router
CLI Example:
.. code-block:: bash
salt '*' neutron.update_router router_id name=new-router-name
admin_state_up=True
:param router: ID or name of router to update
:param name: Name of this router
:param ext_network: ID or name of the external for the gateway (Optional)
:param admin_state_up: Set admin state up to true or false,
default: true (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Value of updated router information
'''
conn = _auth(profile)
return conn.update_router(router, name, admin_state_up, **kwargs)
def delete_router(router, profile=None):
'''
Delete the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_router router-name
:param router: ID or name of router to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_router(router)
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: Added interface information
'''
conn = _auth(profile)
return conn.add_interface_router(router, subnet)
def remove_interface_router(router, subnet, profile=None):
'''
Removes an internal network interface from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_interface_router(router, subnet)
def add_gateway_router(router, ext_network, profile=None):
'''
Adds an external network gateway to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_gateway_router router-name ext-network-name
:param router: ID or name of the router
:param ext_network: ID or name of the external network the gateway
:param profile: Profile to build on (Optional)
:return: Added Gateway router information
'''
conn = _auth(profile)
return conn.add_gateway_router(router, ext_network)
def remove_gateway_router(router, profile=None):
'''
Removes an external network gateway from the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.remove_gateway_router router-name
:param router: ID or name of router
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.remove_gateway_router(router)
def list_floatingips(profile=None):
'''
Fetch a list of all floatingIPs for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_floatingips
salt '*' neutron.list_floatingips profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of floatingIP
'''
conn = _auth(profile)
return conn.list_floatingips()
def show_floatingip(floatingip_id, profile=None):
'''
Fetches information of a certain floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.show_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to look up
:param profile: Profile to build on (Optional)
:return: Floating IP information
'''
conn = _auth(profile)
return conn.show_floatingip(floatingip_id)
def create_floatingip(floating_network, port=None, profile=None):
'''
Creates a new floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.create_floatingip network-name port-name
:param floating_network: Network name or ID to allocate floatingIP from
:param port: Of the port to be associated with the floatingIP (Optional)
:param profile: Profile to build on (Optional)
:return: Created floatingIP information
'''
conn = _auth(profile)
return conn.create_floatingip(floating_network, port)
def update_floatingip(floatingip_id, port=None, profile=None):
'''
Updates a floatingIP
CLI Example:
.. code-block:: bash
salt '*' neutron.update_floatingip network-name port-name
:param floatingip_id: ID of floatingIP
:param port: ID or name of port, to associate floatingip to `None` or do
not specify to disassociate the floatingip (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated floating IP information
'''
conn = _auth(profile)
return conn.update_floatingip(floatingip_id, port)
def delete_floatingip(floatingip_id, profile=None):
'''
Deletes the specified floating IP
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_floatingip floatingip-id
:param floatingip_id: ID of floatingIP to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_floatingip(floatingip_id)
def list_security_groups(profile=None):
'''
Fetches a list of all security groups for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_groups
salt '*' neutron.list_security_groups profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group
'''
conn = _auth(profile)
return conn.list_security_groups()
def show_security_group(security_group, profile=None):
'''
Fetches information of a certain security group
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group security-group-name
:param security_group: ID or name of security group to look up
:param profile: Profile to build on (Optional)
:return: Security group information
'''
conn = _auth(profile)
return conn.show_security_group(security_group)
def create_security_group(name=None, description=None, profile=None):
'''
Creates a new security group
CLI Example:
.. code-block:: bash
salt '*' neutron.create_security_group security-group-name \
description='Security group for servers'
:param name: Name of security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group information
'''
conn = _auth(profile)
return conn.create_security_group(name, description)
def update_security_group(security_group, name=None, description=None,
profile=None):
'''
Updates a security group
CLI Example:
.. code-block:: bash
salt '*' neutron.update_security_group security-group-name \
new-security-group-name
:param security_group: ID or name of security group to update
:param name: Name of this security group (Optional)
:param description: Description of security group (Optional)
:param profile: Profile to build on (Optional)
:return: Value of updated security group information
'''
conn = _auth(profile)
return conn.update_security_group(security_group, name, description)
def delete_security_group(security_group, profile=None):
'''
Deletes the specified security group
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group security-group-name
:param security_group: ID or name of security group to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group(security_group)
def list_security_group_rules(profile=None):
'''
Fetches a list of all security group rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_security_group_rules
salt '*' neutron.list_security_group_rules profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of security group rule
'''
conn = _auth(profile)
return conn.list_security_group_rules()
def show_security_group_rule(security_group_rule_id, profile=None):
'''
Fetches information of a certain security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to look up
:param profile: Profile to build on (Optional)
:return: Security group rule information
'''
conn = _auth(profile)
return conn.show_security_group_rule(security_group_rule_id)
def create_security_group_rule(security_group,
remote_group_id=None,
direction='ingress',
protocol=None,
port_range_min=None,
port_range_max=None,
ethertype='IPv4',
profile=None):
'''
Creates a new security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_security_group_rule security-group-rule-id
:param security_group: Security group name or ID to add rule
:param remote_group_id: Remote security group name or ID to
apply rule (Optional)
:param direction: Direction of traffic: ingress/egress,
default: ingress (Optional)
:param protocol: Protocol of packet: null/icmp/tcp/udp,
default: null (Optional)
:param port_range_min: Starting port range (Optional)
:param port_range_max: Ending port range (Optional)
:param ethertype: IPv4/IPv6, default: IPv4 (Optional)
:param profile: Profile to build on (Optional)
:return: Created security group rule information
'''
conn = _auth(profile)
return conn.create_security_group_rule(security_group,
remote_group_id,
direction,
protocol,
port_range_min,
port_range_max,
ethertype)
def delete_security_group_rule(security_group_rule_id, profile=None):
'''
Deletes the specified security group rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_security_group_rule security-group-rule-id
:param security_group_rule_id: ID of security group rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_security_group_rule(security_group_rule_id)
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service
'''
conn = _auth(profile)
return conn.list_vpnservices(retrieve_all, **kwargs)
def show_vpnservice(vpnservice, profile=None, **kwargs):
'''
Fetches information of a specific VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.show_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to look up
:param profile: Profile to build on (Optional)
:return: VPN service information
'''
conn = _auth(profile)
return conn.show_vpnservice(vpnservice, **kwargs)
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
:param admin_state_up: Set admin state up to true or false,
default:True (Optional)
:param profile: Profile to build on (Optional)
:return: Created VPN service information
'''
conn = _auth(profile)
return conn.create_vpnservice(subnet, router, name, admin_state_up)
def update_vpnservice(vpnservice, desc, profile=None):
'''
Updates a VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.update_vpnservice vpnservice-name desc='VPN Service1'
:param vpnservice: ID or name of vpn service to update
:param desc: Set a description for the VPN service
:param profile: Profile to build on (Optional)
:return: Value of updated VPN service information
'''
conn = _auth(profile)
return conn.update_vpnservice(vpnservice, desc)
def delete_vpnservice(vpnservice, profile=None):
'''
Deletes the specified VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_vpnservice vpnservice-name
:param vpnservice: ID or name of vpn service to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_vpnservice(vpnservice)
def list_ipsec_site_connections(profile=None):
'''
Fetches all configured IPsec Site Connections for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsec_site_connections
salt '*' neutron.list_ipsec_site_connections profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec site connection
'''
conn = _auth(profile)
return conn.list_ipsec_site_connections()
def show_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Fetches information of a specific IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection
to look up
:param profile: Profile to build on (Optional)
:return: IPSec site connection information
'''
conn = _auth(profile)
return conn.show_ipsec_site_connection(ipsec_site_connection)
def create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up=True,
profile=None,
**kwargs):
'''
Creates a new IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsec_site_connection connection-name
ipsec-policy-name ikepolicy-name vpnservice-name
192.168.XXX.XXX/24 192.168.XXX.XXX 192.168.XXX.XXX secret
:param name: Set friendly name for the connection
:param ipsecpolicy: IPSec policy ID or name associated with this connection
:param ikepolicy: IKE policy ID or name associated with this connection
:param vpnservice: VPN service instance ID or name associated with
this connection
:param peer_cidrs: Remote subnet(s) in CIDR format
:param peer_address: Peer gateway public IPv4/IPv6 address or FQDN
:param peer_id: Peer router identity for authentication
Can be IPv4/IPv6 address, e-mail address, key id, or FQDN
:param psk: Pre-shared key string
:param initiator: Initiator state in lowercase, default:bi-directional
:param admin_state_up: Set admin state up to true or false,
default: True (Optional)
:param mtu: size for the connection, default:1500 (Optional)
:param dpd_action: Dead Peer Detection attribute: hold/clear/disabled/
restart/restart-by-peer (Optional)
:param dpd_interval: Dead Peer Detection attribute (Optional)
:param dpd_timeout: Dead Peer Detection attribute (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec site connection information
'''
conn = _auth(profile)
return conn.create_ipsec_site_connection(name,
ipsecpolicy,
ikepolicy,
vpnservice,
peer_cidrs,
peer_address,
peer_id,
psk,
admin_state_up,
**kwargs)
def delete_ipsec_site_connection(ipsec_site_connection, profile=None):
'''
Deletes the specified IPsecSiteConnection
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsec_site_connection connection-name
:param ipsec_site_connection: ID or name of ipsec site connection to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsec_site_connection(ipsec_site_connection)
def list_ikepolicies(profile=None):
'''
Fetches a list of all configured IKEPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ikepolicies
salt '*' neutron.list_ikepolicies profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IKE policy
'''
conn = _auth(profile)
return conn.list_ikepolicies()
def show_ikepolicy(ikepolicy, profile=None):
'''
Fetches information of a specific IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of ikepolicy to look up
:param profile: Profile to build on (Optional)
:return: IKE policy information
'''
conn = _auth(profile)
return conn.show_ikepolicy(ikepolicy)
def create_ikepolicy(name, profile=None, **kwargs):
'''
Creates a new IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ikepolicy ikepolicy-name
phase1_negotiation_mode=main auth_algorithm=sha1
encryption_algorithm=aes-128 pfs=group5
:param name: Name of the IKE policy
:param phase1_negotiation_mode: IKE Phase1 negotiation mode in lowercase,
default: main (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase.
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IKE lifetime attribute. default: seconds (Optional)
:param value: IKE lifetime attribute. default: 3600 (Optional)
:param ike_version: IKE version in lowercase, default: v1 (Optional)
:param profile: Profile to build on (Optional)
:param kwargs:
:return: Created IKE policy information
'''
conn = _auth(profile)
return conn.create_ikepolicy(name, **kwargs)
def delete_ikepolicy(ikepolicy, profile=None):
'''
Deletes the specified IKEPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ikepolicy ikepolicy-name
:param ikepolicy: ID or name of IKE policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ikepolicy(ikepolicy)
def list_ipsecpolicies(profile=None):
'''
Fetches a list of all configured IPsecPolicies for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name
salt '*' neutron.list_ipsecpolicies ipsecpolicy-name profile=openstack1
:param profile: Profile to build on (Optional)
:return: List of IPSec policy
'''
conn = _auth(profile)
return conn.list_ipsecpolicies()
def show_ipsecpolicy(ipsecpolicy, profile=None):
'''
Fetches information of a specific IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.show_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to look up
:param profile: Profile to build on (Optional)
:return: IPSec policy information
'''
conn = _auth(profile)
return conn.show_ipsecpolicy(ipsecpolicy)
def create_ipsecpolicy(name, profile=None, **kwargs):
'''
Creates a new IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.create_ipsecpolicy ipsecpolicy-name
transform_protocol=esp auth_algorithm=sha1
encapsulation_mode=tunnel encryption_algorithm=aes-128
:param name: Name of the IPSec policy
:param transform_protocol: Transform protocol in lowercase,
default: esp (Optional)
:param auth_algorithm: Authentication algorithm in lowercase,
default: sha1 (Optional)
:param encapsulation_mode: Encapsulation mode in lowercase,
default: tunnel (Optional)
:param encryption_algorithm: Encryption algorithm in lowercase,
default:aes-128 (Optional)
:param pfs: Prefect Forward Security in lowercase,
default: group5 (Optional)
:param units: IPSec lifetime attribute. default: seconds (Optional)
:param value: IPSec lifetime attribute. default: 3600 (Optional)
:param profile: Profile to build on (Optional)
:return: Created IPSec policy information
'''
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
def delete_ipsecpolicy(ipsecpolicy, profile=None):
'''
Deletes the specified IPsecPolicy
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_ipsecpolicy ipsecpolicy-name
:param ipsecpolicy: ID or name of IPSec policy to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_ipsecpolicy(ipsecpolicy)
def list_firewall_rules(profile=None):
'''
Fetches a list of all firewall rules for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewall_rules
:param profile: Profile to build on (Optional)
:return: List of firewall rules
'''
conn = _auth(profile)
return conn.list_firewall_rules()
def show_firewall_rule(firewall_rule, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall_rule firewall-rule-name
:param ipsecpolicy: ID or name of firewall rule to look up
:param profile: Profile to build on (Optional)
:return: firewall rule information
'''
conn = _auth(profile)
return conn.show_firewall_rule(firewall_rule)
def create_firewall_rule(protocol, action, profile=None, **kwargs):
'''
Creates a new firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.create_firewall_rule protocol action
tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION
source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADDRESS source_port=SOURCE_PORT
destination_port=DESTINATION_PORT shared=SHARED enabled=ENABLED
:param protocol: Protocol for the firewall rule, choose "tcp","udp","icmp" or "None".
:param action: Action for the firewall rule, choose "allow" or "deny".
:param tenant_id: The owner tenant ID. (Optional)
:param name: Name for the firewall rule. (Optional)
:param description: Description for the firewall rule. (Optional)
:param ip_version: IP protocol version, default: 4. (Optional)
:param source_ip_address: Source IP address or subnet. (Optional)
:param destination_ip_address: Destination IP address or subnet. (Optional)
:param source_port: Source port (integer in [1, 65535] or range in a:b). (Optional)
:param destination_port: Destination port (integer in [1, 65535] or range in a:b). (Optional)
:param shared: Set shared to True, default: False. (Optional)
:param enabled: To enable this rule, default: True. (Optional)
'''
conn = _auth(profile)
return conn.create_firewall_rule(protocol, action, **kwargs)
def delete_firewall_rule(firewall_rule, profile=None):
'''
Deletes the specified firewall_rule
CLI Example:
.. code-block:: bash
salt '*' neutron.delete_firewall_rule firewall-rule
:param firewall_rule: ID or name of firewall rule to delete
:param profile: Profile to build on (Optional)
:return: True(Succeed) or False
'''
conn = _auth(profile)
return conn.delete_firewall_rule(firewall_rule)
def list_firewalls(profile=None):
'''
Fetches a list of all firewalls for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_firewalls
:param profile: Profile to build on (Optional)
:return: List of firewalls
'''
conn = _auth(profile)
return conn.list_firewalls()
def show_firewall(firewall, profile=None):
'''
Fetches information of a specific firewall rule
CLI Example:
.. code-block:: bash
salt '*' neutron.show_firewall firewall
:param firewall: ID or name of firewall to look up
:param profile: Profile to build on (Optional)
:return: firewall information
'''
conn = _auth(profile)
return conn.show_firewall(firewall)
def list_l3_agent_hosting_routers(router, profile=None):
'''
List L3 agents hosting a router.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_l3_agent_hosting_routers router
:param router:router name or ID to query.
:param profile: Profile to build on (Optional)
:return: L3 agents message.
'''
conn = _auth(profile)
return conn.list_l3_agent_hosting_routers(router)
def list_agents(profile=None):
'''
List agents.
CLI Example:
.. code-block:: bash
salt '*' neutron.list_agents
:param profile: Profile to build on (Optional)
:return: agents message.
'''
conn = _auth(profile)
return conn.list_agents()
|
saltstack/salt
|
salt/runners/jobs.py
|
active
|
python
|
def active(display_progress=False):
'''
Return a report on all actively running jobs from a job id centric
perspective
CLI Example:
.. code-block:: bash
salt-run jobs.active
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
if display_progress:
__jid_event__.fire_event({
'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
}, 'progress')
for minion, data in six.iteritems(active_):
if display_progress:
__jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
if not isinstance(data, list):
continue
for job in data:
if not job['jid'] in ret:
ret[job['jid']] = _format_jid_instance(job['jid'], job)
ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
else:
ret[job['jid']]['Running'].append({minion: job['pid']})
mminion = salt.minion.MasterMinion(__opts__)
for jid in ret:
returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
if data:
for minion in data:
if minion not in ret[jid]['Returned']:
ret[jid]['Returned'].append(minion)
return ret
|
Return a report on all actively running jobs from a job id centric
perspective
CLI Example:
.. code-block:: bash
salt-run jobs.active
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/jobs.py#L34-L78
|
[
"def iteritems(d, **kw):\n return d.iteritems(**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 _format_jid_instance(jid, job):\n '''\n Helper to format jid instance\n '''\n ret = _format_job_instance(job)\n ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})\n return ret\n",
"def _get_returner(returner_types):\n '''\n Helper to iterate over returner_types and pick the first one\n '''\n for returner in returner_types:\n if returner and returner is not None:\n return returner\n"
] |
# -*- coding: utf-8 -*-
'''
A convenience system to manage jobs, both active and already run
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import os
# Import salt libs
import salt.client
import salt.payload
import salt.utils.args
import salt.utils.files
import salt.utils.jid
import salt.minion
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.exceptions import SaltClientError
try:
import dateutil.parser as dateutil_parser
DATEUTIL_SUPPORT = True
except ImportError:
DATEUTIL_SUPPORT = False
log = logging.getLogger(__name__)
def lookup_jid(jid,
ext_source=None,
returned=True,
missing=False,
display_progress=False):
'''
Return the printout from a previously executed job
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
returned : True
If ``True``, include the minions that did return from the command.
.. versionadded:: 2015.8.0
missing : False
If ``True``, include the minions that did *not* return from the
command.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run jobs.lookup_jid 20130916125524463507
salt-run jobs.lookup_jid 20130916125524463507 --out=highstate
'''
ret = {}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
try:
data = list_job(
jid,
ext_source=ext_source,
display_progress=display_progress
)
except TypeError:
return ('Requested returner could not be loaded. '
'No JIDs could be retrieved.')
targeted_minions = data.get('Minions', [])
returns = data.get('Result', {})
if returns:
for minion in returns:
if display_progress:
__jid_event__.fire_event({'message': minion}, 'progress')
if u'return' in returns[minion]:
if returned:
ret[minion] = returns[minion].get(u'return')
else:
if returned:
ret[minion] = returns[minion].get('return')
if missing:
for minion_id in (x for x in targeted_minions if x not in returns):
ret[minion_id] = 'Minion did not return'
# We need to check to see if the 'out' key is present and use it to specify
# the correct outputter, so we get highstate output for highstate runs.
try:
# Check if the return data has an 'out' key. We'll use that as the
# outputter in the absence of one being passed on the CLI.
outputter = None
_ret = returns[next(iter(returns))]
if 'out' in _ret:
outputter = _ret['out']
elif 'outputter' in _ret.get('return', {}).get('return', {}):
outputter = _ret['return']['return']['outputter']
except (StopIteration, AttributeError):
pass
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def list_job(jid, ext_source=None, display_progress=False):
'''
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
.. code-block:: bash
salt-run jobs.list_job 20130916125524463507
salt-run jobs.list_job 20130916125524463507 --out=pprint
'''
ret = {'jid': jid}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner: {0}'.format(returner)},
'progress'
)
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret.update(_format_jid_instance(jid, job))
ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret['EndTime'] = endtime
return ret
def list_jobs(ext_source=None,
outputter=None,
search_metadata=None,
search_function=None,
search_target=None,
start_time=None,
end_time=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
If provided, specifies which external job cache to use.
**FILTER OPTIONS**
.. note::
If more than one of the below options are used, only jobs which match
*all* of the filters will be returned.
search_metadata
Specify a dictionary to match to the job's metadata. If any of the
key-value pairs in this dictionary match, the job will be returned.
Example:
.. code-block:: bash
salt-run jobs.list_jobs search_metadata='{"foo": "bar", "baz": "qux"}'
search_function
Can be passed as a string or a list. Returns jobs which match the
specified function. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*'
salt-run jobs.list_jobs search_function='["test.*", "pkg.install"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*,pkg.install'
search_target
Can be passed as a string or a list. Returns jobs which match the
specified minion name. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='*.mydomain.tld'
salt-run jobs.list_jobs search_target='["db*", "myminion"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='db*,myminion'
start_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started after this timestamp.
end_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started before this timestamp.
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs
salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{"bar": "foo"}'
salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
ret = mminion.returners['{0}.get_jids'.format(returner)]()
mret = {}
for item in ret:
_match = True
if search_metadata:
_match = False
if 'Metadata' in ret[item]:
if isinstance(search_metadata, dict):
for key in search_metadata:
if key in ret[item]['Metadata']:
if ret[item]['Metadata'][key] == search_metadata[key]:
_match = True
else:
log.info('The search_metadata parameter must be specified'
' as a dictionary. Ignoring.')
if search_target and _match:
_match = False
if 'Target' in ret[item]:
targets = ret[item]['Target']
if isinstance(targets, six.string_types):
targets = [targets]
for target in targets:
for key in salt.utils.args.split_input(search_target):
if fnmatch.fnmatch(target, key):
_match = True
if search_function and _match:
_match = False
if 'Function' in ret[item]:
for key in salt.utils.args.split_input(search_function):
if fnmatch.fnmatch(ret[item]['Function'], key):
_match = True
if start_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_start_time = dateutil_parser.parse(start_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time >= parsed_start_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping start_time '
'comparison.'
)
if end_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_end_time = dateutil_parser.parse(end_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time <= parsed_end_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping end_time '
'comparison.'
)
if _match:
mret[item] = ret[item]
if outputter:
return {'outputter': outputter, 'data': mret}
else:
return mret
def list_jobs_filter(count,
filter_find_job=True,
ext_source=None,
outputter=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs_filter 50
salt-run jobs.list_jobs_filter 100 filter_find_job=False
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
fun = '{0}.get_jids_filter'.format(returner)
if fun not in mminion.returners:
raise NotImplementedError(
'\'{0}\' returner function not implemented yet.'.format(fun)
)
ret = mminion.returners[fun](count, filter_find_job)
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def print_job(jid, ext_source=None):
'''
Print a specific job's detail given by it's jid, including the return data.
CLI Example:
.. code-block:: bash
salt-run jobs.print_job 20130916125524463507
'''
ret = {}
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
mminion = salt.minion.MasterMinion(__opts__)
try:
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret[jid] = _format_jid_instance(jid, job)
except TypeError:
ret[jid]['Result'] = (
'Requested returner {0} is not available. Jobs cannot be '
'retrieved. Check master log for details.'.format(returner)
)
return ret
ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret[jid]['EndTime'] = endtime
return ret
def exit_success(jid, ext_source=None):
'''
Check if a job has been executed and exit successfully
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.exit_success 20160520145827701627
'''
ret = dict()
data = list_job(
jid,
ext_source=ext_source
)
minions = data.get('Minions', [])
result = data.get('Result', {})
for minion in minions:
if minion in result and 'return' in result[minion]:
ret[minion] = True if result[minion]['return'] else False
else:
ret[minion] = False
for minion in result:
if 'return' in result[minion] and result[minion]['return']:
ret[minion] = True
return ret
def last_run(ext_source=None,
outputter=None,
metadata=None,
function=None,
target=None,
display_progress=False):
'''
.. versionadded:: 2015.8.0
List all detectable jobs and associated functions
CLI Example:
.. code-block:: bash
salt-run jobs.last_run
salt-run jobs.last_run target=nodename
salt-run jobs.last_run function='cmd.run'
salt-run jobs.last_run metadata="{'foo': 'bar'}"
'''
if metadata:
if not isinstance(metadata, dict):
log.info('The metadata parameter must be specified as a dictionary')
return False
_all_jobs = list_jobs(ext_source=ext_source,
outputter=outputter,
search_metadata=metadata,
search_function=function,
search_target=target,
display_progress=display_progress)
if _all_jobs:
last_job = sorted(_all_jobs)[-1]
return print_job(last_job, ext_source)
else:
return False
def _get_returner(returner_types):
'''
Helper to iterate over returner_types and pick the first one
'''
for returner in returner_types:
if returner and returner is not None:
return returner
def _format_job_instance(job):
'''
Helper to format a job instance
'''
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
# unlikely but safeguard from invalid returns
'Target': job.get('tgt', 'unknown-target'),
'Target-type': job.get('tgt_type', 'list'),
'User': job.get('user', 'root')}
if 'metadata' in job:
ret['Metadata'] = job.get('metadata', {})
else:
if 'kwargs' in job:
if 'metadata' in job['kwargs']:
ret['Metadata'] = job['kwargs'].get('metadata', {})
if 'Minions' in job:
ret['Minions'] = job['Minions']
return ret
def _format_jid_instance(jid, job):
'''
Helper to format jid instance
'''
ret = _format_job_instance(job)
ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})
return ret
def _walk_through(job_dir, display_progress=False):
'''
Walk through the job dir and return jobs
'''
serial = salt.payload.Serial(__opts__)
for top in os.listdir(job_dir):
t_path = os.path.join(job_dir, top)
for final in os.listdir(t_path):
load_path = os.path.join(t_path, final, '.load.p')
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
if not os.path.isfile(load_path):
continue
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
jid = job['jid']
if display_progress:
__jid_event__.fire_event(
{'message': 'Found JID {0}'.format(jid)},
'progress'
)
yield jid, job, t_path, final
|
saltstack/salt
|
salt/runners/jobs.py
|
lookup_jid
|
python
|
def lookup_jid(jid,
ext_source=None,
returned=True,
missing=False,
display_progress=False):
'''
Return the printout from a previously executed job
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
returned : True
If ``True``, include the minions that did return from the command.
.. versionadded:: 2015.8.0
missing : False
If ``True``, include the minions that did *not* return from the
command.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run jobs.lookup_jid 20130916125524463507
salt-run jobs.lookup_jid 20130916125524463507 --out=highstate
'''
ret = {}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
try:
data = list_job(
jid,
ext_source=ext_source,
display_progress=display_progress
)
except TypeError:
return ('Requested returner could not be loaded. '
'No JIDs could be retrieved.')
targeted_minions = data.get('Minions', [])
returns = data.get('Result', {})
if returns:
for minion in returns:
if display_progress:
__jid_event__.fire_event({'message': minion}, 'progress')
if u'return' in returns[minion]:
if returned:
ret[minion] = returns[minion].get(u'return')
else:
if returned:
ret[minion] = returns[minion].get('return')
if missing:
for minion_id in (x for x in targeted_minions if x not in returns):
ret[minion_id] = 'Minion did not return'
# We need to check to see if the 'out' key is present and use it to specify
# the correct outputter, so we get highstate output for highstate runs.
try:
# Check if the return data has an 'out' key. We'll use that as the
# outputter in the absence of one being passed on the CLI.
outputter = None
_ret = returns[next(iter(returns))]
if 'out' in _ret:
outputter = _ret['out']
elif 'outputter' in _ret.get('return', {}).get('return', {}):
outputter = _ret['return']['return']['outputter']
except (StopIteration, AttributeError):
pass
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
|
Return the printout from a previously executed job
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
returned : True
If ``True``, include the minions that did return from the command.
.. versionadded:: 2015.8.0
missing : False
If ``True``, include the minions that did *not* return from the
command.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run jobs.lookup_jid 20130916125524463507
salt-run jobs.lookup_jid 20130916125524463507 --out=highstate
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/jobs.py#L81-L168
|
[
"def _get_returner(returner_types):\n '''\n Helper to iterate over returner_types and pick the first one\n '''\n for returner in returner_types:\n if returner and returner is not None:\n return returner\n",
"def list_job(jid, ext_source=None, display_progress=False):\n '''\n List a specific job given by its jid\n\n ext_source\n If provided, specifies which external job cache to use.\n\n display_progress : False\n If ``True``, fire progress events.\n\n .. versionadded:: 2015.8.8\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run jobs.list_job 20130916125524463507\n salt-run jobs.list_job 20130916125524463507 --out=pprint\n '''\n ret = {'jid': jid}\n mminion = salt.minion.MasterMinion(__opts__)\n returner = _get_returner((\n __opts__['ext_job_cache'],\n ext_source,\n __opts__['master_job_cache']\n ))\n if display_progress:\n __jid_event__.fire_event(\n {'message': 'Querying returner: {0}'.format(returner)},\n 'progress'\n )\n\n job = mminion.returners['{0}.get_load'.format(returner)](jid)\n ret.update(_format_jid_instance(jid, job))\n ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)\n\n fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])\n if (__opts__.get('job_cache_store_endtime')\n and fstr in mminion.returners):\n endtime = mminion.returners[fstr](jid)\n if endtime:\n ret['EndTime'] = endtime\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
A convenience system to manage jobs, both active and already run
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import os
# Import salt libs
import salt.client
import salt.payload
import salt.utils.args
import salt.utils.files
import salt.utils.jid
import salt.minion
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.exceptions import SaltClientError
try:
import dateutil.parser as dateutil_parser
DATEUTIL_SUPPORT = True
except ImportError:
DATEUTIL_SUPPORT = False
log = logging.getLogger(__name__)
def active(display_progress=False):
'''
Return a report on all actively running jobs from a job id centric
perspective
CLI Example:
.. code-block:: bash
salt-run jobs.active
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
if display_progress:
__jid_event__.fire_event({
'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
}, 'progress')
for minion, data in six.iteritems(active_):
if display_progress:
__jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
if not isinstance(data, list):
continue
for job in data:
if not job['jid'] in ret:
ret[job['jid']] = _format_jid_instance(job['jid'], job)
ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
else:
ret[job['jid']]['Running'].append({minion: job['pid']})
mminion = salt.minion.MasterMinion(__opts__)
for jid in ret:
returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
if data:
for minion in data:
if minion not in ret[jid]['Returned']:
ret[jid]['Returned'].append(minion)
return ret
def list_job(jid, ext_source=None, display_progress=False):
'''
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
.. code-block:: bash
salt-run jobs.list_job 20130916125524463507
salt-run jobs.list_job 20130916125524463507 --out=pprint
'''
ret = {'jid': jid}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner: {0}'.format(returner)},
'progress'
)
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret.update(_format_jid_instance(jid, job))
ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret['EndTime'] = endtime
return ret
def list_jobs(ext_source=None,
outputter=None,
search_metadata=None,
search_function=None,
search_target=None,
start_time=None,
end_time=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
If provided, specifies which external job cache to use.
**FILTER OPTIONS**
.. note::
If more than one of the below options are used, only jobs which match
*all* of the filters will be returned.
search_metadata
Specify a dictionary to match to the job's metadata. If any of the
key-value pairs in this dictionary match, the job will be returned.
Example:
.. code-block:: bash
salt-run jobs.list_jobs search_metadata='{"foo": "bar", "baz": "qux"}'
search_function
Can be passed as a string or a list. Returns jobs which match the
specified function. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*'
salt-run jobs.list_jobs search_function='["test.*", "pkg.install"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*,pkg.install'
search_target
Can be passed as a string or a list. Returns jobs which match the
specified minion name. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='*.mydomain.tld'
salt-run jobs.list_jobs search_target='["db*", "myminion"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='db*,myminion'
start_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started after this timestamp.
end_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started before this timestamp.
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs
salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{"bar": "foo"}'
salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
ret = mminion.returners['{0}.get_jids'.format(returner)]()
mret = {}
for item in ret:
_match = True
if search_metadata:
_match = False
if 'Metadata' in ret[item]:
if isinstance(search_metadata, dict):
for key in search_metadata:
if key in ret[item]['Metadata']:
if ret[item]['Metadata'][key] == search_metadata[key]:
_match = True
else:
log.info('The search_metadata parameter must be specified'
' as a dictionary. Ignoring.')
if search_target and _match:
_match = False
if 'Target' in ret[item]:
targets = ret[item]['Target']
if isinstance(targets, six.string_types):
targets = [targets]
for target in targets:
for key in salt.utils.args.split_input(search_target):
if fnmatch.fnmatch(target, key):
_match = True
if search_function and _match:
_match = False
if 'Function' in ret[item]:
for key in salt.utils.args.split_input(search_function):
if fnmatch.fnmatch(ret[item]['Function'], key):
_match = True
if start_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_start_time = dateutil_parser.parse(start_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time >= parsed_start_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping start_time '
'comparison.'
)
if end_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_end_time = dateutil_parser.parse(end_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time <= parsed_end_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping end_time '
'comparison.'
)
if _match:
mret[item] = ret[item]
if outputter:
return {'outputter': outputter, 'data': mret}
else:
return mret
def list_jobs_filter(count,
filter_find_job=True,
ext_source=None,
outputter=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs_filter 50
salt-run jobs.list_jobs_filter 100 filter_find_job=False
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
fun = '{0}.get_jids_filter'.format(returner)
if fun not in mminion.returners:
raise NotImplementedError(
'\'{0}\' returner function not implemented yet.'.format(fun)
)
ret = mminion.returners[fun](count, filter_find_job)
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def print_job(jid, ext_source=None):
'''
Print a specific job's detail given by it's jid, including the return data.
CLI Example:
.. code-block:: bash
salt-run jobs.print_job 20130916125524463507
'''
ret = {}
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
mminion = salt.minion.MasterMinion(__opts__)
try:
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret[jid] = _format_jid_instance(jid, job)
except TypeError:
ret[jid]['Result'] = (
'Requested returner {0} is not available. Jobs cannot be '
'retrieved. Check master log for details.'.format(returner)
)
return ret
ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret[jid]['EndTime'] = endtime
return ret
def exit_success(jid, ext_source=None):
'''
Check if a job has been executed and exit successfully
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.exit_success 20160520145827701627
'''
ret = dict()
data = list_job(
jid,
ext_source=ext_source
)
minions = data.get('Minions', [])
result = data.get('Result', {})
for minion in minions:
if minion in result and 'return' in result[minion]:
ret[minion] = True if result[minion]['return'] else False
else:
ret[minion] = False
for minion in result:
if 'return' in result[minion] and result[minion]['return']:
ret[minion] = True
return ret
def last_run(ext_source=None,
outputter=None,
metadata=None,
function=None,
target=None,
display_progress=False):
'''
.. versionadded:: 2015.8.0
List all detectable jobs and associated functions
CLI Example:
.. code-block:: bash
salt-run jobs.last_run
salt-run jobs.last_run target=nodename
salt-run jobs.last_run function='cmd.run'
salt-run jobs.last_run metadata="{'foo': 'bar'}"
'''
if metadata:
if not isinstance(metadata, dict):
log.info('The metadata parameter must be specified as a dictionary')
return False
_all_jobs = list_jobs(ext_source=ext_source,
outputter=outputter,
search_metadata=metadata,
search_function=function,
search_target=target,
display_progress=display_progress)
if _all_jobs:
last_job = sorted(_all_jobs)[-1]
return print_job(last_job, ext_source)
else:
return False
def _get_returner(returner_types):
'''
Helper to iterate over returner_types and pick the first one
'''
for returner in returner_types:
if returner and returner is not None:
return returner
def _format_job_instance(job):
'''
Helper to format a job instance
'''
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
# unlikely but safeguard from invalid returns
'Target': job.get('tgt', 'unknown-target'),
'Target-type': job.get('tgt_type', 'list'),
'User': job.get('user', 'root')}
if 'metadata' in job:
ret['Metadata'] = job.get('metadata', {})
else:
if 'kwargs' in job:
if 'metadata' in job['kwargs']:
ret['Metadata'] = job['kwargs'].get('metadata', {})
if 'Minions' in job:
ret['Minions'] = job['Minions']
return ret
def _format_jid_instance(jid, job):
'''
Helper to format jid instance
'''
ret = _format_job_instance(job)
ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})
return ret
def _walk_through(job_dir, display_progress=False):
'''
Walk through the job dir and return jobs
'''
serial = salt.payload.Serial(__opts__)
for top in os.listdir(job_dir):
t_path = os.path.join(job_dir, top)
for final in os.listdir(t_path):
load_path = os.path.join(t_path, final, '.load.p')
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
if not os.path.isfile(load_path):
continue
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
jid = job['jid']
if display_progress:
__jid_event__.fire_event(
{'message': 'Found JID {0}'.format(jid)},
'progress'
)
yield jid, job, t_path, final
|
saltstack/salt
|
salt/runners/jobs.py
|
list_job
|
python
|
def list_job(jid, ext_source=None, display_progress=False):
'''
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
.. code-block:: bash
salt-run jobs.list_job 20130916125524463507
salt-run jobs.list_job 20130916125524463507 --out=pprint
'''
ret = {'jid': jid}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner: {0}'.format(returner)},
'progress'
)
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret.update(_format_jid_instance(jid, job))
ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret['EndTime'] = endtime
return ret
|
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
.. code-block:: bash
salt-run jobs.list_job 20130916125524463507
salt-run jobs.list_job 20130916125524463507 --out=pprint
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/jobs.py#L171-L214
|
[
"def _format_jid_instance(jid, job):\n '''\n Helper to format jid instance\n '''\n ret = _format_job_instance(job)\n ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})\n return ret\n",
"def _get_returner(returner_types):\n '''\n Helper to iterate over returner_types and pick the first one\n '''\n for returner in returner_types:\n if returner and returner is not None:\n return returner\n"
] |
# -*- coding: utf-8 -*-
'''
A convenience system to manage jobs, both active and already run
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import os
# Import salt libs
import salt.client
import salt.payload
import salt.utils.args
import salt.utils.files
import salt.utils.jid
import salt.minion
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.exceptions import SaltClientError
try:
import dateutil.parser as dateutil_parser
DATEUTIL_SUPPORT = True
except ImportError:
DATEUTIL_SUPPORT = False
log = logging.getLogger(__name__)
def active(display_progress=False):
'''
Return a report on all actively running jobs from a job id centric
perspective
CLI Example:
.. code-block:: bash
salt-run jobs.active
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
if display_progress:
__jid_event__.fire_event({
'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
}, 'progress')
for minion, data in six.iteritems(active_):
if display_progress:
__jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
if not isinstance(data, list):
continue
for job in data:
if not job['jid'] in ret:
ret[job['jid']] = _format_jid_instance(job['jid'], job)
ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
else:
ret[job['jid']]['Running'].append({minion: job['pid']})
mminion = salt.minion.MasterMinion(__opts__)
for jid in ret:
returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
if data:
for minion in data:
if minion not in ret[jid]['Returned']:
ret[jid]['Returned'].append(minion)
return ret
def lookup_jid(jid,
ext_source=None,
returned=True,
missing=False,
display_progress=False):
'''
Return the printout from a previously executed job
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
returned : True
If ``True``, include the minions that did return from the command.
.. versionadded:: 2015.8.0
missing : False
If ``True``, include the minions that did *not* return from the
command.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run jobs.lookup_jid 20130916125524463507
salt-run jobs.lookup_jid 20130916125524463507 --out=highstate
'''
ret = {}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
try:
data = list_job(
jid,
ext_source=ext_source,
display_progress=display_progress
)
except TypeError:
return ('Requested returner could not be loaded. '
'No JIDs could be retrieved.')
targeted_minions = data.get('Minions', [])
returns = data.get('Result', {})
if returns:
for minion in returns:
if display_progress:
__jid_event__.fire_event({'message': minion}, 'progress')
if u'return' in returns[minion]:
if returned:
ret[minion] = returns[minion].get(u'return')
else:
if returned:
ret[minion] = returns[minion].get('return')
if missing:
for minion_id in (x for x in targeted_minions if x not in returns):
ret[minion_id] = 'Minion did not return'
# We need to check to see if the 'out' key is present and use it to specify
# the correct outputter, so we get highstate output for highstate runs.
try:
# Check if the return data has an 'out' key. We'll use that as the
# outputter in the absence of one being passed on the CLI.
outputter = None
_ret = returns[next(iter(returns))]
if 'out' in _ret:
outputter = _ret['out']
elif 'outputter' in _ret.get('return', {}).get('return', {}):
outputter = _ret['return']['return']['outputter']
except (StopIteration, AttributeError):
pass
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def list_jobs(ext_source=None,
outputter=None,
search_metadata=None,
search_function=None,
search_target=None,
start_time=None,
end_time=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
If provided, specifies which external job cache to use.
**FILTER OPTIONS**
.. note::
If more than one of the below options are used, only jobs which match
*all* of the filters will be returned.
search_metadata
Specify a dictionary to match to the job's metadata. If any of the
key-value pairs in this dictionary match, the job will be returned.
Example:
.. code-block:: bash
salt-run jobs.list_jobs search_metadata='{"foo": "bar", "baz": "qux"}'
search_function
Can be passed as a string or a list. Returns jobs which match the
specified function. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*'
salt-run jobs.list_jobs search_function='["test.*", "pkg.install"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*,pkg.install'
search_target
Can be passed as a string or a list. Returns jobs which match the
specified minion name. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='*.mydomain.tld'
salt-run jobs.list_jobs search_target='["db*", "myminion"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='db*,myminion'
start_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started after this timestamp.
end_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started before this timestamp.
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs
salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{"bar": "foo"}'
salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
ret = mminion.returners['{0}.get_jids'.format(returner)]()
mret = {}
for item in ret:
_match = True
if search_metadata:
_match = False
if 'Metadata' in ret[item]:
if isinstance(search_metadata, dict):
for key in search_metadata:
if key in ret[item]['Metadata']:
if ret[item]['Metadata'][key] == search_metadata[key]:
_match = True
else:
log.info('The search_metadata parameter must be specified'
' as a dictionary. Ignoring.')
if search_target and _match:
_match = False
if 'Target' in ret[item]:
targets = ret[item]['Target']
if isinstance(targets, six.string_types):
targets = [targets]
for target in targets:
for key in salt.utils.args.split_input(search_target):
if fnmatch.fnmatch(target, key):
_match = True
if search_function and _match:
_match = False
if 'Function' in ret[item]:
for key in salt.utils.args.split_input(search_function):
if fnmatch.fnmatch(ret[item]['Function'], key):
_match = True
if start_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_start_time = dateutil_parser.parse(start_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time >= parsed_start_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping start_time '
'comparison.'
)
if end_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_end_time = dateutil_parser.parse(end_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time <= parsed_end_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping end_time '
'comparison.'
)
if _match:
mret[item] = ret[item]
if outputter:
return {'outputter': outputter, 'data': mret}
else:
return mret
def list_jobs_filter(count,
filter_find_job=True,
ext_source=None,
outputter=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs_filter 50
salt-run jobs.list_jobs_filter 100 filter_find_job=False
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
fun = '{0}.get_jids_filter'.format(returner)
if fun not in mminion.returners:
raise NotImplementedError(
'\'{0}\' returner function not implemented yet.'.format(fun)
)
ret = mminion.returners[fun](count, filter_find_job)
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def print_job(jid, ext_source=None):
'''
Print a specific job's detail given by it's jid, including the return data.
CLI Example:
.. code-block:: bash
salt-run jobs.print_job 20130916125524463507
'''
ret = {}
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
mminion = salt.minion.MasterMinion(__opts__)
try:
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret[jid] = _format_jid_instance(jid, job)
except TypeError:
ret[jid]['Result'] = (
'Requested returner {0} is not available. Jobs cannot be '
'retrieved. Check master log for details.'.format(returner)
)
return ret
ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret[jid]['EndTime'] = endtime
return ret
def exit_success(jid, ext_source=None):
'''
Check if a job has been executed and exit successfully
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.exit_success 20160520145827701627
'''
ret = dict()
data = list_job(
jid,
ext_source=ext_source
)
minions = data.get('Minions', [])
result = data.get('Result', {})
for minion in minions:
if minion in result and 'return' in result[minion]:
ret[minion] = True if result[minion]['return'] else False
else:
ret[minion] = False
for minion in result:
if 'return' in result[minion] and result[minion]['return']:
ret[minion] = True
return ret
def last_run(ext_source=None,
outputter=None,
metadata=None,
function=None,
target=None,
display_progress=False):
'''
.. versionadded:: 2015.8.0
List all detectable jobs and associated functions
CLI Example:
.. code-block:: bash
salt-run jobs.last_run
salt-run jobs.last_run target=nodename
salt-run jobs.last_run function='cmd.run'
salt-run jobs.last_run metadata="{'foo': 'bar'}"
'''
if metadata:
if not isinstance(metadata, dict):
log.info('The metadata parameter must be specified as a dictionary')
return False
_all_jobs = list_jobs(ext_source=ext_source,
outputter=outputter,
search_metadata=metadata,
search_function=function,
search_target=target,
display_progress=display_progress)
if _all_jobs:
last_job = sorted(_all_jobs)[-1]
return print_job(last_job, ext_source)
else:
return False
def _get_returner(returner_types):
'''
Helper to iterate over returner_types and pick the first one
'''
for returner in returner_types:
if returner and returner is not None:
return returner
def _format_job_instance(job):
'''
Helper to format a job instance
'''
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
# unlikely but safeguard from invalid returns
'Target': job.get('tgt', 'unknown-target'),
'Target-type': job.get('tgt_type', 'list'),
'User': job.get('user', 'root')}
if 'metadata' in job:
ret['Metadata'] = job.get('metadata', {})
else:
if 'kwargs' in job:
if 'metadata' in job['kwargs']:
ret['Metadata'] = job['kwargs'].get('metadata', {})
if 'Minions' in job:
ret['Minions'] = job['Minions']
return ret
def _format_jid_instance(jid, job):
'''
Helper to format jid instance
'''
ret = _format_job_instance(job)
ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})
return ret
def _walk_through(job_dir, display_progress=False):
'''
Walk through the job dir and return jobs
'''
serial = salt.payload.Serial(__opts__)
for top in os.listdir(job_dir):
t_path = os.path.join(job_dir, top)
for final in os.listdir(t_path):
load_path = os.path.join(t_path, final, '.load.p')
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
if not os.path.isfile(load_path):
continue
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
jid = job['jid']
if display_progress:
__jid_event__.fire_event(
{'message': 'Found JID {0}'.format(jid)},
'progress'
)
yield jid, job, t_path, final
|
saltstack/salt
|
salt/runners/jobs.py
|
list_jobs
|
python
|
def list_jobs(ext_source=None,
outputter=None,
search_metadata=None,
search_function=None,
search_target=None,
start_time=None,
end_time=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
If provided, specifies which external job cache to use.
**FILTER OPTIONS**
.. note::
If more than one of the below options are used, only jobs which match
*all* of the filters will be returned.
search_metadata
Specify a dictionary to match to the job's metadata. If any of the
key-value pairs in this dictionary match, the job will be returned.
Example:
.. code-block:: bash
salt-run jobs.list_jobs search_metadata='{"foo": "bar", "baz": "qux"}'
search_function
Can be passed as a string or a list. Returns jobs which match the
specified function. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*'
salt-run jobs.list_jobs search_function='["test.*", "pkg.install"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*,pkg.install'
search_target
Can be passed as a string or a list. Returns jobs which match the
specified minion name. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='*.mydomain.tld'
salt-run jobs.list_jobs search_target='["db*", "myminion"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='db*,myminion'
start_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started after this timestamp.
end_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started before this timestamp.
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs
salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{"bar": "foo"}'
salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
ret = mminion.returners['{0}.get_jids'.format(returner)]()
mret = {}
for item in ret:
_match = True
if search_metadata:
_match = False
if 'Metadata' in ret[item]:
if isinstance(search_metadata, dict):
for key in search_metadata:
if key in ret[item]['Metadata']:
if ret[item]['Metadata'][key] == search_metadata[key]:
_match = True
else:
log.info('The search_metadata parameter must be specified'
' as a dictionary. Ignoring.')
if search_target and _match:
_match = False
if 'Target' in ret[item]:
targets = ret[item]['Target']
if isinstance(targets, six.string_types):
targets = [targets]
for target in targets:
for key in salt.utils.args.split_input(search_target):
if fnmatch.fnmatch(target, key):
_match = True
if search_function and _match:
_match = False
if 'Function' in ret[item]:
for key in salt.utils.args.split_input(search_function):
if fnmatch.fnmatch(ret[item]['Function'], key):
_match = True
if start_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_start_time = dateutil_parser.parse(start_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time >= parsed_start_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping start_time '
'comparison.'
)
if end_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_end_time = dateutil_parser.parse(end_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time <= parsed_end_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping end_time '
'comparison.'
)
if _match:
mret[item] = ret[item]
if outputter:
return {'outputter': outputter, 'data': mret}
else:
return mret
|
List all detectable jobs and associated functions
ext_source
If provided, specifies which external job cache to use.
**FILTER OPTIONS**
.. note::
If more than one of the below options are used, only jobs which match
*all* of the filters will be returned.
search_metadata
Specify a dictionary to match to the job's metadata. If any of the
key-value pairs in this dictionary match, the job will be returned.
Example:
.. code-block:: bash
salt-run jobs.list_jobs search_metadata='{"foo": "bar", "baz": "qux"}'
search_function
Can be passed as a string or a list. Returns jobs which match the
specified function. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*'
salt-run jobs.list_jobs search_function='["test.*", "pkg.install"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*,pkg.install'
search_target
Can be passed as a string or a list. Returns jobs which match the
specified minion name. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='*.mydomain.tld'
salt-run jobs.list_jobs search_target='["db*", "myminion"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='db*,myminion'
start_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started after this timestamp.
end_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started before this timestamp.
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs
salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{"bar": "foo"}'
salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/jobs.py#L217-L379
|
[
"def split_input(val, mapper=None):\n '''\n Take an input value and split it into a list, returning the resulting list\n '''\n if mapper is None:\n mapper = lambda x: x\n if isinstance(val, list):\n return list(map(mapper, val))\n try:\n return list(map(mapper, [x.strip() for x in val.split(',')]))\n except AttributeError:\n return list(map(mapper, [x.strip() for x in six.text_type(val).split(',')]))\n",
"def _get_returner(returner_types):\n '''\n Helper to iterate over returner_types and pick the first one\n '''\n for returner in returner_types:\n if returner and returner is not None:\n return returner\n"
] |
# -*- coding: utf-8 -*-
'''
A convenience system to manage jobs, both active and already run
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import os
# Import salt libs
import salt.client
import salt.payload
import salt.utils.args
import salt.utils.files
import salt.utils.jid
import salt.minion
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.exceptions import SaltClientError
try:
import dateutil.parser as dateutil_parser
DATEUTIL_SUPPORT = True
except ImportError:
DATEUTIL_SUPPORT = False
log = logging.getLogger(__name__)
def active(display_progress=False):
'''
Return a report on all actively running jobs from a job id centric
perspective
CLI Example:
.. code-block:: bash
salt-run jobs.active
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
if display_progress:
__jid_event__.fire_event({
'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
}, 'progress')
for minion, data in six.iteritems(active_):
if display_progress:
__jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
if not isinstance(data, list):
continue
for job in data:
if not job['jid'] in ret:
ret[job['jid']] = _format_jid_instance(job['jid'], job)
ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
else:
ret[job['jid']]['Running'].append({minion: job['pid']})
mminion = salt.minion.MasterMinion(__opts__)
for jid in ret:
returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
if data:
for minion in data:
if minion not in ret[jid]['Returned']:
ret[jid]['Returned'].append(minion)
return ret
def lookup_jid(jid,
ext_source=None,
returned=True,
missing=False,
display_progress=False):
'''
Return the printout from a previously executed job
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
returned : True
If ``True``, include the minions that did return from the command.
.. versionadded:: 2015.8.0
missing : False
If ``True``, include the minions that did *not* return from the
command.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run jobs.lookup_jid 20130916125524463507
salt-run jobs.lookup_jid 20130916125524463507 --out=highstate
'''
ret = {}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
try:
data = list_job(
jid,
ext_source=ext_source,
display_progress=display_progress
)
except TypeError:
return ('Requested returner could not be loaded. '
'No JIDs could be retrieved.')
targeted_minions = data.get('Minions', [])
returns = data.get('Result', {})
if returns:
for minion in returns:
if display_progress:
__jid_event__.fire_event({'message': minion}, 'progress')
if u'return' in returns[minion]:
if returned:
ret[minion] = returns[minion].get(u'return')
else:
if returned:
ret[minion] = returns[minion].get('return')
if missing:
for minion_id in (x for x in targeted_minions if x not in returns):
ret[minion_id] = 'Minion did not return'
# We need to check to see if the 'out' key is present and use it to specify
# the correct outputter, so we get highstate output for highstate runs.
try:
# Check if the return data has an 'out' key. We'll use that as the
# outputter in the absence of one being passed on the CLI.
outputter = None
_ret = returns[next(iter(returns))]
if 'out' in _ret:
outputter = _ret['out']
elif 'outputter' in _ret.get('return', {}).get('return', {}):
outputter = _ret['return']['return']['outputter']
except (StopIteration, AttributeError):
pass
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def list_job(jid, ext_source=None, display_progress=False):
'''
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
.. code-block:: bash
salt-run jobs.list_job 20130916125524463507
salt-run jobs.list_job 20130916125524463507 --out=pprint
'''
ret = {'jid': jid}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner: {0}'.format(returner)},
'progress'
)
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret.update(_format_jid_instance(jid, job))
ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret['EndTime'] = endtime
return ret
def list_jobs_filter(count,
filter_find_job=True,
ext_source=None,
outputter=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs_filter 50
salt-run jobs.list_jobs_filter 100 filter_find_job=False
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
fun = '{0}.get_jids_filter'.format(returner)
if fun not in mminion.returners:
raise NotImplementedError(
'\'{0}\' returner function not implemented yet.'.format(fun)
)
ret = mminion.returners[fun](count, filter_find_job)
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def print_job(jid, ext_source=None):
'''
Print a specific job's detail given by it's jid, including the return data.
CLI Example:
.. code-block:: bash
salt-run jobs.print_job 20130916125524463507
'''
ret = {}
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
mminion = salt.minion.MasterMinion(__opts__)
try:
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret[jid] = _format_jid_instance(jid, job)
except TypeError:
ret[jid]['Result'] = (
'Requested returner {0} is not available. Jobs cannot be '
'retrieved. Check master log for details.'.format(returner)
)
return ret
ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret[jid]['EndTime'] = endtime
return ret
def exit_success(jid, ext_source=None):
'''
Check if a job has been executed and exit successfully
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.exit_success 20160520145827701627
'''
ret = dict()
data = list_job(
jid,
ext_source=ext_source
)
minions = data.get('Minions', [])
result = data.get('Result', {})
for minion in minions:
if minion in result and 'return' in result[minion]:
ret[minion] = True if result[minion]['return'] else False
else:
ret[minion] = False
for minion in result:
if 'return' in result[minion] and result[minion]['return']:
ret[minion] = True
return ret
def last_run(ext_source=None,
outputter=None,
metadata=None,
function=None,
target=None,
display_progress=False):
'''
.. versionadded:: 2015.8.0
List all detectable jobs and associated functions
CLI Example:
.. code-block:: bash
salt-run jobs.last_run
salt-run jobs.last_run target=nodename
salt-run jobs.last_run function='cmd.run'
salt-run jobs.last_run metadata="{'foo': 'bar'}"
'''
if metadata:
if not isinstance(metadata, dict):
log.info('The metadata parameter must be specified as a dictionary')
return False
_all_jobs = list_jobs(ext_source=ext_source,
outputter=outputter,
search_metadata=metadata,
search_function=function,
search_target=target,
display_progress=display_progress)
if _all_jobs:
last_job = sorted(_all_jobs)[-1]
return print_job(last_job, ext_source)
else:
return False
def _get_returner(returner_types):
'''
Helper to iterate over returner_types and pick the first one
'''
for returner in returner_types:
if returner and returner is not None:
return returner
def _format_job_instance(job):
'''
Helper to format a job instance
'''
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
# unlikely but safeguard from invalid returns
'Target': job.get('tgt', 'unknown-target'),
'Target-type': job.get('tgt_type', 'list'),
'User': job.get('user', 'root')}
if 'metadata' in job:
ret['Metadata'] = job.get('metadata', {})
else:
if 'kwargs' in job:
if 'metadata' in job['kwargs']:
ret['Metadata'] = job['kwargs'].get('metadata', {})
if 'Minions' in job:
ret['Minions'] = job['Minions']
return ret
def _format_jid_instance(jid, job):
'''
Helper to format jid instance
'''
ret = _format_job_instance(job)
ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})
return ret
def _walk_through(job_dir, display_progress=False):
'''
Walk through the job dir and return jobs
'''
serial = salt.payload.Serial(__opts__)
for top in os.listdir(job_dir):
t_path = os.path.join(job_dir, top)
for final in os.listdir(t_path):
load_path = os.path.join(t_path, final, '.load.p')
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
if not os.path.isfile(load_path):
continue
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
jid = job['jid']
if display_progress:
__jid_event__.fire_event(
{'message': 'Found JID {0}'.format(jid)},
'progress'
)
yield jid, job, t_path, final
|
saltstack/salt
|
salt/runners/jobs.py
|
list_jobs_filter
|
python
|
def list_jobs_filter(count,
filter_find_job=True,
ext_source=None,
outputter=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs_filter 50
salt-run jobs.list_jobs_filter 100 filter_find_job=False
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
fun = '{0}.get_jids_filter'.format(returner)
if fun not in mminion.returners:
raise NotImplementedError(
'\'{0}\' returner function not implemented yet.'.format(fun)
)
ret = mminion.returners[fun](count, filter_find_job)
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
|
List all detectable jobs and associated functions
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs_filter 50
salt-run jobs.list_jobs_filter 100 filter_find_job=False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/jobs.py#L382-L423
|
[
"def _get_returner(returner_types):\n '''\n Helper to iterate over returner_types and pick the first one\n '''\n for returner in returner_types:\n if returner and returner is not None:\n return returner\n"
] |
# -*- coding: utf-8 -*-
'''
A convenience system to manage jobs, both active and already run
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import os
# Import salt libs
import salt.client
import salt.payload
import salt.utils.args
import salt.utils.files
import salt.utils.jid
import salt.minion
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.exceptions import SaltClientError
try:
import dateutil.parser as dateutil_parser
DATEUTIL_SUPPORT = True
except ImportError:
DATEUTIL_SUPPORT = False
log = logging.getLogger(__name__)
def active(display_progress=False):
'''
Return a report on all actively running jobs from a job id centric
perspective
CLI Example:
.. code-block:: bash
salt-run jobs.active
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
if display_progress:
__jid_event__.fire_event({
'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
}, 'progress')
for minion, data in six.iteritems(active_):
if display_progress:
__jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
if not isinstance(data, list):
continue
for job in data:
if not job['jid'] in ret:
ret[job['jid']] = _format_jid_instance(job['jid'], job)
ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
else:
ret[job['jid']]['Running'].append({minion: job['pid']})
mminion = salt.minion.MasterMinion(__opts__)
for jid in ret:
returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
if data:
for minion in data:
if minion not in ret[jid]['Returned']:
ret[jid]['Returned'].append(minion)
return ret
def lookup_jid(jid,
ext_source=None,
returned=True,
missing=False,
display_progress=False):
'''
Return the printout from a previously executed job
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
returned : True
If ``True``, include the minions that did return from the command.
.. versionadded:: 2015.8.0
missing : False
If ``True``, include the minions that did *not* return from the
command.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run jobs.lookup_jid 20130916125524463507
salt-run jobs.lookup_jid 20130916125524463507 --out=highstate
'''
ret = {}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
try:
data = list_job(
jid,
ext_source=ext_source,
display_progress=display_progress
)
except TypeError:
return ('Requested returner could not be loaded. '
'No JIDs could be retrieved.')
targeted_minions = data.get('Minions', [])
returns = data.get('Result', {})
if returns:
for minion in returns:
if display_progress:
__jid_event__.fire_event({'message': minion}, 'progress')
if u'return' in returns[minion]:
if returned:
ret[minion] = returns[minion].get(u'return')
else:
if returned:
ret[minion] = returns[minion].get('return')
if missing:
for minion_id in (x for x in targeted_minions if x not in returns):
ret[minion_id] = 'Minion did not return'
# We need to check to see if the 'out' key is present and use it to specify
# the correct outputter, so we get highstate output for highstate runs.
try:
# Check if the return data has an 'out' key. We'll use that as the
# outputter in the absence of one being passed on the CLI.
outputter = None
_ret = returns[next(iter(returns))]
if 'out' in _ret:
outputter = _ret['out']
elif 'outputter' in _ret.get('return', {}).get('return', {}):
outputter = _ret['return']['return']['outputter']
except (StopIteration, AttributeError):
pass
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def list_job(jid, ext_source=None, display_progress=False):
'''
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
.. code-block:: bash
salt-run jobs.list_job 20130916125524463507
salt-run jobs.list_job 20130916125524463507 --out=pprint
'''
ret = {'jid': jid}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner: {0}'.format(returner)},
'progress'
)
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret.update(_format_jid_instance(jid, job))
ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret['EndTime'] = endtime
return ret
def list_jobs(ext_source=None,
outputter=None,
search_metadata=None,
search_function=None,
search_target=None,
start_time=None,
end_time=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
If provided, specifies which external job cache to use.
**FILTER OPTIONS**
.. note::
If more than one of the below options are used, only jobs which match
*all* of the filters will be returned.
search_metadata
Specify a dictionary to match to the job's metadata. If any of the
key-value pairs in this dictionary match, the job will be returned.
Example:
.. code-block:: bash
salt-run jobs.list_jobs search_metadata='{"foo": "bar", "baz": "qux"}'
search_function
Can be passed as a string or a list. Returns jobs which match the
specified function. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*'
salt-run jobs.list_jobs search_function='["test.*", "pkg.install"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*,pkg.install'
search_target
Can be passed as a string or a list. Returns jobs which match the
specified minion name. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='*.mydomain.tld'
salt-run jobs.list_jobs search_target='["db*", "myminion"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='db*,myminion'
start_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started after this timestamp.
end_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started before this timestamp.
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs
salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{"bar": "foo"}'
salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
ret = mminion.returners['{0}.get_jids'.format(returner)]()
mret = {}
for item in ret:
_match = True
if search_metadata:
_match = False
if 'Metadata' in ret[item]:
if isinstance(search_metadata, dict):
for key in search_metadata:
if key in ret[item]['Metadata']:
if ret[item]['Metadata'][key] == search_metadata[key]:
_match = True
else:
log.info('The search_metadata parameter must be specified'
' as a dictionary. Ignoring.')
if search_target and _match:
_match = False
if 'Target' in ret[item]:
targets = ret[item]['Target']
if isinstance(targets, six.string_types):
targets = [targets]
for target in targets:
for key in salt.utils.args.split_input(search_target):
if fnmatch.fnmatch(target, key):
_match = True
if search_function and _match:
_match = False
if 'Function' in ret[item]:
for key in salt.utils.args.split_input(search_function):
if fnmatch.fnmatch(ret[item]['Function'], key):
_match = True
if start_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_start_time = dateutil_parser.parse(start_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time >= parsed_start_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping start_time '
'comparison.'
)
if end_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_end_time = dateutil_parser.parse(end_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time <= parsed_end_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping end_time '
'comparison.'
)
if _match:
mret[item] = ret[item]
if outputter:
return {'outputter': outputter, 'data': mret}
else:
return mret
def print_job(jid, ext_source=None):
'''
Print a specific job's detail given by it's jid, including the return data.
CLI Example:
.. code-block:: bash
salt-run jobs.print_job 20130916125524463507
'''
ret = {}
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
mminion = salt.minion.MasterMinion(__opts__)
try:
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret[jid] = _format_jid_instance(jid, job)
except TypeError:
ret[jid]['Result'] = (
'Requested returner {0} is not available. Jobs cannot be '
'retrieved. Check master log for details.'.format(returner)
)
return ret
ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret[jid]['EndTime'] = endtime
return ret
def exit_success(jid, ext_source=None):
'''
Check if a job has been executed and exit successfully
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.exit_success 20160520145827701627
'''
ret = dict()
data = list_job(
jid,
ext_source=ext_source
)
minions = data.get('Minions', [])
result = data.get('Result', {})
for minion in minions:
if minion in result and 'return' in result[minion]:
ret[minion] = True if result[minion]['return'] else False
else:
ret[minion] = False
for minion in result:
if 'return' in result[minion] and result[minion]['return']:
ret[minion] = True
return ret
def last_run(ext_source=None,
outputter=None,
metadata=None,
function=None,
target=None,
display_progress=False):
'''
.. versionadded:: 2015.8.0
List all detectable jobs and associated functions
CLI Example:
.. code-block:: bash
salt-run jobs.last_run
salt-run jobs.last_run target=nodename
salt-run jobs.last_run function='cmd.run'
salt-run jobs.last_run metadata="{'foo': 'bar'}"
'''
if metadata:
if not isinstance(metadata, dict):
log.info('The metadata parameter must be specified as a dictionary')
return False
_all_jobs = list_jobs(ext_source=ext_source,
outputter=outputter,
search_metadata=metadata,
search_function=function,
search_target=target,
display_progress=display_progress)
if _all_jobs:
last_job = sorted(_all_jobs)[-1]
return print_job(last_job, ext_source)
else:
return False
def _get_returner(returner_types):
'''
Helper to iterate over returner_types and pick the first one
'''
for returner in returner_types:
if returner and returner is not None:
return returner
def _format_job_instance(job):
'''
Helper to format a job instance
'''
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
# unlikely but safeguard from invalid returns
'Target': job.get('tgt', 'unknown-target'),
'Target-type': job.get('tgt_type', 'list'),
'User': job.get('user', 'root')}
if 'metadata' in job:
ret['Metadata'] = job.get('metadata', {})
else:
if 'kwargs' in job:
if 'metadata' in job['kwargs']:
ret['Metadata'] = job['kwargs'].get('metadata', {})
if 'Minions' in job:
ret['Minions'] = job['Minions']
return ret
def _format_jid_instance(jid, job):
'''
Helper to format jid instance
'''
ret = _format_job_instance(job)
ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})
return ret
def _walk_through(job_dir, display_progress=False):
'''
Walk through the job dir and return jobs
'''
serial = salt.payload.Serial(__opts__)
for top in os.listdir(job_dir):
t_path = os.path.join(job_dir, top)
for final in os.listdir(t_path):
load_path = os.path.join(t_path, final, '.load.p')
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
if not os.path.isfile(load_path):
continue
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
jid = job['jid']
if display_progress:
__jid_event__.fire_event(
{'message': 'Found JID {0}'.format(jid)},
'progress'
)
yield jid, job, t_path, final
|
saltstack/salt
|
salt/runners/jobs.py
|
print_job
|
python
|
def print_job(jid, ext_source=None):
'''
Print a specific job's detail given by it's jid, including the return data.
CLI Example:
.. code-block:: bash
salt-run jobs.print_job 20130916125524463507
'''
ret = {}
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
mminion = salt.minion.MasterMinion(__opts__)
try:
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret[jid] = _format_jid_instance(jid, job)
except TypeError:
ret[jid]['Result'] = (
'Requested returner {0} is not available. Jobs cannot be '
'retrieved. Check master log for details.'.format(returner)
)
return ret
ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret[jid]['EndTime'] = endtime
return ret
|
Print a specific job's detail given by it's jid, including the return data.
CLI Example:
.. code-block:: bash
salt-run jobs.print_job 20130916125524463507
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/jobs.py#L426-L463
|
[
"def _format_jid_instance(jid, job):\n '''\n Helper to format jid instance\n '''\n ret = _format_job_instance(job)\n ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})\n return ret\n",
"def _get_returner(returner_types):\n '''\n Helper to iterate over returner_types and pick the first one\n '''\n for returner in returner_types:\n if returner and returner is not None:\n return returner\n"
] |
# -*- coding: utf-8 -*-
'''
A convenience system to manage jobs, both active and already run
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import os
# Import salt libs
import salt.client
import salt.payload
import salt.utils.args
import salt.utils.files
import salt.utils.jid
import salt.minion
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.exceptions import SaltClientError
try:
import dateutil.parser as dateutil_parser
DATEUTIL_SUPPORT = True
except ImportError:
DATEUTIL_SUPPORT = False
log = logging.getLogger(__name__)
def active(display_progress=False):
'''
Return a report on all actively running jobs from a job id centric
perspective
CLI Example:
.. code-block:: bash
salt-run jobs.active
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
if display_progress:
__jid_event__.fire_event({
'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
}, 'progress')
for minion, data in six.iteritems(active_):
if display_progress:
__jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
if not isinstance(data, list):
continue
for job in data:
if not job['jid'] in ret:
ret[job['jid']] = _format_jid_instance(job['jid'], job)
ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
else:
ret[job['jid']]['Running'].append({minion: job['pid']})
mminion = salt.minion.MasterMinion(__opts__)
for jid in ret:
returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
if data:
for minion in data:
if minion not in ret[jid]['Returned']:
ret[jid]['Returned'].append(minion)
return ret
def lookup_jid(jid,
ext_source=None,
returned=True,
missing=False,
display_progress=False):
'''
Return the printout from a previously executed job
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
returned : True
If ``True``, include the minions that did return from the command.
.. versionadded:: 2015.8.0
missing : False
If ``True``, include the minions that did *not* return from the
command.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run jobs.lookup_jid 20130916125524463507
salt-run jobs.lookup_jid 20130916125524463507 --out=highstate
'''
ret = {}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
try:
data = list_job(
jid,
ext_source=ext_source,
display_progress=display_progress
)
except TypeError:
return ('Requested returner could not be loaded. '
'No JIDs could be retrieved.')
targeted_minions = data.get('Minions', [])
returns = data.get('Result', {})
if returns:
for minion in returns:
if display_progress:
__jid_event__.fire_event({'message': minion}, 'progress')
if u'return' in returns[minion]:
if returned:
ret[minion] = returns[minion].get(u'return')
else:
if returned:
ret[minion] = returns[minion].get('return')
if missing:
for minion_id in (x for x in targeted_minions if x not in returns):
ret[minion_id] = 'Minion did not return'
# We need to check to see if the 'out' key is present and use it to specify
# the correct outputter, so we get highstate output for highstate runs.
try:
# Check if the return data has an 'out' key. We'll use that as the
# outputter in the absence of one being passed on the CLI.
outputter = None
_ret = returns[next(iter(returns))]
if 'out' in _ret:
outputter = _ret['out']
elif 'outputter' in _ret.get('return', {}).get('return', {}):
outputter = _ret['return']['return']['outputter']
except (StopIteration, AttributeError):
pass
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def list_job(jid, ext_source=None, display_progress=False):
'''
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
.. code-block:: bash
salt-run jobs.list_job 20130916125524463507
salt-run jobs.list_job 20130916125524463507 --out=pprint
'''
ret = {'jid': jid}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner: {0}'.format(returner)},
'progress'
)
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret.update(_format_jid_instance(jid, job))
ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret['EndTime'] = endtime
return ret
def list_jobs(ext_source=None,
outputter=None,
search_metadata=None,
search_function=None,
search_target=None,
start_time=None,
end_time=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
If provided, specifies which external job cache to use.
**FILTER OPTIONS**
.. note::
If more than one of the below options are used, only jobs which match
*all* of the filters will be returned.
search_metadata
Specify a dictionary to match to the job's metadata. If any of the
key-value pairs in this dictionary match, the job will be returned.
Example:
.. code-block:: bash
salt-run jobs.list_jobs search_metadata='{"foo": "bar", "baz": "qux"}'
search_function
Can be passed as a string or a list. Returns jobs which match the
specified function. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*'
salt-run jobs.list_jobs search_function='["test.*", "pkg.install"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*,pkg.install'
search_target
Can be passed as a string or a list. Returns jobs which match the
specified minion name. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='*.mydomain.tld'
salt-run jobs.list_jobs search_target='["db*", "myminion"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='db*,myminion'
start_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started after this timestamp.
end_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started before this timestamp.
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs
salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{"bar": "foo"}'
salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
ret = mminion.returners['{0}.get_jids'.format(returner)]()
mret = {}
for item in ret:
_match = True
if search_metadata:
_match = False
if 'Metadata' in ret[item]:
if isinstance(search_metadata, dict):
for key in search_metadata:
if key in ret[item]['Metadata']:
if ret[item]['Metadata'][key] == search_metadata[key]:
_match = True
else:
log.info('The search_metadata parameter must be specified'
' as a dictionary. Ignoring.')
if search_target and _match:
_match = False
if 'Target' in ret[item]:
targets = ret[item]['Target']
if isinstance(targets, six.string_types):
targets = [targets]
for target in targets:
for key in salt.utils.args.split_input(search_target):
if fnmatch.fnmatch(target, key):
_match = True
if search_function and _match:
_match = False
if 'Function' in ret[item]:
for key in salt.utils.args.split_input(search_function):
if fnmatch.fnmatch(ret[item]['Function'], key):
_match = True
if start_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_start_time = dateutil_parser.parse(start_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time >= parsed_start_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping start_time '
'comparison.'
)
if end_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_end_time = dateutil_parser.parse(end_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time <= parsed_end_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping end_time '
'comparison.'
)
if _match:
mret[item] = ret[item]
if outputter:
return {'outputter': outputter, 'data': mret}
else:
return mret
def list_jobs_filter(count,
filter_find_job=True,
ext_source=None,
outputter=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs_filter 50
salt-run jobs.list_jobs_filter 100 filter_find_job=False
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
fun = '{0}.get_jids_filter'.format(returner)
if fun not in mminion.returners:
raise NotImplementedError(
'\'{0}\' returner function not implemented yet.'.format(fun)
)
ret = mminion.returners[fun](count, filter_find_job)
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def exit_success(jid, ext_source=None):
'''
Check if a job has been executed and exit successfully
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.exit_success 20160520145827701627
'''
ret = dict()
data = list_job(
jid,
ext_source=ext_source
)
minions = data.get('Minions', [])
result = data.get('Result', {})
for minion in minions:
if minion in result and 'return' in result[minion]:
ret[minion] = True if result[minion]['return'] else False
else:
ret[minion] = False
for minion in result:
if 'return' in result[minion] and result[minion]['return']:
ret[minion] = True
return ret
def last_run(ext_source=None,
outputter=None,
metadata=None,
function=None,
target=None,
display_progress=False):
'''
.. versionadded:: 2015.8.0
List all detectable jobs and associated functions
CLI Example:
.. code-block:: bash
salt-run jobs.last_run
salt-run jobs.last_run target=nodename
salt-run jobs.last_run function='cmd.run'
salt-run jobs.last_run metadata="{'foo': 'bar'}"
'''
if metadata:
if not isinstance(metadata, dict):
log.info('The metadata parameter must be specified as a dictionary')
return False
_all_jobs = list_jobs(ext_source=ext_source,
outputter=outputter,
search_metadata=metadata,
search_function=function,
search_target=target,
display_progress=display_progress)
if _all_jobs:
last_job = sorted(_all_jobs)[-1]
return print_job(last_job, ext_source)
else:
return False
def _get_returner(returner_types):
'''
Helper to iterate over returner_types and pick the first one
'''
for returner in returner_types:
if returner and returner is not None:
return returner
def _format_job_instance(job):
'''
Helper to format a job instance
'''
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
# unlikely but safeguard from invalid returns
'Target': job.get('tgt', 'unknown-target'),
'Target-type': job.get('tgt_type', 'list'),
'User': job.get('user', 'root')}
if 'metadata' in job:
ret['Metadata'] = job.get('metadata', {})
else:
if 'kwargs' in job:
if 'metadata' in job['kwargs']:
ret['Metadata'] = job['kwargs'].get('metadata', {})
if 'Minions' in job:
ret['Minions'] = job['Minions']
return ret
def _format_jid_instance(jid, job):
'''
Helper to format jid instance
'''
ret = _format_job_instance(job)
ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})
return ret
def _walk_through(job_dir, display_progress=False):
'''
Walk through the job dir and return jobs
'''
serial = salt.payload.Serial(__opts__)
for top in os.listdir(job_dir):
t_path = os.path.join(job_dir, top)
for final in os.listdir(t_path):
load_path = os.path.join(t_path, final, '.load.p')
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
if not os.path.isfile(load_path):
continue
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
jid = job['jid']
if display_progress:
__jid_event__.fire_event(
{'message': 'Found JID {0}'.format(jid)},
'progress'
)
yield jid, job, t_path, final
|
saltstack/salt
|
salt/runners/jobs.py
|
exit_success
|
python
|
def exit_success(jid, ext_source=None):
'''
Check if a job has been executed and exit successfully
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.exit_success 20160520145827701627
'''
ret = dict()
data = list_job(
jid,
ext_source=ext_source
)
minions = data.get('Minions', [])
result = data.get('Result', {})
for minion in minions:
if minion in result and 'return' in result[minion]:
ret[minion] = True if result[minion]['return'] else False
else:
ret[minion] = False
for minion in result:
if 'return' in result[minion] and result[minion]['return']:
ret[minion] = True
return ret
|
Check if a job has been executed and exit successfully
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.exit_success 20160520145827701627
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/jobs.py#L466-L500
|
[
"def list_job(jid, ext_source=None, display_progress=False):\n '''\n List a specific job given by its jid\n\n ext_source\n If provided, specifies which external job cache to use.\n\n display_progress : False\n If ``True``, fire progress events.\n\n .. versionadded:: 2015.8.8\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run jobs.list_job 20130916125524463507\n salt-run jobs.list_job 20130916125524463507 --out=pprint\n '''\n ret = {'jid': jid}\n mminion = salt.minion.MasterMinion(__opts__)\n returner = _get_returner((\n __opts__['ext_job_cache'],\n ext_source,\n __opts__['master_job_cache']\n ))\n if display_progress:\n __jid_event__.fire_event(\n {'message': 'Querying returner: {0}'.format(returner)},\n 'progress'\n )\n\n job = mminion.returners['{0}.get_load'.format(returner)](jid)\n ret.update(_format_jid_instance(jid, job))\n ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)\n\n fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])\n if (__opts__.get('job_cache_store_endtime')\n and fstr in mminion.returners):\n endtime = mminion.returners[fstr](jid)\n if endtime:\n ret['EndTime'] = endtime\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
A convenience system to manage jobs, both active and already run
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import os
# Import salt libs
import salt.client
import salt.payload
import salt.utils.args
import salt.utils.files
import salt.utils.jid
import salt.minion
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.exceptions import SaltClientError
try:
import dateutil.parser as dateutil_parser
DATEUTIL_SUPPORT = True
except ImportError:
DATEUTIL_SUPPORT = False
log = logging.getLogger(__name__)
def active(display_progress=False):
'''
Return a report on all actively running jobs from a job id centric
perspective
CLI Example:
.. code-block:: bash
salt-run jobs.active
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
if display_progress:
__jid_event__.fire_event({
'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
}, 'progress')
for minion, data in six.iteritems(active_):
if display_progress:
__jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
if not isinstance(data, list):
continue
for job in data:
if not job['jid'] in ret:
ret[job['jid']] = _format_jid_instance(job['jid'], job)
ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
else:
ret[job['jid']]['Running'].append({minion: job['pid']})
mminion = salt.minion.MasterMinion(__opts__)
for jid in ret:
returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
if data:
for minion in data:
if minion not in ret[jid]['Returned']:
ret[jid]['Returned'].append(minion)
return ret
def lookup_jid(jid,
ext_source=None,
returned=True,
missing=False,
display_progress=False):
'''
Return the printout from a previously executed job
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
returned : True
If ``True``, include the minions that did return from the command.
.. versionadded:: 2015.8.0
missing : False
If ``True``, include the minions that did *not* return from the
command.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run jobs.lookup_jid 20130916125524463507
salt-run jobs.lookup_jid 20130916125524463507 --out=highstate
'''
ret = {}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
try:
data = list_job(
jid,
ext_source=ext_source,
display_progress=display_progress
)
except TypeError:
return ('Requested returner could not be loaded. '
'No JIDs could be retrieved.')
targeted_minions = data.get('Minions', [])
returns = data.get('Result', {})
if returns:
for minion in returns:
if display_progress:
__jid_event__.fire_event({'message': minion}, 'progress')
if u'return' in returns[minion]:
if returned:
ret[minion] = returns[minion].get(u'return')
else:
if returned:
ret[minion] = returns[minion].get('return')
if missing:
for minion_id in (x for x in targeted_minions if x not in returns):
ret[minion_id] = 'Minion did not return'
# We need to check to see if the 'out' key is present and use it to specify
# the correct outputter, so we get highstate output for highstate runs.
try:
# Check if the return data has an 'out' key. We'll use that as the
# outputter in the absence of one being passed on the CLI.
outputter = None
_ret = returns[next(iter(returns))]
if 'out' in _ret:
outputter = _ret['out']
elif 'outputter' in _ret.get('return', {}).get('return', {}):
outputter = _ret['return']['return']['outputter']
except (StopIteration, AttributeError):
pass
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def list_job(jid, ext_source=None, display_progress=False):
'''
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
.. code-block:: bash
salt-run jobs.list_job 20130916125524463507
salt-run jobs.list_job 20130916125524463507 --out=pprint
'''
ret = {'jid': jid}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner: {0}'.format(returner)},
'progress'
)
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret.update(_format_jid_instance(jid, job))
ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret['EndTime'] = endtime
return ret
def list_jobs(ext_source=None,
outputter=None,
search_metadata=None,
search_function=None,
search_target=None,
start_time=None,
end_time=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
If provided, specifies which external job cache to use.
**FILTER OPTIONS**
.. note::
If more than one of the below options are used, only jobs which match
*all* of the filters will be returned.
search_metadata
Specify a dictionary to match to the job's metadata. If any of the
key-value pairs in this dictionary match, the job will be returned.
Example:
.. code-block:: bash
salt-run jobs.list_jobs search_metadata='{"foo": "bar", "baz": "qux"}'
search_function
Can be passed as a string or a list. Returns jobs which match the
specified function. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*'
salt-run jobs.list_jobs search_function='["test.*", "pkg.install"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*,pkg.install'
search_target
Can be passed as a string or a list. Returns jobs which match the
specified minion name. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='*.mydomain.tld'
salt-run jobs.list_jobs search_target='["db*", "myminion"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='db*,myminion'
start_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started after this timestamp.
end_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started before this timestamp.
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs
salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{"bar": "foo"}'
salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
ret = mminion.returners['{0}.get_jids'.format(returner)]()
mret = {}
for item in ret:
_match = True
if search_metadata:
_match = False
if 'Metadata' in ret[item]:
if isinstance(search_metadata, dict):
for key in search_metadata:
if key in ret[item]['Metadata']:
if ret[item]['Metadata'][key] == search_metadata[key]:
_match = True
else:
log.info('The search_metadata parameter must be specified'
' as a dictionary. Ignoring.')
if search_target and _match:
_match = False
if 'Target' in ret[item]:
targets = ret[item]['Target']
if isinstance(targets, six.string_types):
targets = [targets]
for target in targets:
for key in salt.utils.args.split_input(search_target):
if fnmatch.fnmatch(target, key):
_match = True
if search_function and _match:
_match = False
if 'Function' in ret[item]:
for key in salt.utils.args.split_input(search_function):
if fnmatch.fnmatch(ret[item]['Function'], key):
_match = True
if start_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_start_time = dateutil_parser.parse(start_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time >= parsed_start_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping start_time '
'comparison.'
)
if end_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_end_time = dateutil_parser.parse(end_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time <= parsed_end_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping end_time '
'comparison.'
)
if _match:
mret[item] = ret[item]
if outputter:
return {'outputter': outputter, 'data': mret}
else:
return mret
def list_jobs_filter(count,
filter_find_job=True,
ext_source=None,
outputter=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs_filter 50
salt-run jobs.list_jobs_filter 100 filter_find_job=False
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
fun = '{0}.get_jids_filter'.format(returner)
if fun not in mminion.returners:
raise NotImplementedError(
'\'{0}\' returner function not implemented yet.'.format(fun)
)
ret = mminion.returners[fun](count, filter_find_job)
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def print_job(jid, ext_source=None):
'''
Print a specific job's detail given by it's jid, including the return data.
CLI Example:
.. code-block:: bash
salt-run jobs.print_job 20130916125524463507
'''
ret = {}
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
mminion = salt.minion.MasterMinion(__opts__)
try:
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret[jid] = _format_jid_instance(jid, job)
except TypeError:
ret[jid]['Result'] = (
'Requested returner {0} is not available. Jobs cannot be '
'retrieved. Check master log for details.'.format(returner)
)
return ret
ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret[jid]['EndTime'] = endtime
return ret
def last_run(ext_source=None,
outputter=None,
metadata=None,
function=None,
target=None,
display_progress=False):
'''
.. versionadded:: 2015.8.0
List all detectable jobs and associated functions
CLI Example:
.. code-block:: bash
salt-run jobs.last_run
salt-run jobs.last_run target=nodename
salt-run jobs.last_run function='cmd.run'
salt-run jobs.last_run metadata="{'foo': 'bar'}"
'''
if metadata:
if not isinstance(metadata, dict):
log.info('The metadata parameter must be specified as a dictionary')
return False
_all_jobs = list_jobs(ext_source=ext_source,
outputter=outputter,
search_metadata=metadata,
search_function=function,
search_target=target,
display_progress=display_progress)
if _all_jobs:
last_job = sorted(_all_jobs)[-1]
return print_job(last_job, ext_source)
else:
return False
def _get_returner(returner_types):
'''
Helper to iterate over returner_types and pick the first one
'''
for returner in returner_types:
if returner and returner is not None:
return returner
def _format_job_instance(job):
'''
Helper to format a job instance
'''
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
# unlikely but safeguard from invalid returns
'Target': job.get('tgt', 'unknown-target'),
'Target-type': job.get('tgt_type', 'list'),
'User': job.get('user', 'root')}
if 'metadata' in job:
ret['Metadata'] = job.get('metadata', {})
else:
if 'kwargs' in job:
if 'metadata' in job['kwargs']:
ret['Metadata'] = job['kwargs'].get('metadata', {})
if 'Minions' in job:
ret['Minions'] = job['Minions']
return ret
def _format_jid_instance(jid, job):
'''
Helper to format jid instance
'''
ret = _format_job_instance(job)
ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})
return ret
def _walk_through(job_dir, display_progress=False):
'''
Walk through the job dir and return jobs
'''
serial = salt.payload.Serial(__opts__)
for top in os.listdir(job_dir):
t_path = os.path.join(job_dir, top)
for final in os.listdir(t_path):
load_path = os.path.join(t_path, final, '.load.p')
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
if not os.path.isfile(load_path):
continue
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
jid = job['jid']
if display_progress:
__jid_event__.fire_event(
{'message': 'Found JID {0}'.format(jid)},
'progress'
)
yield jid, job, t_path, final
|
saltstack/salt
|
salt/runners/jobs.py
|
last_run
|
python
|
def last_run(ext_source=None,
outputter=None,
metadata=None,
function=None,
target=None,
display_progress=False):
'''
.. versionadded:: 2015.8.0
List all detectable jobs and associated functions
CLI Example:
.. code-block:: bash
salt-run jobs.last_run
salt-run jobs.last_run target=nodename
salt-run jobs.last_run function='cmd.run'
salt-run jobs.last_run metadata="{'foo': 'bar'}"
'''
if metadata:
if not isinstance(metadata, dict):
log.info('The metadata parameter must be specified as a dictionary')
return False
_all_jobs = list_jobs(ext_source=ext_source,
outputter=outputter,
search_metadata=metadata,
search_function=function,
search_target=target,
display_progress=display_progress)
if _all_jobs:
last_job = sorted(_all_jobs)[-1]
return print_job(last_job, ext_source)
else:
return False
|
.. versionadded:: 2015.8.0
List all detectable jobs and associated functions
CLI Example:
.. code-block:: bash
salt-run jobs.last_run
salt-run jobs.last_run target=nodename
salt-run jobs.last_run function='cmd.run'
salt-run jobs.last_run metadata="{'foo': 'bar'}"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/jobs.py#L503-L539
|
[
"def list_jobs(ext_source=None,\n outputter=None,\n search_metadata=None,\n search_function=None,\n search_target=None,\n start_time=None,\n end_time=None,\n display_progress=False):\n '''\n List all detectable jobs and associated functions\n\n ext_source\n If provided, specifies which external job cache to use.\n\n **FILTER OPTIONS**\n\n .. note::\n If more than one of the below options are used, only jobs which match\n *all* of the filters will be returned.\n\n search_metadata\n Specify a dictionary to match to the job's metadata. If any of the\n key-value pairs in this dictionary match, the job will be returned.\n Example:\n\n .. code-block:: bash\n\n salt-run jobs.list_jobs search_metadata='{\"foo\": \"bar\", \"baz\": \"qux\"}'\n\n search_function\n Can be passed as a string or a list. Returns jobs which match the\n specified function. Globbing is allowed. Example:\n\n .. code-block:: bash\n\n salt-run jobs.list_jobs search_function='test.*'\n salt-run jobs.list_jobs search_function='[\"test.*\", \"pkg.install\"]'\n\n .. versionchanged:: 2015.8.8\n Multiple targets can now also be passed as a comma-separated list.\n For example:\n\n .. code-block:: bash\n\n salt-run jobs.list_jobs search_function='test.*,pkg.install'\n\n search_target\n Can be passed as a string or a list. Returns jobs which match the\n specified minion name. Globbing is allowed. Example:\n\n .. code-block:: bash\n\n salt-run jobs.list_jobs search_target='*.mydomain.tld'\n salt-run jobs.list_jobs search_target='[\"db*\", \"myminion\"]'\n\n .. versionchanged:: 2015.8.8\n Multiple targets can now also be passed as a comma-separated list.\n For example:\n\n .. code-block:: bash\n\n salt-run jobs.list_jobs search_target='db*,myminion'\n\n start_time\n Accepts any timestamp supported by the dateutil_ Python module (if this\n module is not installed, this argument will be ignored). Returns jobs\n which started after this timestamp.\n\n end_time\n Accepts any timestamp supported by the dateutil_ Python module (if this\n module is not installed, this argument will be ignored). Returns jobs\n which started before this timestamp.\n\n .. _dateutil: https://pypi.python.org/pypi/python-dateutil\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run jobs.list_jobs\n salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{\"bar\": \"foo\"}'\n salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'\n\n '''\n returner = _get_returner((\n __opts__['ext_job_cache'],\n ext_source,\n __opts__['master_job_cache']\n ))\n if display_progress:\n __jid_event__.fire_event(\n {'message': 'Querying returner {0} for jobs.'.format(returner)},\n 'progress'\n )\n mminion = salt.minion.MasterMinion(__opts__)\n\n ret = mminion.returners['{0}.get_jids'.format(returner)]()\n\n mret = {}\n for item in ret:\n _match = True\n if search_metadata:\n _match = False\n if 'Metadata' in ret[item]:\n if isinstance(search_metadata, dict):\n for key in search_metadata:\n if key in ret[item]['Metadata']:\n if ret[item]['Metadata'][key] == search_metadata[key]:\n _match = True\n else:\n log.info('The search_metadata parameter must be specified'\n ' as a dictionary. Ignoring.')\n if search_target and _match:\n _match = False\n if 'Target' in ret[item]:\n targets = ret[item]['Target']\n if isinstance(targets, six.string_types):\n targets = [targets]\n for target in targets:\n for key in salt.utils.args.split_input(search_target):\n if fnmatch.fnmatch(target, key):\n _match = True\n\n if search_function and _match:\n _match = False\n if 'Function' in ret[item]:\n for key in salt.utils.args.split_input(search_function):\n if fnmatch.fnmatch(ret[item]['Function'], key):\n _match = True\n\n if start_time and _match:\n _match = False\n if DATEUTIL_SUPPORT:\n parsed_start_time = dateutil_parser.parse(start_time)\n _start_time = dateutil_parser.parse(ret[item]['StartTime'])\n if _start_time >= parsed_start_time:\n _match = True\n else:\n log.error(\n '\\'dateutil\\' library not available, skipping start_time '\n 'comparison.'\n )\n\n if end_time and _match:\n _match = False\n if DATEUTIL_SUPPORT:\n parsed_end_time = dateutil_parser.parse(end_time)\n _start_time = dateutil_parser.parse(ret[item]['StartTime'])\n if _start_time <= parsed_end_time:\n _match = True\n else:\n log.error(\n '\\'dateutil\\' library not available, skipping end_time '\n 'comparison.'\n )\n\n if _match:\n mret[item] = ret[item]\n\n if outputter:\n return {'outputter': outputter, 'data': mret}\n else:\n return mret\n",
"def print_job(jid, ext_source=None):\n '''\n Print a specific job's detail given by it's jid, including the return data.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run jobs.print_job 20130916125524463507\n '''\n ret = {}\n\n returner = _get_returner((\n __opts__['ext_job_cache'],\n ext_source,\n __opts__['master_job_cache']\n ))\n mminion = salt.minion.MasterMinion(__opts__)\n\n try:\n job = mminion.returners['{0}.get_load'.format(returner)](jid)\n ret[jid] = _format_jid_instance(jid, job)\n except TypeError:\n ret[jid]['Result'] = (\n 'Requested returner {0} is not available. Jobs cannot be '\n 'retrieved. Check master log for details.'.format(returner)\n )\n return ret\n ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)\n\n fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])\n if (__opts__.get('job_cache_store_endtime')\n and fstr in mminion.returners):\n endtime = mminion.returners[fstr](jid)\n if endtime:\n ret[jid]['EndTime'] = endtime\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
A convenience system to manage jobs, both active and already run
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import os
# Import salt libs
import salt.client
import salt.payload
import salt.utils.args
import salt.utils.files
import salt.utils.jid
import salt.minion
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.exceptions import SaltClientError
try:
import dateutil.parser as dateutil_parser
DATEUTIL_SUPPORT = True
except ImportError:
DATEUTIL_SUPPORT = False
log = logging.getLogger(__name__)
def active(display_progress=False):
'''
Return a report on all actively running jobs from a job id centric
perspective
CLI Example:
.. code-block:: bash
salt-run jobs.active
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
if display_progress:
__jid_event__.fire_event({
'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
}, 'progress')
for minion, data in six.iteritems(active_):
if display_progress:
__jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
if not isinstance(data, list):
continue
for job in data:
if not job['jid'] in ret:
ret[job['jid']] = _format_jid_instance(job['jid'], job)
ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
else:
ret[job['jid']]['Running'].append({minion: job['pid']})
mminion = salt.minion.MasterMinion(__opts__)
for jid in ret:
returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
if data:
for minion in data:
if minion not in ret[jid]['Returned']:
ret[jid]['Returned'].append(minion)
return ret
def lookup_jid(jid,
ext_source=None,
returned=True,
missing=False,
display_progress=False):
'''
Return the printout from a previously executed job
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
returned : True
If ``True``, include the minions that did return from the command.
.. versionadded:: 2015.8.0
missing : False
If ``True``, include the minions that did *not* return from the
command.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run jobs.lookup_jid 20130916125524463507
salt-run jobs.lookup_jid 20130916125524463507 --out=highstate
'''
ret = {}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
try:
data = list_job(
jid,
ext_source=ext_source,
display_progress=display_progress
)
except TypeError:
return ('Requested returner could not be loaded. '
'No JIDs could be retrieved.')
targeted_minions = data.get('Minions', [])
returns = data.get('Result', {})
if returns:
for minion in returns:
if display_progress:
__jid_event__.fire_event({'message': minion}, 'progress')
if u'return' in returns[minion]:
if returned:
ret[minion] = returns[minion].get(u'return')
else:
if returned:
ret[minion] = returns[minion].get('return')
if missing:
for minion_id in (x for x in targeted_minions if x not in returns):
ret[minion_id] = 'Minion did not return'
# We need to check to see if the 'out' key is present and use it to specify
# the correct outputter, so we get highstate output for highstate runs.
try:
# Check if the return data has an 'out' key. We'll use that as the
# outputter in the absence of one being passed on the CLI.
outputter = None
_ret = returns[next(iter(returns))]
if 'out' in _ret:
outputter = _ret['out']
elif 'outputter' in _ret.get('return', {}).get('return', {}):
outputter = _ret['return']['return']['outputter']
except (StopIteration, AttributeError):
pass
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def list_job(jid, ext_source=None, display_progress=False):
'''
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
.. code-block:: bash
salt-run jobs.list_job 20130916125524463507
salt-run jobs.list_job 20130916125524463507 --out=pprint
'''
ret = {'jid': jid}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner: {0}'.format(returner)},
'progress'
)
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret.update(_format_jid_instance(jid, job))
ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret['EndTime'] = endtime
return ret
def list_jobs(ext_source=None,
outputter=None,
search_metadata=None,
search_function=None,
search_target=None,
start_time=None,
end_time=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
If provided, specifies which external job cache to use.
**FILTER OPTIONS**
.. note::
If more than one of the below options are used, only jobs which match
*all* of the filters will be returned.
search_metadata
Specify a dictionary to match to the job's metadata. If any of the
key-value pairs in this dictionary match, the job will be returned.
Example:
.. code-block:: bash
salt-run jobs.list_jobs search_metadata='{"foo": "bar", "baz": "qux"}'
search_function
Can be passed as a string or a list. Returns jobs which match the
specified function. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*'
salt-run jobs.list_jobs search_function='["test.*", "pkg.install"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*,pkg.install'
search_target
Can be passed as a string or a list. Returns jobs which match the
specified minion name. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='*.mydomain.tld'
salt-run jobs.list_jobs search_target='["db*", "myminion"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='db*,myminion'
start_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started after this timestamp.
end_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started before this timestamp.
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs
salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{"bar": "foo"}'
salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
ret = mminion.returners['{0}.get_jids'.format(returner)]()
mret = {}
for item in ret:
_match = True
if search_metadata:
_match = False
if 'Metadata' in ret[item]:
if isinstance(search_metadata, dict):
for key in search_metadata:
if key in ret[item]['Metadata']:
if ret[item]['Metadata'][key] == search_metadata[key]:
_match = True
else:
log.info('The search_metadata parameter must be specified'
' as a dictionary. Ignoring.')
if search_target and _match:
_match = False
if 'Target' in ret[item]:
targets = ret[item]['Target']
if isinstance(targets, six.string_types):
targets = [targets]
for target in targets:
for key in salt.utils.args.split_input(search_target):
if fnmatch.fnmatch(target, key):
_match = True
if search_function and _match:
_match = False
if 'Function' in ret[item]:
for key in salt.utils.args.split_input(search_function):
if fnmatch.fnmatch(ret[item]['Function'], key):
_match = True
if start_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_start_time = dateutil_parser.parse(start_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time >= parsed_start_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping start_time '
'comparison.'
)
if end_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_end_time = dateutil_parser.parse(end_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time <= parsed_end_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping end_time '
'comparison.'
)
if _match:
mret[item] = ret[item]
if outputter:
return {'outputter': outputter, 'data': mret}
else:
return mret
def list_jobs_filter(count,
filter_find_job=True,
ext_source=None,
outputter=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs_filter 50
salt-run jobs.list_jobs_filter 100 filter_find_job=False
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
fun = '{0}.get_jids_filter'.format(returner)
if fun not in mminion.returners:
raise NotImplementedError(
'\'{0}\' returner function not implemented yet.'.format(fun)
)
ret = mminion.returners[fun](count, filter_find_job)
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def print_job(jid, ext_source=None):
'''
Print a specific job's detail given by it's jid, including the return data.
CLI Example:
.. code-block:: bash
salt-run jobs.print_job 20130916125524463507
'''
ret = {}
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
mminion = salt.minion.MasterMinion(__opts__)
try:
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret[jid] = _format_jid_instance(jid, job)
except TypeError:
ret[jid]['Result'] = (
'Requested returner {0} is not available. Jobs cannot be '
'retrieved. Check master log for details.'.format(returner)
)
return ret
ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret[jid]['EndTime'] = endtime
return ret
def exit_success(jid, ext_source=None):
'''
Check if a job has been executed and exit successfully
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.exit_success 20160520145827701627
'''
ret = dict()
data = list_job(
jid,
ext_source=ext_source
)
minions = data.get('Minions', [])
result = data.get('Result', {})
for minion in minions:
if minion in result and 'return' in result[minion]:
ret[minion] = True if result[minion]['return'] else False
else:
ret[minion] = False
for minion in result:
if 'return' in result[minion] and result[minion]['return']:
ret[minion] = True
return ret
def _get_returner(returner_types):
'''
Helper to iterate over returner_types and pick the first one
'''
for returner in returner_types:
if returner and returner is not None:
return returner
def _format_job_instance(job):
'''
Helper to format a job instance
'''
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
# unlikely but safeguard from invalid returns
'Target': job.get('tgt', 'unknown-target'),
'Target-type': job.get('tgt_type', 'list'),
'User': job.get('user', 'root')}
if 'metadata' in job:
ret['Metadata'] = job.get('metadata', {})
else:
if 'kwargs' in job:
if 'metadata' in job['kwargs']:
ret['Metadata'] = job['kwargs'].get('metadata', {})
if 'Minions' in job:
ret['Minions'] = job['Minions']
return ret
def _format_jid_instance(jid, job):
'''
Helper to format jid instance
'''
ret = _format_job_instance(job)
ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})
return ret
def _walk_through(job_dir, display_progress=False):
'''
Walk through the job dir and return jobs
'''
serial = salt.payload.Serial(__opts__)
for top in os.listdir(job_dir):
t_path = os.path.join(job_dir, top)
for final in os.listdir(t_path):
load_path = os.path.join(t_path, final, '.load.p')
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
if not os.path.isfile(load_path):
continue
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
jid = job['jid']
if display_progress:
__jid_event__.fire_event(
{'message': 'Found JID {0}'.format(jid)},
'progress'
)
yield jid, job, t_path, final
|
saltstack/salt
|
salt/runners/jobs.py
|
_format_job_instance
|
python
|
def _format_job_instance(job):
'''
Helper to format a job instance
'''
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
# unlikely but safeguard from invalid returns
'Target': job.get('tgt', 'unknown-target'),
'Target-type': job.get('tgt_type', 'list'),
'User': job.get('user', 'root')}
if 'metadata' in job:
ret['Metadata'] = job.get('metadata', {})
else:
if 'kwargs' in job:
if 'metadata' in job['kwargs']:
ret['Metadata'] = job['kwargs'].get('metadata', {})
if 'Minions' in job:
ret['Minions'] = job['Minions']
return ret
|
Helper to format a job instance
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/jobs.py#L551-L575
| null |
# -*- coding: utf-8 -*-
'''
A convenience system to manage jobs, both active and already run
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import os
# Import salt libs
import salt.client
import salt.payload
import salt.utils.args
import salt.utils.files
import salt.utils.jid
import salt.minion
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.exceptions import SaltClientError
try:
import dateutil.parser as dateutil_parser
DATEUTIL_SUPPORT = True
except ImportError:
DATEUTIL_SUPPORT = False
log = logging.getLogger(__name__)
def active(display_progress=False):
'''
Return a report on all actively running jobs from a job id centric
perspective
CLI Example:
.. code-block:: bash
salt-run jobs.active
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
if display_progress:
__jid_event__.fire_event({
'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
}, 'progress')
for minion, data in six.iteritems(active_):
if display_progress:
__jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
if not isinstance(data, list):
continue
for job in data:
if not job['jid'] in ret:
ret[job['jid']] = _format_jid_instance(job['jid'], job)
ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
else:
ret[job['jid']]['Running'].append({minion: job['pid']})
mminion = salt.minion.MasterMinion(__opts__)
for jid in ret:
returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
if data:
for minion in data:
if minion not in ret[jid]['Returned']:
ret[jid]['Returned'].append(minion)
return ret
def lookup_jid(jid,
ext_source=None,
returned=True,
missing=False,
display_progress=False):
'''
Return the printout from a previously executed job
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
returned : True
If ``True``, include the minions that did return from the command.
.. versionadded:: 2015.8.0
missing : False
If ``True``, include the minions that did *not* return from the
command.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run jobs.lookup_jid 20130916125524463507
salt-run jobs.lookup_jid 20130916125524463507 --out=highstate
'''
ret = {}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
try:
data = list_job(
jid,
ext_source=ext_source,
display_progress=display_progress
)
except TypeError:
return ('Requested returner could not be loaded. '
'No JIDs could be retrieved.')
targeted_minions = data.get('Minions', [])
returns = data.get('Result', {})
if returns:
for minion in returns:
if display_progress:
__jid_event__.fire_event({'message': minion}, 'progress')
if u'return' in returns[minion]:
if returned:
ret[minion] = returns[minion].get(u'return')
else:
if returned:
ret[minion] = returns[minion].get('return')
if missing:
for minion_id in (x for x in targeted_minions if x not in returns):
ret[minion_id] = 'Minion did not return'
# We need to check to see if the 'out' key is present and use it to specify
# the correct outputter, so we get highstate output for highstate runs.
try:
# Check if the return data has an 'out' key. We'll use that as the
# outputter in the absence of one being passed on the CLI.
outputter = None
_ret = returns[next(iter(returns))]
if 'out' in _ret:
outputter = _ret['out']
elif 'outputter' in _ret.get('return', {}).get('return', {}):
outputter = _ret['return']['return']['outputter']
except (StopIteration, AttributeError):
pass
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def list_job(jid, ext_source=None, display_progress=False):
'''
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
.. code-block:: bash
salt-run jobs.list_job 20130916125524463507
salt-run jobs.list_job 20130916125524463507 --out=pprint
'''
ret = {'jid': jid}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner: {0}'.format(returner)},
'progress'
)
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret.update(_format_jid_instance(jid, job))
ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret['EndTime'] = endtime
return ret
def list_jobs(ext_source=None,
outputter=None,
search_metadata=None,
search_function=None,
search_target=None,
start_time=None,
end_time=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
If provided, specifies which external job cache to use.
**FILTER OPTIONS**
.. note::
If more than one of the below options are used, only jobs which match
*all* of the filters will be returned.
search_metadata
Specify a dictionary to match to the job's metadata. If any of the
key-value pairs in this dictionary match, the job will be returned.
Example:
.. code-block:: bash
salt-run jobs.list_jobs search_metadata='{"foo": "bar", "baz": "qux"}'
search_function
Can be passed as a string or a list. Returns jobs which match the
specified function. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*'
salt-run jobs.list_jobs search_function='["test.*", "pkg.install"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*,pkg.install'
search_target
Can be passed as a string or a list. Returns jobs which match the
specified minion name. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='*.mydomain.tld'
salt-run jobs.list_jobs search_target='["db*", "myminion"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='db*,myminion'
start_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started after this timestamp.
end_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started before this timestamp.
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs
salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{"bar": "foo"}'
salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
ret = mminion.returners['{0}.get_jids'.format(returner)]()
mret = {}
for item in ret:
_match = True
if search_metadata:
_match = False
if 'Metadata' in ret[item]:
if isinstance(search_metadata, dict):
for key in search_metadata:
if key in ret[item]['Metadata']:
if ret[item]['Metadata'][key] == search_metadata[key]:
_match = True
else:
log.info('The search_metadata parameter must be specified'
' as a dictionary. Ignoring.')
if search_target and _match:
_match = False
if 'Target' in ret[item]:
targets = ret[item]['Target']
if isinstance(targets, six.string_types):
targets = [targets]
for target in targets:
for key in salt.utils.args.split_input(search_target):
if fnmatch.fnmatch(target, key):
_match = True
if search_function and _match:
_match = False
if 'Function' in ret[item]:
for key in salt.utils.args.split_input(search_function):
if fnmatch.fnmatch(ret[item]['Function'], key):
_match = True
if start_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_start_time = dateutil_parser.parse(start_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time >= parsed_start_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping start_time '
'comparison.'
)
if end_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_end_time = dateutil_parser.parse(end_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time <= parsed_end_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping end_time '
'comparison.'
)
if _match:
mret[item] = ret[item]
if outputter:
return {'outputter': outputter, 'data': mret}
else:
return mret
def list_jobs_filter(count,
filter_find_job=True,
ext_source=None,
outputter=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs_filter 50
salt-run jobs.list_jobs_filter 100 filter_find_job=False
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
fun = '{0}.get_jids_filter'.format(returner)
if fun not in mminion.returners:
raise NotImplementedError(
'\'{0}\' returner function not implemented yet.'.format(fun)
)
ret = mminion.returners[fun](count, filter_find_job)
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def print_job(jid, ext_source=None):
'''
Print a specific job's detail given by it's jid, including the return data.
CLI Example:
.. code-block:: bash
salt-run jobs.print_job 20130916125524463507
'''
ret = {}
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
mminion = salt.minion.MasterMinion(__opts__)
try:
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret[jid] = _format_jid_instance(jid, job)
except TypeError:
ret[jid]['Result'] = (
'Requested returner {0} is not available. Jobs cannot be '
'retrieved. Check master log for details.'.format(returner)
)
return ret
ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret[jid]['EndTime'] = endtime
return ret
def exit_success(jid, ext_source=None):
'''
Check if a job has been executed and exit successfully
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.exit_success 20160520145827701627
'''
ret = dict()
data = list_job(
jid,
ext_source=ext_source
)
minions = data.get('Minions', [])
result = data.get('Result', {})
for minion in minions:
if minion in result and 'return' in result[minion]:
ret[minion] = True if result[minion]['return'] else False
else:
ret[minion] = False
for minion in result:
if 'return' in result[minion] and result[minion]['return']:
ret[minion] = True
return ret
def last_run(ext_source=None,
outputter=None,
metadata=None,
function=None,
target=None,
display_progress=False):
'''
.. versionadded:: 2015.8.0
List all detectable jobs and associated functions
CLI Example:
.. code-block:: bash
salt-run jobs.last_run
salt-run jobs.last_run target=nodename
salt-run jobs.last_run function='cmd.run'
salt-run jobs.last_run metadata="{'foo': 'bar'}"
'''
if metadata:
if not isinstance(metadata, dict):
log.info('The metadata parameter must be specified as a dictionary')
return False
_all_jobs = list_jobs(ext_source=ext_source,
outputter=outputter,
search_metadata=metadata,
search_function=function,
search_target=target,
display_progress=display_progress)
if _all_jobs:
last_job = sorted(_all_jobs)[-1]
return print_job(last_job, ext_source)
else:
return False
def _get_returner(returner_types):
'''
Helper to iterate over returner_types and pick the first one
'''
for returner in returner_types:
if returner and returner is not None:
return returner
def _format_jid_instance(jid, job):
'''
Helper to format jid instance
'''
ret = _format_job_instance(job)
ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})
return ret
def _walk_through(job_dir, display_progress=False):
'''
Walk through the job dir and return jobs
'''
serial = salt.payload.Serial(__opts__)
for top in os.listdir(job_dir):
t_path = os.path.join(job_dir, top)
for final in os.listdir(t_path):
load_path = os.path.join(t_path, final, '.load.p')
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
if not os.path.isfile(load_path):
continue
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
jid = job['jid']
if display_progress:
__jid_event__.fire_event(
{'message': 'Found JID {0}'.format(jid)},
'progress'
)
yield jid, job, t_path, final
|
saltstack/salt
|
salt/runners/jobs.py
|
_walk_through
|
python
|
def _walk_through(job_dir, display_progress=False):
'''
Walk through the job dir and return jobs
'''
serial = salt.payload.Serial(__opts__)
for top in os.listdir(job_dir):
t_path = os.path.join(job_dir, top)
for final in os.listdir(t_path):
load_path = os.path.join(t_path, final, '.load.p')
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
if not os.path.isfile(load_path):
continue
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
jid = job['jid']
if display_progress:
__jid_event__.fire_event(
{'message': 'Found JID {0}'.format(jid)},
'progress'
)
yield jid, job, t_path, final
|
Walk through the job dir and return jobs
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/jobs.py#L587-L612
| null |
# -*- coding: utf-8 -*-
'''
A convenience system to manage jobs, both active and already run
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import os
# Import salt libs
import salt.client
import salt.payload
import salt.utils.args
import salt.utils.files
import salt.utils.jid
import salt.minion
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.exceptions import SaltClientError
try:
import dateutil.parser as dateutil_parser
DATEUTIL_SUPPORT = True
except ImportError:
DATEUTIL_SUPPORT = False
log = logging.getLogger(__name__)
def active(display_progress=False):
'''
Return a report on all actively running jobs from a job id centric
perspective
CLI Example:
.. code-block:: bash
salt-run jobs.active
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
if display_progress:
__jid_event__.fire_event({
'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
}, 'progress')
for minion, data in six.iteritems(active_):
if display_progress:
__jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
if not isinstance(data, list):
continue
for job in data:
if not job['jid'] in ret:
ret[job['jid']] = _format_jid_instance(job['jid'], job)
ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
else:
ret[job['jid']]['Running'].append({minion: job['pid']})
mminion = salt.minion.MasterMinion(__opts__)
for jid in ret:
returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
data = mminion.returners['{0}.get_jid'.format(returner)](jid)
if data:
for minion in data:
if minion not in ret[jid]['Returned']:
ret[jid]['Returned'].append(minion)
return ret
def lookup_jid(jid,
ext_source=None,
returned=True,
missing=False,
display_progress=False):
'''
Return the printout from a previously executed job
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
returned : True
If ``True``, include the minions that did return from the command.
.. versionadded:: 2015.8.0
missing : False
If ``True``, include the minions that did *not* return from the
command.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run jobs.lookup_jid 20130916125524463507
salt-run jobs.lookup_jid 20130916125524463507 --out=highstate
'''
ret = {}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
try:
data = list_job(
jid,
ext_source=ext_source,
display_progress=display_progress
)
except TypeError:
return ('Requested returner could not be loaded. '
'No JIDs could be retrieved.')
targeted_minions = data.get('Minions', [])
returns = data.get('Result', {})
if returns:
for minion in returns:
if display_progress:
__jid_event__.fire_event({'message': minion}, 'progress')
if u'return' in returns[minion]:
if returned:
ret[minion] = returns[minion].get(u'return')
else:
if returned:
ret[minion] = returns[minion].get('return')
if missing:
for minion_id in (x for x in targeted_minions if x not in returns):
ret[minion_id] = 'Minion did not return'
# We need to check to see if the 'out' key is present and use it to specify
# the correct outputter, so we get highstate output for highstate runs.
try:
# Check if the return data has an 'out' key. We'll use that as the
# outputter in the absence of one being passed on the CLI.
outputter = None
_ret = returns[next(iter(returns))]
if 'out' in _ret:
outputter = _ret['out']
elif 'outputter' in _ret.get('return', {}).get('return', {}):
outputter = _ret['return']['return']['outputter']
except (StopIteration, AttributeError):
pass
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def list_job(jid, ext_source=None, display_progress=False):
'''
List a specific job given by its jid
ext_source
If provided, specifies which external job cache to use.
display_progress : False
If ``True``, fire progress events.
.. versionadded:: 2015.8.8
CLI Example:
.. code-block:: bash
salt-run jobs.list_job 20130916125524463507
salt-run jobs.list_job 20130916125524463507 --out=pprint
'''
ret = {'jid': jid}
mminion = salt.minion.MasterMinion(__opts__)
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner: {0}'.format(returner)},
'progress'
)
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret.update(_format_jid_instance(jid, job))
ret['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret['EndTime'] = endtime
return ret
def list_jobs(ext_source=None,
outputter=None,
search_metadata=None,
search_function=None,
search_target=None,
start_time=None,
end_time=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
If provided, specifies which external job cache to use.
**FILTER OPTIONS**
.. note::
If more than one of the below options are used, only jobs which match
*all* of the filters will be returned.
search_metadata
Specify a dictionary to match to the job's metadata. If any of the
key-value pairs in this dictionary match, the job will be returned.
Example:
.. code-block:: bash
salt-run jobs.list_jobs search_metadata='{"foo": "bar", "baz": "qux"}'
search_function
Can be passed as a string or a list. Returns jobs which match the
specified function. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*'
salt-run jobs.list_jobs search_function='["test.*", "pkg.install"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_function='test.*,pkg.install'
search_target
Can be passed as a string or a list. Returns jobs which match the
specified minion name. Globbing is allowed. Example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='*.mydomain.tld'
salt-run jobs.list_jobs search_target='["db*", "myminion"]'
.. versionchanged:: 2015.8.8
Multiple targets can now also be passed as a comma-separated list.
For example:
.. code-block:: bash
salt-run jobs.list_jobs search_target='db*,myminion'
start_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started after this timestamp.
end_time
Accepts any timestamp supported by the dateutil_ Python module (if this
module is not installed, this argument will be ignored). Returns jobs
which started before this timestamp.
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs
salt-run jobs.list_jobs search_function='test.*' search_target='localhost' search_metadata='{"bar": "foo"}'
salt-run jobs.list_jobs start_time='2015, Mar 16 19:00' end_time='2015, Mar 18 22:00'
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
ret = mminion.returners['{0}.get_jids'.format(returner)]()
mret = {}
for item in ret:
_match = True
if search_metadata:
_match = False
if 'Metadata' in ret[item]:
if isinstance(search_metadata, dict):
for key in search_metadata:
if key in ret[item]['Metadata']:
if ret[item]['Metadata'][key] == search_metadata[key]:
_match = True
else:
log.info('The search_metadata parameter must be specified'
' as a dictionary. Ignoring.')
if search_target and _match:
_match = False
if 'Target' in ret[item]:
targets = ret[item]['Target']
if isinstance(targets, six.string_types):
targets = [targets]
for target in targets:
for key in salt.utils.args.split_input(search_target):
if fnmatch.fnmatch(target, key):
_match = True
if search_function and _match:
_match = False
if 'Function' in ret[item]:
for key in salt.utils.args.split_input(search_function):
if fnmatch.fnmatch(ret[item]['Function'], key):
_match = True
if start_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_start_time = dateutil_parser.parse(start_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time >= parsed_start_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping start_time '
'comparison.'
)
if end_time and _match:
_match = False
if DATEUTIL_SUPPORT:
parsed_end_time = dateutil_parser.parse(end_time)
_start_time = dateutil_parser.parse(ret[item]['StartTime'])
if _start_time <= parsed_end_time:
_match = True
else:
log.error(
'\'dateutil\' library not available, skipping end_time '
'comparison.'
)
if _match:
mret[item] = ret[item]
if outputter:
return {'outputter': outputter, 'data': mret}
else:
return mret
def list_jobs_filter(count,
filter_find_job=True,
ext_source=None,
outputter=None,
display_progress=False):
'''
List all detectable jobs and associated functions
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.list_jobs_filter 50
salt-run jobs.list_jobs_filter 100 filter_find_job=False
'''
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
if display_progress:
__jid_event__.fire_event(
{'message': 'Querying returner {0} for jobs.'.format(returner)},
'progress'
)
mminion = salt.minion.MasterMinion(__opts__)
fun = '{0}.get_jids_filter'.format(returner)
if fun not in mminion.returners:
raise NotImplementedError(
'\'{0}\' returner function not implemented yet.'.format(fun)
)
ret = mminion.returners[fun](count, filter_find_job)
if outputter:
return {'outputter': outputter, 'data': ret}
else:
return ret
def print_job(jid, ext_source=None):
'''
Print a specific job's detail given by it's jid, including the return data.
CLI Example:
.. code-block:: bash
salt-run jobs.print_job 20130916125524463507
'''
ret = {}
returner = _get_returner((
__opts__['ext_job_cache'],
ext_source,
__opts__['master_job_cache']
))
mminion = salt.minion.MasterMinion(__opts__)
try:
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret[jid] = _format_jid_instance(jid, job)
except TypeError:
ret[jid]['Result'] = (
'Requested returner {0} is not available. Jobs cannot be '
'retrieved. Check master log for details.'.format(returner)
)
return ret
ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime')
and fstr in mminion.returners):
endtime = mminion.returners[fstr](jid)
if endtime:
ret[jid]['EndTime'] = endtime
return ret
def exit_success(jid, ext_source=None):
'''
Check if a job has been executed and exit successfully
jid
The jid to look up.
ext_source
The external job cache to use. Default: `None`.
CLI Example:
.. code-block:: bash
salt-run jobs.exit_success 20160520145827701627
'''
ret = dict()
data = list_job(
jid,
ext_source=ext_source
)
minions = data.get('Minions', [])
result = data.get('Result', {})
for minion in minions:
if minion in result and 'return' in result[minion]:
ret[minion] = True if result[minion]['return'] else False
else:
ret[minion] = False
for minion in result:
if 'return' in result[minion] and result[minion]['return']:
ret[minion] = True
return ret
def last_run(ext_source=None,
outputter=None,
metadata=None,
function=None,
target=None,
display_progress=False):
'''
.. versionadded:: 2015.8.0
List all detectable jobs and associated functions
CLI Example:
.. code-block:: bash
salt-run jobs.last_run
salt-run jobs.last_run target=nodename
salt-run jobs.last_run function='cmd.run'
salt-run jobs.last_run metadata="{'foo': 'bar'}"
'''
if metadata:
if not isinstance(metadata, dict):
log.info('The metadata parameter must be specified as a dictionary')
return False
_all_jobs = list_jobs(ext_source=ext_source,
outputter=outputter,
search_metadata=metadata,
search_function=function,
search_target=target,
display_progress=display_progress)
if _all_jobs:
last_job = sorted(_all_jobs)[-1]
return print_job(last_job, ext_source)
else:
return False
def _get_returner(returner_types):
'''
Helper to iterate over returner_types and pick the first one
'''
for returner in returner_types:
if returner and returner is not None:
return returner
def _format_job_instance(job):
'''
Helper to format a job instance
'''
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
# unlikely but safeguard from invalid returns
'Target': job.get('tgt', 'unknown-target'),
'Target-type': job.get('tgt_type', 'list'),
'User': job.get('user', 'root')}
if 'metadata' in job:
ret['Metadata'] = job.get('metadata', {})
else:
if 'kwargs' in job:
if 'metadata' in job['kwargs']:
ret['Metadata'] = job['kwargs'].get('metadata', {})
if 'Minions' in job:
ret['Minions'] = job['Minions']
return ret
def _format_jid_instance(jid, job):
'''
Helper to format jid instance
'''
ret = _format_job_instance(job)
ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)})
return ret
|
saltstack/salt
|
salt/states/ifttt.py
|
trigger_event
|
python
|
def trigger_event(name,
event,
value1=None,
value2=None,
value3=None
):
'''
Trigger an event in IFTTT
.. code-block:: yaml
ifttt-event:
ifttt.trigger_event:
- event: TestEvent
- value1: 'A value that we want to send.'
- value2: 'A second value that we want to send.'
- value3: 'A third value that we want to send.'
The following parameters are required:
name
The unique name for this event.
event
The name of the event to trigger in IFTTT.
The following parameters are optional:
value1
One of the values that we can send to IFTT.
value2
One of the values that we can send to IFTT.
value3
One of the values that we can send to IFTT.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'The following trigger would be sent to IFTTT: {0}'.format(event)
ret['result'] = None
return ret
ret['result'] = __salt__['ifttt.trigger_event'](
event=event,
value1=value1,
value2=value2,
value3=value3
)
if ret and ret['result']:
ret['result'] = True
ret['comment'] = 'Triggered Event: {0}'.format(name)
else:
ret['comment'] = 'Failed to trigger event: {0}'.format(name)
return ret
|
Trigger an event in IFTTT
.. code-block:: yaml
ifttt-event:
ifttt.trigger_event:
- event: TestEvent
- value1: 'A value that we want to send.'
- value2: 'A second value that we want to send.'
- value3: 'A third value that we want to send.'
The following parameters are required:
name
The unique name for this event.
event
The name of the event to trigger in IFTTT.
The following parameters are optional:
value1
One of the values that we can send to IFTT.
value2
One of the values that we can send to IFTT.
value3
One of the values that we can send to IFTT.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ifttt.py#L38-L98
| null |
# -*- coding: utf-8 -*-
'''
Trigger an event in IFTTT
=========================
This state is useful for trigging events in IFTTT.
.. versionadded:: 2015.8.0
.. code-block:: yaml
ifttt-event:
ifttt.trigger_event:
- event: TestEvent
- value1: 'This state was executed successfully.'
- value2: 'Another value we can send.'
- value3: 'A third value we can send.'
The api key can be specified in the master or minion configuration like below:
.. code-block:: yaml
ifttt:
secret_key: bzMRb-KKIAaNOwKEEw792J7Eb-B3z7muhdhYblJn4V6
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
def __virtual__():
'''
Only load if the ifttt module is available in __salt__
'''
return 'ifttt' if 'ifttt.trigger_event' in __salt__ else False
|
saltstack/salt
|
salt/states/infoblox_cname.py
|
absent
|
python
|
def absent(name=None, canonical=None, **api_opts):
'''
Ensure the CNAME with the given name or canonical name is removed
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
obj = __salt__['infoblox.get_cname'](name=name, canonical=canonical, **api_opts)
if not obj:
ret['result'] = True
ret['comment'] = 'infoblox already removed'
return ret
if __opts__['test']:
ret['result'] = None
ret['changes'] = {'old': obj, 'new': 'absent'}
return ret
if __salt__['infoblox.delete_cname'](name=name, canonical=canonical, **api_opts):
ret['result'] = True
ret['changes'] = {'old': obj, 'new': 'absent'}
return ret
|
Ensure the CNAME with the given name or canonical name is removed
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/infoblox_cname.py#L104-L124
| null |
# -*- coding: utf-8 -*-
'''
Infoblox CNAME managment.
functions accept api_opts:
api_verifyssl: verify SSL [default to True or pillar value]
api_url: server to connect to [default to pillar value]
api_username: [default to pillar value]
api_password: [default to pillar value]
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
def present(name=None, data=None, ensure_data=True, **api_opts):
'''
Ensure the CNAME with the given data is present.
name
CNAME of record
data
raw CNAME api data see: https://INFOBLOX/wapidoc
State example:
.. code-block:: yaml
infoblox_cname.present:
- name: example-ha-0.domain.com
- data:
name: example-ha-0.domain.com
canonical: example.domain.com
zone: example.com
view: Internal
comment: Example comment
infoblox_cname.present:
- name: example-ha-0.domain.com
- data:
name: example-ha-0.domain.com
canonical: example.domain.com
zone: example.com
view: Internal
comment: Example comment
- api_url: https://INFOBLOX/wapi/v1.2.1
- api_username: username
- api_password: passwd
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if not data:
data = {}
if 'name' not in data:
data.update({'name': name})
obj = __salt__['infoblox.get_cname'](name=name, **api_opts)
if obj is None:
# perhaps the user updated the name
obj = __salt__['infoblox.get_cname'](name=data['name'], **api_opts)
if obj:
# warn user that the data was updated and does not match
ret['result'] = False
ret['comment'] = '** please update the name: {0} to equal the updated data name {1}'.format(name, data['name'])
return ret
if obj:
if not ensure_data:
ret['result'] = True
ret['comment'] = 'infoblox record already created (supplied fields not ensured to match)'
return ret
diff = __salt__['infoblox.diff_objects'](data, obj)
if not diff:
ret['result'] = True
ret['comment'] = 'supplied fields already updated (note: removing fields might not update)'
return ret
if diff:
ret['changes'] = {'diff': diff}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'would attempt to update infoblox record'
return ret
new_obj = __salt__['infoblox.update_object'](obj['_ref'], data=data, **api_opts)
ret['result'] = True
ret['comment'] = 'infoblox record fields updated (note: removing fields might not update)'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'would attempt to create infoblox record {0}'.format(data['name'])
return ret
new_obj_ref = __salt__['infoblox.create_cname'](data=data, **api_opts)
new_obj = __salt__['infoblox.get_cname'](name=name, **api_opts)
ret['result'] = True
ret['comment'] = 'infoblox record created'
ret['changes'] = {'old': 'None', 'new': {'_ref': new_obj_ref, 'data': new_obj}}
return ret
|
saltstack/salt
|
salt/returners/redis_return.py
|
_get_options
|
python
|
def _get_options(ret=None):
'''
Get the redis options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'unix_socket_path': 'unix_socket_path',
'db': 'db',
'password': 'password',
'cluster_mode': 'cluster_mode',
'startup_nodes': 'cluster.startup_nodes',
'skip_full_coverage_check': 'cluster.skip_full_coverage_check',
}
if salt.utils.platform.is_proxy():
return {
'host': __opts__.get('redis.host', 'salt'),
'port': __opts__.get('redis.port', 6379),
'unix_socket_path': __opts__.get('redis.unix_socket_path', None),
'db': __opts__.get('redis.db', '0'),
'password': __opts__.get('redis.password', ''),
'cluster_mode': __opts__.get('redis.cluster_mode', False),
'startup_nodes': __opts__.get('redis.cluster.startup_nodes', {}),
'skip_full_coverage_check': __opts__.get('redis.cluster.skip_full_coverage_check', False)
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
|
Get the redis options from salt.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/redis_return.py#L145-L176
| null |
# -*- coding: utf-8 -*-
'''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
redis.password: ''
.. versionadded:: 2018.3.1
Alternatively a UNIX socket can be specified by `unix_socket_path`:
.. code-block:: yaml
redis.db: '0'
redis.unix_socket_path: /var/run/redis/redis.sock
Cluster Mode Example:
.. code-block:: yaml
redis.db: '0'
redis.cluster_mode: true
redis.cluster.skip_full_coverage_check: true
redis.cluster.startup_nodes:
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.redis.db: '0'
alternative.redis.host: 'salt'
alternative.redis.port: 6379
alternative.redis.password: ''
To use the redis returner, append '--return redis' to the salt command.
.. code-block:: bash
salt '*' test.ping --return redis
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return redis --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return redis --return_kwargs '{"db": "another-salt"}'
Redis Cluster Mode Options:
cluster_mode: ``False``
Whether cluster_mode is enabled or not
cluster.startup_nodes:
A list of host, port dictionaries pointing to cluster members. At least one is required
but multiple nodes are better
.. code-block:: yaml
cache.redis.cluster.startup_nodes
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
cluster.skip_full_coverage_check: ``False``
Some cluster providers restrict certain redis commands such as CONFIG for enhanced security.
Set this option to true to skip checks that required advanced privileges.
.. note::
Most cloud hosted redis clusters will require this to be set to ``True``
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.returners
import salt.utils.jid
import salt.utils.json
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
log = logging.getLogger(__name__)
try:
from rediscluster import StrictRedisCluster
HAS_REDIS_CLUSTER = True
except ImportError:
HAS_REDIS_CLUSTER = False
REDIS_POOL = None
# Define the module's virtual name
__virtualname__ = 'redis'
def __virtual__():
'''
The redis library must be installed for this module to work.
The redis redis cluster library must be installed if cluster_mode is True
'''
if not HAS_REDIS:
return False, 'Could not import redis returner; ' \
'redis python client is not installed.'
if not HAS_REDIS_CLUSTER and _get_options().get('cluster_mode', False):
return (False, "Please install the redis-py-cluster package.")
return __virtualname__
def _get_serv(ret=None):
'''
Return a redis server object
'''
_options = _get_options(ret)
global REDIS_POOL
if REDIS_POOL:
return REDIS_POOL
elif _options.get('cluster_mode'):
REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),
skip_full_coverage_check=_options.get('skip_full_coverage_check'),
decode_responses=True)
else:
REDIS_POOL = redis.StrictRedis(host=_options.get('host'),
port=_options.get('port'),
unix_socket_path=_options.get('unix_socket_path', None),
db=_options.get('db'),
decode_responses=True,
password=_options.get('password'))
return REDIS_POOL
def _get_ttl():
return __opts__.get('keep_jobs', 24) * 3600
def returner(ret):
'''
Return data to a redis data store
'''
serv = _get_serv(ret)
pipeline = serv.pipeline(transaction=False)
minion, jid = ret['id'], ret['jid']
pipeline.hset('ret:{0}'.format(jid), minion, salt.utils.json.dumps(ret))
pipeline.expire('ret:{0}'.format(jid), _get_ttl())
pipeline.set('{0}:{1}'.format(minion, ret['fun']), jid)
pipeline.sadd('minions', minion)
pipeline.execute()
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
serv.setex('load:{0}'.format(jid), _get_ttl(), salt.utils.json.dumps(load))
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
data = serv.get('load:{0}'.format(jid))
if data:
return salt.utils.json.loads(data)
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
ret = {}
for minion, data in six.iteritems(serv.hgetall('ret:{0}'.format(jid))):
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
ret = {}
for minion in serv.smembers('minions'):
ind_str = '{0}:{1}'.format(minion, fun)
try:
jid = serv.get(ind_str)
except Exception:
continue
if not jid:
continue
data = serv.get('{0}:{1}'.format(minion, jid))
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_jids():
'''
Return a dict mapping all job ids to job information
'''
serv = _get_serv(ret=None)
ret = {}
for s in serv.mget(serv.keys('load:*')):
if s is None:
continue
load = salt.utils.json.loads(s)
jid = load['jid']
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
return list(serv.smembers('minions'))
def clean_old_jobs():
'''
Clean out minions's return data for old jobs.
Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually
get cleaned by redis.But for jobs with some very late minion return, the
corresponding hset's TTL will be refreshed to a too late timestamp, we'll
do manually cleaning here.
'''
serv = _get_serv(ret=None)
ret_jids = serv.keys('ret:*')
living_jids = set(serv.keys('load:*'))
to_remove = []
for ret_key in ret_jids:
load_key = ret_key.replace('ret:', 'load:', 1)
if load_key not in living_jids:
to_remove.append(ret_key)
if to_remove:
serv.delete(*to_remove)
log.debug('clean old jobs: %s', to_remove)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/redis_return.py
|
_get_serv
|
python
|
def _get_serv(ret=None):
'''
Return a redis server object
'''
_options = _get_options(ret)
global REDIS_POOL
if REDIS_POOL:
return REDIS_POOL
elif _options.get('cluster_mode'):
REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),
skip_full_coverage_check=_options.get('skip_full_coverage_check'),
decode_responses=True)
else:
REDIS_POOL = redis.StrictRedis(host=_options.get('host'),
port=_options.get('port'),
unix_socket_path=_options.get('unix_socket_path', None),
db=_options.get('db'),
decode_responses=True,
password=_options.get('password'))
return REDIS_POOL
|
Return a redis server object
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/redis_return.py#L179-L198
|
[
"def _get_options(ret=None):\n '''\n Get the redis options from salt.\n '''\n attrs = {'host': 'host',\n 'port': 'port',\n 'unix_socket_path': 'unix_socket_path',\n 'db': 'db',\n 'password': 'password',\n 'cluster_mode': 'cluster_mode',\n 'startup_nodes': 'cluster.startup_nodes',\n 'skip_full_coverage_check': 'cluster.skip_full_coverage_check',\n }\n\n if salt.utils.platform.is_proxy():\n return {\n 'host': __opts__.get('redis.host', 'salt'),\n 'port': __opts__.get('redis.port', 6379),\n 'unix_socket_path': __opts__.get('redis.unix_socket_path', None),\n 'db': __opts__.get('redis.db', '0'),\n 'password': __opts__.get('redis.password', ''),\n 'cluster_mode': __opts__.get('redis.cluster_mode', False),\n 'startup_nodes': __opts__.get('redis.cluster.startup_nodes', {}),\n 'skip_full_coverage_check': __opts__.get('redis.cluster.skip_full_coverage_check', False)\n }\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n return _options\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
redis.password: ''
.. versionadded:: 2018.3.1
Alternatively a UNIX socket can be specified by `unix_socket_path`:
.. code-block:: yaml
redis.db: '0'
redis.unix_socket_path: /var/run/redis/redis.sock
Cluster Mode Example:
.. code-block:: yaml
redis.db: '0'
redis.cluster_mode: true
redis.cluster.skip_full_coverage_check: true
redis.cluster.startup_nodes:
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.redis.db: '0'
alternative.redis.host: 'salt'
alternative.redis.port: 6379
alternative.redis.password: ''
To use the redis returner, append '--return redis' to the salt command.
.. code-block:: bash
salt '*' test.ping --return redis
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return redis --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return redis --return_kwargs '{"db": "another-salt"}'
Redis Cluster Mode Options:
cluster_mode: ``False``
Whether cluster_mode is enabled or not
cluster.startup_nodes:
A list of host, port dictionaries pointing to cluster members. At least one is required
but multiple nodes are better
.. code-block:: yaml
cache.redis.cluster.startup_nodes
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
cluster.skip_full_coverage_check: ``False``
Some cluster providers restrict certain redis commands such as CONFIG for enhanced security.
Set this option to true to skip checks that required advanced privileges.
.. note::
Most cloud hosted redis clusters will require this to be set to ``True``
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.returners
import salt.utils.jid
import salt.utils.json
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
log = logging.getLogger(__name__)
try:
from rediscluster import StrictRedisCluster
HAS_REDIS_CLUSTER = True
except ImportError:
HAS_REDIS_CLUSTER = False
REDIS_POOL = None
# Define the module's virtual name
__virtualname__ = 'redis'
def __virtual__():
'''
The redis library must be installed for this module to work.
The redis redis cluster library must be installed if cluster_mode is True
'''
if not HAS_REDIS:
return False, 'Could not import redis returner; ' \
'redis python client is not installed.'
if not HAS_REDIS_CLUSTER and _get_options().get('cluster_mode', False):
return (False, "Please install the redis-py-cluster package.")
return __virtualname__
def _get_options(ret=None):
'''
Get the redis options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'unix_socket_path': 'unix_socket_path',
'db': 'db',
'password': 'password',
'cluster_mode': 'cluster_mode',
'startup_nodes': 'cluster.startup_nodes',
'skip_full_coverage_check': 'cluster.skip_full_coverage_check',
}
if salt.utils.platform.is_proxy():
return {
'host': __opts__.get('redis.host', 'salt'),
'port': __opts__.get('redis.port', 6379),
'unix_socket_path': __opts__.get('redis.unix_socket_path', None),
'db': __opts__.get('redis.db', '0'),
'password': __opts__.get('redis.password', ''),
'cluster_mode': __opts__.get('redis.cluster_mode', False),
'startup_nodes': __opts__.get('redis.cluster.startup_nodes', {}),
'skip_full_coverage_check': __opts__.get('redis.cluster.skip_full_coverage_check', False)
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_ttl():
return __opts__.get('keep_jobs', 24) * 3600
def returner(ret):
'''
Return data to a redis data store
'''
serv = _get_serv(ret)
pipeline = serv.pipeline(transaction=False)
minion, jid = ret['id'], ret['jid']
pipeline.hset('ret:{0}'.format(jid), minion, salt.utils.json.dumps(ret))
pipeline.expire('ret:{0}'.format(jid), _get_ttl())
pipeline.set('{0}:{1}'.format(minion, ret['fun']), jid)
pipeline.sadd('minions', minion)
pipeline.execute()
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
serv.setex('load:{0}'.format(jid), _get_ttl(), salt.utils.json.dumps(load))
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
data = serv.get('load:{0}'.format(jid))
if data:
return salt.utils.json.loads(data)
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
ret = {}
for minion, data in six.iteritems(serv.hgetall('ret:{0}'.format(jid))):
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
ret = {}
for minion in serv.smembers('minions'):
ind_str = '{0}:{1}'.format(minion, fun)
try:
jid = serv.get(ind_str)
except Exception:
continue
if not jid:
continue
data = serv.get('{0}:{1}'.format(minion, jid))
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_jids():
'''
Return a dict mapping all job ids to job information
'''
serv = _get_serv(ret=None)
ret = {}
for s in serv.mget(serv.keys('load:*')):
if s is None:
continue
load = salt.utils.json.loads(s)
jid = load['jid']
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
return list(serv.smembers('minions'))
def clean_old_jobs():
'''
Clean out minions's return data for old jobs.
Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually
get cleaned by redis.But for jobs with some very late minion return, the
corresponding hset's TTL will be refreshed to a too late timestamp, we'll
do manually cleaning here.
'''
serv = _get_serv(ret=None)
ret_jids = serv.keys('ret:*')
living_jids = set(serv.keys('load:*'))
to_remove = []
for ret_key in ret_jids:
load_key = ret_key.replace('ret:', 'load:', 1)
if load_key not in living_jids:
to_remove.append(ret_key)
if to_remove:
serv.delete(*to_remove)
log.debug('clean old jobs: %s', to_remove)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/redis_return.py
|
returner
|
python
|
def returner(ret):
'''
Return data to a redis data store
'''
serv = _get_serv(ret)
pipeline = serv.pipeline(transaction=False)
minion, jid = ret['id'], ret['jid']
pipeline.hset('ret:{0}'.format(jid), minion, salt.utils.json.dumps(ret))
pipeline.expire('ret:{0}'.format(jid), _get_ttl())
pipeline.set('{0}:{1}'.format(minion, ret['fun']), jid)
pipeline.sadd('minions', minion)
pipeline.execute()
|
Return data to a redis data store
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/redis_return.py#L205-L216
|
[
"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_ttl():\n return __opts__.get('keep_jobs', 24) * 3600\n",
"def _get_serv(ret=None):\n '''\n Return a redis server object\n '''\n _options = _get_options(ret)\n global REDIS_POOL\n if REDIS_POOL:\n return REDIS_POOL\n elif _options.get('cluster_mode'):\n REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),\n skip_full_coverage_check=_options.get('skip_full_coverage_check'),\n decode_responses=True)\n else:\n REDIS_POOL = redis.StrictRedis(host=_options.get('host'),\n port=_options.get('port'),\n unix_socket_path=_options.get('unix_socket_path', None),\n db=_options.get('db'),\n decode_responses=True,\n password=_options.get('password'))\n return REDIS_POOL\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
redis.password: ''
.. versionadded:: 2018.3.1
Alternatively a UNIX socket can be specified by `unix_socket_path`:
.. code-block:: yaml
redis.db: '0'
redis.unix_socket_path: /var/run/redis/redis.sock
Cluster Mode Example:
.. code-block:: yaml
redis.db: '0'
redis.cluster_mode: true
redis.cluster.skip_full_coverage_check: true
redis.cluster.startup_nodes:
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.redis.db: '0'
alternative.redis.host: 'salt'
alternative.redis.port: 6379
alternative.redis.password: ''
To use the redis returner, append '--return redis' to the salt command.
.. code-block:: bash
salt '*' test.ping --return redis
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return redis --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return redis --return_kwargs '{"db": "another-salt"}'
Redis Cluster Mode Options:
cluster_mode: ``False``
Whether cluster_mode is enabled or not
cluster.startup_nodes:
A list of host, port dictionaries pointing to cluster members. At least one is required
but multiple nodes are better
.. code-block:: yaml
cache.redis.cluster.startup_nodes
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
cluster.skip_full_coverage_check: ``False``
Some cluster providers restrict certain redis commands such as CONFIG for enhanced security.
Set this option to true to skip checks that required advanced privileges.
.. note::
Most cloud hosted redis clusters will require this to be set to ``True``
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.returners
import salt.utils.jid
import salt.utils.json
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
log = logging.getLogger(__name__)
try:
from rediscluster import StrictRedisCluster
HAS_REDIS_CLUSTER = True
except ImportError:
HAS_REDIS_CLUSTER = False
REDIS_POOL = None
# Define the module's virtual name
__virtualname__ = 'redis'
def __virtual__():
'''
The redis library must be installed for this module to work.
The redis redis cluster library must be installed if cluster_mode is True
'''
if not HAS_REDIS:
return False, 'Could not import redis returner; ' \
'redis python client is not installed.'
if not HAS_REDIS_CLUSTER and _get_options().get('cluster_mode', False):
return (False, "Please install the redis-py-cluster package.")
return __virtualname__
def _get_options(ret=None):
'''
Get the redis options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'unix_socket_path': 'unix_socket_path',
'db': 'db',
'password': 'password',
'cluster_mode': 'cluster_mode',
'startup_nodes': 'cluster.startup_nodes',
'skip_full_coverage_check': 'cluster.skip_full_coverage_check',
}
if salt.utils.platform.is_proxy():
return {
'host': __opts__.get('redis.host', 'salt'),
'port': __opts__.get('redis.port', 6379),
'unix_socket_path': __opts__.get('redis.unix_socket_path', None),
'db': __opts__.get('redis.db', '0'),
'password': __opts__.get('redis.password', ''),
'cluster_mode': __opts__.get('redis.cluster_mode', False),
'startup_nodes': __opts__.get('redis.cluster.startup_nodes', {}),
'skip_full_coverage_check': __opts__.get('redis.cluster.skip_full_coverage_check', False)
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_serv(ret=None):
'''
Return a redis server object
'''
_options = _get_options(ret)
global REDIS_POOL
if REDIS_POOL:
return REDIS_POOL
elif _options.get('cluster_mode'):
REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),
skip_full_coverage_check=_options.get('skip_full_coverage_check'),
decode_responses=True)
else:
REDIS_POOL = redis.StrictRedis(host=_options.get('host'),
port=_options.get('port'),
unix_socket_path=_options.get('unix_socket_path', None),
db=_options.get('db'),
decode_responses=True,
password=_options.get('password'))
return REDIS_POOL
def _get_ttl():
return __opts__.get('keep_jobs', 24) * 3600
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
serv.setex('load:{0}'.format(jid), _get_ttl(), salt.utils.json.dumps(load))
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
data = serv.get('load:{0}'.format(jid))
if data:
return salt.utils.json.loads(data)
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
ret = {}
for minion, data in six.iteritems(serv.hgetall('ret:{0}'.format(jid))):
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
ret = {}
for minion in serv.smembers('minions'):
ind_str = '{0}:{1}'.format(minion, fun)
try:
jid = serv.get(ind_str)
except Exception:
continue
if not jid:
continue
data = serv.get('{0}:{1}'.format(minion, jid))
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_jids():
'''
Return a dict mapping all job ids to job information
'''
serv = _get_serv(ret=None)
ret = {}
for s in serv.mget(serv.keys('load:*')):
if s is None:
continue
load = salt.utils.json.loads(s)
jid = load['jid']
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
return list(serv.smembers('minions'))
def clean_old_jobs():
'''
Clean out minions's return data for old jobs.
Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually
get cleaned by redis.But for jobs with some very late minion return, the
corresponding hset's TTL will be refreshed to a too late timestamp, we'll
do manually cleaning here.
'''
serv = _get_serv(ret=None)
ret_jids = serv.keys('ret:*')
living_jids = set(serv.keys('load:*'))
to_remove = []
for ret_key in ret_jids:
load_key = ret_key.replace('ret:', 'load:', 1)
if load_key not in living_jids:
to_remove.append(ret_key)
if to_remove:
serv.delete(*to_remove)
log.debug('clean old jobs: %s', to_remove)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/redis_return.py
|
save_load
|
python
|
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
serv.setex('load:{0}'.format(jid), _get_ttl(), salt.utils.json.dumps(load))
|
Save the load to the specified jid
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/redis_return.py#L219-L224
|
[
"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_ttl():\n return __opts__.get('keep_jobs', 24) * 3600\n",
"def _get_serv(ret=None):\n '''\n Return a redis server object\n '''\n _options = _get_options(ret)\n global REDIS_POOL\n if REDIS_POOL:\n return REDIS_POOL\n elif _options.get('cluster_mode'):\n REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),\n skip_full_coverage_check=_options.get('skip_full_coverage_check'),\n decode_responses=True)\n else:\n REDIS_POOL = redis.StrictRedis(host=_options.get('host'),\n port=_options.get('port'),\n unix_socket_path=_options.get('unix_socket_path', None),\n db=_options.get('db'),\n decode_responses=True,\n password=_options.get('password'))\n return REDIS_POOL\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
redis.password: ''
.. versionadded:: 2018.3.1
Alternatively a UNIX socket can be specified by `unix_socket_path`:
.. code-block:: yaml
redis.db: '0'
redis.unix_socket_path: /var/run/redis/redis.sock
Cluster Mode Example:
.. code-block:: yaml
redis.db: '0'
redis.cluster_mode: true
redis.cluster.skip_full_coverage_check: true
redis.cluster.startup_nodes:
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.redis.db: '0'
alternative.redis.host: 'salt'
alternative.redis.port: 6379
alternative.redis.password: ''
To use the redis returner, append '--return redis' to the salt command.
.. code-block:: bash
salt '*' test.ping --return redis
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return redis --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return redis --return_kwargs '{"db": "another-salt"}'
Redis Cluster Mode Options:
cluster_mode: ``False``
Whether cluster_mode is enabled or not
cluster.startup_nodes:
A list of host, port dictionaries pointing to cluster members. At least one is required
but multiple nodes are better
.. code-block:: yaml
cache.redis.cluster.startup_nodes
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
cluster.skip_full_coverage_check: ``False``
Some cluster providers restrict certain redis commands such as CONFIG for enhanced security.
Set this option to true to skip checks that required advanced privileges.
.. note::
Most cloud hosted redis clusters will require this to be set to ``True``
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.returners
import salt.utils.jid
import salt.utils.json
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
log = logging.getLogger(__name__)
try:
from rediscluster import StrictRedisCluster
HAS_REDIS_CLUSTER = True
except ImportError:
HAS_REDIS_CLUSTER = False
REDIS_POOL = None
# Define the module's virtual name
__virtualname__ = 'redis'
def __virtual__():
'''
The redis library must be installed for this module to work.
The redis redis cluster library must be installed if cluster_mode is True
'''
if not HAS_REDIS:
return False, 'Could not import redis returner; ' \
'redis python client is not installed.'
if not HAS_REDIS_CLUSTER and _get_options().get('cluster_mode', False):
return (False, "Please install the redis-py-cluster package.")
return __virtualname__
def _get_options(ret=None):
'''
Get the redis options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'unix_socket_path': 'unix_socket_path',
'db': 'db',
'password': 'password',
'cluster_mode': 'cluster_mode',
'startup_nodes': 'cluster.startup_nodes',
'skip_full_coverage_check': 'cluster.skip_full_coverage_check',
}
if salt.utils.platform.is_proxy():
return {
'host': __opts__.get('redis.host', 'salt'),
'port': __opts__.get('redis.port', 6379),
'unix_socket_path': __opts__.get('redis.unix_socket_path', None),
'db': __opts__.get('redis.db', '0'),
'password': __opts__.get('redis.password', ''),
'cluster_mode': __opts__.get('redis.cluster_mode', False),
'startup_nodes': __opts__.get('redis.cluster.startup_nodes', {}),
'skip_full_coverage_check': __opts__.get('redis.cluster.skip_full_coverage_check', False)
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_serv(ret=None):
'''
Return a redis server object
'''
_options = _get_options(ret)
global REDIS_POOL
if REDIS_POOL:
return REDIS_POOL
elif _options.get('cluster_mode'):
REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),
skip_full_coverage_check=_options.get('skip_full_coverage_check'),
decode_responses=True)
else:
REDIS_POOL = redis.StrictRedis(host=_options.get('host'),
port=_options.get('port'),
unix_socket_path=_options.get('unix_socket_path', None),
db=_options.get('db'),
decode_responses=True,
password=_options.get('password'))
return REDIS_POOL
def _get_ttl():
return __opts__.get('keep_jobs', 24) * 3600
def returner(ret):
'''
Return data to a redis data store
'''
serv = _get_serv(ret)
pipeline = serv.pipeline(transaction=False)
minion, jid = ret['id'], ret['jid']
pipeline.hset('ret:{0}'.format(jid), minion, salt.utils.json.dumps(ret))
pipeline.expire('ret:{0}'.format(jid), _get_ttl())
pipeline.set('{0}:{1}'.format(minion, ret['fun']), jid)
pipeline.sadd('minions', minion)
pipeline.execute()
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
data = serv.get('load:{0}'.format(jid))
if data:
return salt.utils.json.loads(data)
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
ret = {}
for minion, data in six.iteritems(serv.hgetall('ret:{0}'.format(jid))):
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
ret = {}
for minion in serv.smembers('minions'):
ind_str = '{0}:{1}'.format(minion, fun)
try:
jid = serv.get(ind_str)
except Exception:
continue
if not jid:
continue
data = serv.get('{0}:{1}'.format(minion, jid))
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_jids():
'''
Return a dict mapping all job ids to job information
'''
serv = _get_serv(ret=None)
ret = {}
for s in serv.mget(serv.keys('load:*')):
if s is None:
continue
load = salt.utils.json.loads(s)
jid = load['jid']
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
return list(serv.smembers('minions'))
def clean_old_jobs():
'''
Clean out minions's return data for old jobs.
Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually
get cleaned by redis.But for jobs with some very late minion return, the
corresponding hset's TTL will be refreshed to a too late timestamp, we'll
do manually cleaning here.
'''
serv = _get_serv(ret=None)
ret_jids = serv.keys('ret:*')
living_jids = set(serv.keys('load:*'))
to_remove = []
for ret_key in ret_jids:
load_key = ret_key.replace('ret:', 'load:', 1)
if load_key not in living_jids:
to_remove.append(ret_key)
if to_remove:
serv.delete(*to_remove)
log.debug('clean old jobs: %s', to_remove)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/redis_return.py
|
get_load
|
python
|
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
data = serv.get('load:{0}'.format(jid))
if data:
return salt.utils.json.loads(data)
return {}
|
Return the load data that marks a specified jid
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/redis_return.py#L234-L242
|
[
"def _get_serv(ret=None):\n '''\n Return a redis server object\n '''\n _options = _get_options(ret)\n global REDIS_POOL\n if REDIS_POOL:\n return REDIS_POOL\n elif _options.get('cluster_mode'):\n REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),\n skip_full_coverage_check=_options.get('skip_full_coverage_check'),\n decode_responses=True)\n else:\n REDIS_POOL = redis.StrictRedis(host=_options.get('host'),\n port=_options.get('port'),\n unix_socket_path=_options.get('unix_socket_path', None),\n db=_options.get('db'),\n decode_responses=True,\n password=_options.get('password'))\n return REDIS_POOL\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
redis.password: ''
.. versionadded:: 2018.3.1
Alternatively a UNIX socket can be specified by `unix_socket_path`:
.. code-block:: yaml
redis.db: '0'
redis.unix_socket_path: /var/run/redis/redis.sock
Cluster Mode Example:
.. code-block:: yaml
redis.db: '0'
redis.cluster_mode: true
redis.cluster.skip_full_coverage_check: true
redis.cluster.startup_nodes:
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.redis.db: '0'
alternative.redis.host: 'salt'
alternative.redis.port: 6379
alternative.redis.password: ''
To use the redis returner, append '--return redis' to the salt command.
.. code-block:: bash
salt '*' test.ping --return redis
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return redis --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return redis --return_kwargs '{"db": "another-salt"}'
Redis Cluster Mode Options:
cluster_mode: ``False``
Whether cluster_mode is enabled or not
cluster.startup_nodes:
A list of host, port dictionaries pointing to cluster members. At least one is required
but multiple nodes are better
.. code-block:: yaml
cache.redis.cluster.startup_nodes
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
cluster.skip_full_coverage_check: ``False``
Some cluster providers restrict certain redis commands such as CONFIG for enhanced security.
Set this option to true to skip checks that required advanced privileges.
.. note::
Most cloud hosted redis clusters will require this to be set to ``True``
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.returners
import salt.utils.jid
import salt.utils.json
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
log = logging.getLogger(__name__)
try:
from rediscluster import StrictRedisCluster
HAS_REDIS_CLUSTER = True
except ImportError:
HAS_REDIS_CLUSTER = False
REDIS_POOL = None
# Define the module's virtual name
__virtualname__ = 'redis'
def __virtual__():
'''
The redis library must be installed for this module to work.
The redis redis cluster library must be installed if cluster_mode is True
'''
if not HAS_REDIS:
return False, 'Could not import redis returner; ' \
'redis python client is not installed.'
if not HAS_REDIS_CLUSTER and _get_options().get('cluster_mode', False):
return (False, "Please install the redis-py-cluster package.")
return __virtualname__
def _get_options(ret=None):
'''
Get the redis options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'unix_socket_path': 'unix_socket_path',
'db': 'db',
'password': 'password',
'cluster_mode': 'cluster_mode',
'startup_nodes': 'cluster.startup_nodes',
'skip_full_coverage_check': 'cluster.skip_full_coverage_check',
}
if salt.utils.platform.is_proxy():
return {
'host': __opts__.get('redis.host', 'salt'),
'port': __opts__.get('redis.port', 6379),
'unix_socket_path': __opts__.get('redis.unix_socket_path', None),
'db': __opts__.get('redis.db', '0'),
'password': __opts__.get('redis.password', ''),
'cluster_mode': __opts__.get('redis.cluster_mode', False),
'startup_nodes': __opts__.get('redis.cluster.startup_nodes', {}),
'skip_full_coverage_check': __opts__.get('redis.cluster.skip_full_coverage_check', False)
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_serv(ret=None):
'''
Return a redis server object
'''
_options = _get_options(ret)
global REDIS_POOL
if REDIS_POOL:
return REDIS_POOL
elif _options.get('cluster_mode'):
REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),
skip_full_coverage_check=_options.get('skip_full_coverage_check'),
decode_responses=True)
else:
REDIS_POOL = redis.StrictRedis(host=_options.get('host'),
port=_options.get('port'),
unix_socket_path=_options.get('unix_socket_path', None),
db=_options.get('db'),
decode_responses=True,
password=_options.get('password'))
return REDIS_POOL
def _get_ttl():
return __opts__.get('keep_jobs', 24) * 3600
def returner(ret):
'''
Return data to a redis data store
'''
serv = _get_serv(ret)
pipeline = serv.pipeline(transaction=False)
minion, jid = ret['id'], ret['jid']
pipeline.hset('ret:{0}'.format(jid), minion, salt.utils.json.dumps(ret))
pipeline.expire('ret:{0}'.format(jid), _get_ttl())
pipeline.set('{0}:{1}'.format(minion, ret['fun']), jid)
pipeline.sadd('minions', minion)
pipeline.execute()
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
serv.setex('load:{0}'.format(jid), _get_ttl(), salt.utils.json.dumps(load))
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
ret = {}
for minion, data in six.iteritems(serv.hgetall('ret:{0}'.format(jid))):
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
ret = {}
for minion in serv.smembers('minions'):
ind_str = '{0}:{1}'.format(minion, fun)
try:
jid = serv.get(ind_str)
except Exception:
continue
if not jid:
continue
data = serv.get('{0}:{1}'.format(minion, jid))
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_jids():
'''
Return a dict mapping all job ids to job information
'''
serv = _get_serv(ret=None)
ret = {}
for s in serv.mget(serv.keys('load:*')):
if s is None:
continue
load = salt.utils.json.loads(s)
jid = load['jid']
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
return list(serv.smembers('minions'))
def clean_old_jobs():
'''
Clean out minions's return data for old jobs.
Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually
get cleaned by redis.But for jobs with some very late minion return, the
corresponding hset's TTL will be refreshed to a too late timestamp, we'll
do manually cleaning here.
'''
serv = _get_serv(ret=None)
ret_jids = serv.keys('ret:*')
living_jids = set(serv.keys('load:*'))
to_remove = []
for ret_key in ret_jids:
load_key = ret_key.replace('ret:', 'load:', 1)
if load_key not in living_jids:
to_remove.append(ret_key)
if to_remove:
serv.delete(*to_remove)
log.debug('clean old jobs: %s', to_remove)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/redis_return.py
|
get_jid
|
python
|
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
ret = {}
for minion, data in six.iteritems(serv.hgetall('ret:{0}'.format(jid))):
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
|
Return the information returned when the specified job id was executed
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/redis_return.py#L245-L254
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _get_serv(ret=None):\n '''\n Return a redis server object\n '''\n _options = _get_options(ret)\n global REDIS_POOL\n if REDIS_POOL:\n return REDIS_POOL\n elif _options.get('cluster_mode'):\n REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),\n skip_full_coverage_check=_options.get('skip_full_coverage_check'),\n decode_responses=True)\n else:\n REDIS_POOL = redis.StrictRedis(host=_options.get('host'),\n port=_options.get('port'),\n unix_socket_path=_options.get('unix_socket_path', None),\n db=_options.get('db'),\n decode_responses=True,\n password=_options.get('password'))\n return REDIS_POOL\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
redis.password: ''
.. versionadded:: 2018.3.1
Alternatively a UNIX socket can be specified by `unix_socket_path`:
.. code-block:: yaml
redis.db: '0'
redis.unix_socket_path: /var/run/redis/redis.sock
Cluster Mode Example:
.. code-block:: yaml
redis.db: '0'
redis.cluster_mode: true
redis.cluster.skip_full_coverage_check: true
redis.cluster.startup_nodes:
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.redis.db: '0'
alternative.redis.host: 'salt'
alternative.redis.port: 6379
alternative.redis.password: ''
To use the redis returner, append '--return redis' to the salt command.
.. code-block:: bash
salt '*' test.ping --return redis
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return redis --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return redis --return_kwargs '{"db": "another-salt"}'
Redis Cluster Mode Options:
cluster_mode: ``False``
Whether cluster_mode is enabled or not
cluster.startup_nodes:
A list of host, port dictionaries pointing to cluster members. At least one is required
but multiple nodes are better
.. code-block:: yaml
cache.redis.cluster.startup_nodes
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
cluster.skip_full_coverage_check: ``False``
Some cluster providers restrict certain redis commands such as CONFIG for enhanced security.
Set this option to true to skip checks that required advanced privileges.
.. note::
Most cloud hosted redis clusters will require this to be set to ``True``
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.returners
import salt.utils.jid
import salt.utils.json
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
log = logging.getLogger(__name__)
try:
from rediscluster import StrictRedisCluster
HAS_REDIS_CLUSTER = True
except ImportError:
HAS_REDIS_CLUSTER = False
REDIS_POOL = None
# Define the module's virtual name
__virtualname__ = 'redis'
def __virtual__():
'''
The redis library must be installed for this module to work.
The redis redis cluster library must be installed if cluster_mode is True
'''
if not HAS_REDIS:
return False, 'Could not import redis returner; ' \
'redis python client is not installed.'
if not HAS_REDIS_CLUSTER and _get_options().get('cluster_mode', False):
return (False, "Please install the redis-py-cluster package.")
return __virtualname__
def _get_options(ret=None):
'''
Get the redis options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'unix_socket_path': 'unix_socket_path',
'db': 'db',
'password': 'password',
'cluster_mode': 'cluster_mode',
'startup_nodes': 'cluster.startup_nodes',
'skip_full_coverage_check': 'cluster.skip_full_coverage_check',
}
if salt.utils.platform.is_proxy():
return {
'host': __opts__.get('redis.host', 'salt'),
'port': __opts__.get('redis.port', 6379),
'unix_socket_path': __opts__.get('redis.unix_socket_path', None),
'db': __opts__.get('redis.db', '0'),
'password': __opts__.get('redis.password', ''),
'cluster_mode': __opts__.get('redis.cluster_mode', False),
'startup_nodes': __opts__.get('redis.cluster.startup_nodes', {}),
'skip_full_coverage_check': __opts__.get('redis.cluster.skip_full_coverage_check', False)
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_serv(ret=None):
'''
Return a redis server object
'''
_options = _get_options(ret)
global REDIS_POOL
if REDIS_POOL:
return REDIS_POOL
elif _options.get('cluster_mode'):
REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),
skip_full_coverage_check=_options.get('skip_full_coverage_check'),
decode_responses=True)
else:
REDIS_POOL = redis.StrictRedis(host=_options.get('host'),
port=_options.get('port'),
unix_socket_path=_options.get('unix_socket_path', None),
db=_options.get('db'),
decode_responses=True,
password=_options.get('password'))
return REDIS_POOL
def _get_ttl():
return __opts__.get('keep_jobs', 24) * 3600
def returner(ret):
'''
Return data to a redis data store
'''
serv = _get_serv(ret)
pipeline = serv.pipeline(transaction=False)
minion, jid = ret['id'], ret['jid']
pipeline.hset('ret:{0}'.format(jid), minion, salt.utils.json.dumps(ret))
pipeline.expire('ret:{0}'.format(jid), _get_ttl())
pipeline.set('{0}:{1}'.format(minion, ret['fun']), jid)
pipeline.sadd('minions', minion)
pipeline.execute()
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
serv.setex('load:{0}'.format(jid), _get_ttl(), salt.utils.json.dumps(load))
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
data = serv.get('load:{0}'.format(jid))
if data:
return salt.utils.json.loads(data)
return {}
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
ret = {}
for minion in serv.smembers('minions'):
ind_str = '{0}:{1}'.format(minion, fun)
try:
jid = serv.get(ind_str)
except Exception:
continue
if not jid:
continue
data = serv.get('{0}:{1}'.format(minion, jid))
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_jids():
'''
Return a dict mapping all job ids to job information
'''
serv = _get_serv(ret=None)
ret = {}
for s in serv.mget(serv.keys('load:*')):
if s is None:
continue
load = salt.utils.json.loads(s)
jid = load['jid']
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
return list(serv.smembers('minions'))
def clean_old_jobs():
'''
Clean out minions's return data for old jobs.
Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually
get cleaned by redis.But for jobs with some very late minion return, the
corresponding hset's TTL will be refreshed to a too late timestamp, we'll
do manually cleaning here.
'''
serv = _get_serv(ret=None)
ret_jids = serv.keys('ret:*')
living_jids = set(serv.keys('load:*'))
to_remove = []
for ret_key in ret_jids:
load_key = ret_key.replace('ret:', 'load:', 1)
if load_key not in living_jids:
to_remove.append(ret_key)
if to_remove:
serv.delete(*to_remove)
log.debug('clean old jobs: %s', to_remove)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/redis_return.py
|
get_fun
|
python
|
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
serv = _get_serv(ret=None)
ret = {}
for minion in serv.smembers('minions'):
ind_str = '{0}:{1}'.format(minion, fun)
try:
jid = serv.get(ind_str)
except Exception:
continue
if not jid:
continue
data = serv.get('{0}:{1}'.format(minion, jid))
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
|
Return a dict of the last function called for all minions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/redis_return.py#L257-L274
|
[
"def _get_serv(ret=None):\n '''\n Return a redis server object\n '''\n _options = _get_options(ret)\n global REDIS_POOL\n if REDIS_POOL:\n return REDIS_POOL\n elif _options.get('cluster_mode'):\n REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),\n skip_full_coverage_check=_options.get('skip_full_coverage_check'),\n decode_responses=True)\n else:\n REDIS_POOL = redis.StrictRedis(host=_options.get('host'),\n port=_options.get('port'),\n unix_socket_path=_options.get('unix_socket_path', None),\n db=_options.get('db'),\n decode_responses=True,\n password=_options.get('password'))\n return REDIS_POOL\n"
] |
# -*- coding: utf-8 -*-
'''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
.. code-block:: yaml
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
redis.password: ''
.. versionadded:: 2018.3.1
Alternatively a UNIX socket can be specified by `unix_socket_path`:
.. code-block:: yaml
redis.db: '0'
redis.unix_socket_path: /var/run/redis/redis.sock
Cluster Mode Example:
.. code-block:: yaml
redis.db: '0'
redis.cluster_mode: true
redis.cluster.skip_full_coverage_check: true
redis.cluster.startup_nodes:
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.redis.db: '0'
alternative.redis.host: 'salt'
alternative.redis.port: 6379
alternative.redis.password: ''
To use the redis returner, append '--return redis' to the salt command.
.. code-block:: bash
salt '*' test.ping --return redis
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return redis --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return redis --return_kwargs '{"db": "another-salt"}'
Redis Cluster Mode Options:
cluster_mode: ``False``
Whether cluster_mode is enabled or not
cluster.startup_nodes:
A list of host, port dictionaries pointing to cluster members. At least one is required
but multiple nodes are better
.. code-block:: yaml
cache.redis.cluster.startup_nodes
- host: redis-member-1
port: 6379
- host: redis-member-2
port: 6379
cluster.skip_full_coverage_check: ``False``
Some cluster providers restrict certain redis commands such as CONFIG for enhanced security.
Set this option to true to skip checks that required advanced privileges.
.. note::
Most cloud hosted redis clusters will require this to be set to ``True``
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.returners
import salt.utils.jid
import salt.utils.json
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
log = logging.getLogger(__name__)
try:
from rediscluster import StrictRedisCluster
HAS_REDIS_CLUSTER = True
except ImportError:
HAS_REDIS_CLUSTER = False
REDIS_POOL = None
# Define the module's virtual name
__virtualname__ = 'redis'
def __virtual__():
'''
The redis library must be installed for this module to work.
The redis redis cluster library must be installed if cluster_mode is True
'''
if not HAS_REDIS:
return False, 'Could not import redis returner; ' \
'redis python client is not installed.'
if not HAS_REDIS_CLUSTER and _get_options().get('cluster_mode', False):
return (False, "Please install the redis-py-cluster package.")
return __virtualname__
def _get_options(ret=None):
'''
Get the redis options from salt.
'''
attrs = {'host': 'host',
'port': 'port',
'unix_socket_path': 'unix_socket_path',
'db': 'db',
'password': 'password',
'cluster_mode': 'cluster_mode',
'startup_nodes': 'cluster.startup_nodes',
'skip_full_coverage_check': 'cluster.skip_full_coverage_check',
}
if salt.utils.platform.is_proxy():
return {
'host': __opts__.get('redis.host', 'salt'),
'port': __opts__.get('redis.port', 6379),
'unix_socket_path': __opts__.get('redis.unix_socket_path', None),
'db': __opts__.get('redis.db', '0'),
'password': __opts__.get('redis.password', ''),
'cluster_mode': __opts__.get('redis.cluster_mode', False),
'startup_nodes': __opts__.get('redis.cluster.startup_nodes', {}),
'skip_full_coverage_check': __opts__.get('redis.cluster.skip_full_coverage_check', False)
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
def _get_serv(ret=None):
'''
Return a redis server object
'''
_options = _get_options(ret)
global REDIS_POOL
if REDIS_POOL:
return REDIS_POOL
elif _options.get('cluster_mode'):
REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),
skip_full_coverage_check=_options.get('skip_full_coverage_check'),
decode_responses=True)
else:
REDIS_POOL = redis.StrictRedis(host=_options.get('host'),
port=_options.get('port'),
unix_socket_path=_options.get('unix_socket_path', None),
db=_options.get('db'),
decode_responses=True,
password=_options.get('password'))
return REDIS_POOL
def _get_ttl():
return __opts__.get('keep_jobs', 24) * 3600
def returner(ret):
'''
Return data to a redis data store
'''
serv = _get_serv(ret)
pipeline = serv.pipeline(transaction=False)
minion, jid = ret['id'], ret['jid']
pipeline.hset('ret:{0}'.format(jid), minion, salt.utils.json.dumps(ret))
pipeline.expire('ret:{0}'.format(jid), _get_ttl())
pipeline.set('{0}:{1}'.format(minion, ret['fun']), jid)
pipeline.sadd('minions', minion)
pipeline.execute()
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
serv.setex('load:{0}'.format(jid), _get_ttl(), salt.utils.json.dumps(load))
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
serv = _get_serv(ret=None)
data = serv.get('load:{0}'.format(jid))
if data:
return salt.utils.json.loads(data)
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
serv = _get_serv(ret=None)
ret = {}
for minion, data in six.iteritems(serv.hgetall('ret:{0}'.format(jid))):
if data:
ret[minion] = salt.utils.json.loads(data)
return ret
def get_jids():
'''
Return a dict mapping all job ids to job information
'''
serv = _get_serv(ret=None)
ret = {}
for s in serv.mget(serv.keys('load:*')):
if s is None:
continue
load = salt.utils.json.loads(s)
jid = load['jid']
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
serv = _get_serv(ret=None)
return list(serv.smembers('minions'))
def clean_old_jobs():
'''
Clean out minions's return data for old jobs.
Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually
get cleaned by redis.But for jobs with some very late minion return, the
corresponding hset's TTL will be refreshed to a too late timestamp, we'll
do manually cleaning here.
'''
serv = _get_serv(ret=None)
ret_jids = serv.keys('ret:*')
living_jids = set(serv.keys('load:*'))
to_remove = []
for ret_key in ret_jids:
load_key = ret_key.replace('ret:', 'load:', 1)
if load_key not in living_jids:
to_remove.append(ret_key)
if to_remove:
serv.delete(*to_remove)
log.debug('clean old jobs: %s', to_remove)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.