repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/modules/boto_ec2.py | _get_all_eip_addresses | def _get_all_eip_addresses(addresses=None, allocation_ids=None, region=None,
key=None, keyid=None, profile=None):
'''
Get all EIP's associated with the current credentials.
addresses
(list) - Optional list of addresses. If provided, only those those in the
list will be returned.
allocation_ids
(list) - Optional list of allocation IDs. If provided, only the
addresses associated with the given allocation IDs will be returned.
returns
(list) - The requested Addresses as a list of :class:`boto.ec2.address.Address`
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.get_all_addresses(addresses=addresses, allocation_ids=allocation_ids)
except boto.exception.BotoServerError as e:
log.error(e)
return [] | python | def _get_all_eip_addresses(addresses=None, allocation_ids=None, region=None,
key=None, keyid=None, profile=None):
'''
Get all EIP's associated with the current credentials.
addresses
(list) - Optional list of addresses. If provided, only those those in the
list will be returned.
allocation_ids
(list) - Optional list of allocation IDs. If provided, only the
addresses associated with the given allocation IDs will be returned.
returns
(list) - The requested Addresses as a list of :class:`boto.ec2.address.Address`
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.get_all_addresses(addresses=addresses, allocation_ids=allocation_ids)
except boto.exception.BotoServerError as e:
log.error(e)
return [] | [
"def",
"_get_all_eip_addresses",
"(",
"addresses",
"=",
"None",
",",
"allocation_ids",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"r... | Get all EIP's associated with the current credentials.
addresses
(list) - Optional list of addresses. If provided, only those those in the
list will be returned.
allocation_ids
(list) - Optional list of allocation IDs. If provided, only the
addresses associated with the given allocation IDs will be returned.
returns
(list) - The requested Addresses as a list of :class:`boto.ec2.address.Address` | [
"Get",
"all",
"EIP",
"s",
"associated",
"with",
"the",
"current",
"credentials",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L99-L120 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_all_eip_addresses | def get_all_eip_addresses(addresses=None, allocation_ids=None, region=None,
key=None, keyid=None, profile=None):
'''
Get public addresses of some, or all EIPs associated with the current account.
addresses
(list) - Optional list of addresses. If provided, only the addresses
associated with those in the list will be returned.
allocation_ids
(list) - Optional list of allocation IDs. If provided, only the
addresses associated with the given allocation IDs will be returned.
returns
(list) - A list of the requested EIP addresses
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_all_eip_addresses
.. versionadded:: 2016.3.0
'''
return [x.public_ip for x in _get_all_eip_addresses(addresses, allocation_ids, region,
key, keyid, profile)] | python | def get_all_eip_addresses(addresses=None, allocation_ids=None, region=None,
key=None, keyid=None, profile=None):
'''
Get public addresses of some, or all EIPs associated with the current account.
addresses
(list) - Optional list of addresses. If provided, only the addresses
associated with those in the list will be returned.
allocation_ids
(list) - Optional list of allocation IDs. If provided, only the
addresses associated with the given allocation IDs will be returned.
returns
(list) - A list of the requested EIP addresses
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_all_eip_addresses
.. versionadded:: 2016.3.0
'''
return [x.public_ip for x in _get_all_eip_addresses(addresses, allocation_ids, region,
key, keyid, profile)] | [
"def",
"get_all_eip_addresses",
"(",
"addresses",
"=",
"None",
",",
"allocation_ids",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"return",
"[",
"x",
".",
"public_i... | Get public addresses of some, or all EIPs associated with the current account.
addresses
(list) - Optional list of addresses. If provided, only the addresses
associated with those in the list will be returned.
allocation_ids
(list) - Optional list of allocation IDs. If provided, only the
addresses associated with the given allocation IDs will be returned.
returns
(list) - A list of the requested EIP addresses
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_all_eip_addresses
.. versionadded:: 2016.3.0 | [
"Get",
"public",
"addresses",
"of",
"some",
"or",
"all",
"EIPs",
"associated",
"with",
"the",
"current",
"account",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L123-L147 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_unassociated_eip_address | def get_unassociated_eip_address(domain='standard', region=None, key=None,
keyid=None, profile=None):
'''
Return the first unassociated EIP
domain
Indicates whether the address is an EC2 address or a VPC address
(standard|vpc).
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_unassociated_eip_address
.. versionadded:: 2016.3.0
'''
eip = None
for address in get_all_eip_addresses(region=region, key=key, keyid=keyid,
profile=profile):
address_info = get_eip_address_info(addresses=address, region=region,
key=key, keyid=keyid,
profile=profile)[0]
if address_info['instance_id']:
log.debug('%s is already associated with the instance %s',
address, address_info['instance_id'])
continue
if address_info['network_interface_id']:
log.debug('%s is already associated with the network interface %s',
address, address_info['network_interface_id'])
continue
if address_info['domain'] == domain:
log.debug(
"The first unassociated EIP address in the domain '%s' is %s",
domain, address
)
eip = address
break
if not eip:
log.debug('No unassociated Elastic IP found!')
return eip | python | def get_unassociated_eip_address(domain='standard', region=None, key=None,
keyid=None, profile=None):
'''
Return the first unassociated EIP
domain
Indicates whether the address is an EC2 address or a VPC address
(standard|vpc).
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_unassociated_eip_address
.. versionadded:: 2016.3.0
'''
eip = None
for address in get_all_eip_addresses(region=region, key=key, keyid=keyid,
profile=profile):
address_info = get_eip_address_info(addresses=address, region=region,
key=key, keyid=keyid,
profile=profile)[0]
if address_info['instance_id']:
log.debug('%s is already associated with the instance %s',
address, address_info['instance_id'])
continue
if address_info['network_interface_id']:
log.debug('%s is already associated with the network interface %s',
address, address_info['network_interface_id'])
continue
if address_info['domain'] == domain:
log.debug(
"The first unassociated EIP address in the domain '%s' is %s",
domain, address
)
eip = address
break
if not eip:
log.debug('No unassociated Elastic IP found!')
return eip | [
"def",
"get_unassociated_eip_address",
"(",
"domain",
"=",
"'standard'",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"eip",
"=",
"None",
"for",
"address",
"in",
"get_all_eip_address... | Return the first unassociated EIP
domain
Indicates whether the address is an EC2 address or a VPC address
(standard|vpc).
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_unassociated_eip_address
.. versionadded:: 2016.3.0 | [
"Return",
"the",
"first",
"unassociated",
"EIP"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L150-L194 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_eip_address_info | def get_eip_address_info(addresses=None, allocation_ids=None, region=None, key=None,
keyid=None, profile=None):
'''
Get 'interesting' info about some, or all EIPs associated with the current account.
addresses
(list) - Optional list of addresses. If provided, only the addresses
associated with those in the list will be returned.
allocation_ids
(list) - Optional list of allocation IDs. If provided, only the
addresses associated with the given allocation IDs will be returned.
returns
(list of dicts) - A list of dicts, each containing the info for one of the requested EIPs.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_eip_address_info addresses=52.4.2.15
.. versionadded:: 2016.3.0
'''
if type(addresses) == (type('string')):
addresses = [addresses]
if type(allocation_ids) == (type('string')):
allocation_ids = [allocation_ids]
ret = _get_all_eip_addresses(addresses=addresses, allocation_ids=allocation_ids,
region=region, key=key, keyid=keyid, profile=profile)
interesting = ['allocation_id', 'association_id', 'domain', 'instance_id',
'network_interface_id', 'network_interface_owner_id', 'public_ip',
'private_ip_address']
return [dict([(x, getattr(address, x)) for x in interesting]) for address in ret] | python | def get_eip_address_info(addresses=None, allocation_ids=None, region=None, key=None,
keyid=None, profile=None):
'''
Get 'interesting' info about some, or all EIPs associated with the current account.
addresses
(list) - Optional list of addresses. If provided, only the addresses
associated with those in the list will be returned.
allocation_ids
(list) - Optional list of allocation IDs. If provided, only the
addresses associated with the given allocation IDs will be returned.
returns
(list of dicts) - A list of dicts, each containing the info for one of the requested EIPs.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_eip_address_info addresses=52.4.2.15
.. versionadded:: 2016.3.0
'''
if type(addresses) == (type('string')):
addresses = [addresses]
if type(allocation_ids) == (type('string')):
allocation_ids = [allocation_ids]
ret = _get_all_eip_addresses(addresses=addresses, allocation_ids=allocation_ids,
region=region, key=key, keyid=keyid, profile=profile)
interesting = ['allocation_id', 'association_id', 'domain', 'instance_id',
'network_interface_id', 'network_interface_owner_id', 'public_ip',
'private_ip_address']
return [dict([(x, getattr(address, x)) for x in interesting]) for address in ret] | [
"def",
"get_eip_address_info",
"(",
"addresses",
"=",
"None",
",",
"allocation_ids",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"type",
"(",
"addresses",
")"... | Get 'interesting' info about some, or all EIPs associated with the current account.
addresses
(list) - Optional list of addresses. If provided, only the addresses
associated with those in the list will be returned.
allocation_ids
(list) - Optional list of allocation IDs. If provided, only the
addresses associated with the given allocation IDs will be returned.
returns
(list of dicts) - A list of dicts, each containing the info for one of the requested EIPs.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_eip_address_info addresses=52.4.2.15
.. versionadded:: 2016.3.0 | [
"Get",
"interesting",
"info",
"about",
"some",
"or",
"all",
"EIPs",
"associated",
"with",
"the",
"current",
"account",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L197-L232 | train |
saltstack/salt | salt/modules/boto_ec2.py | allocate_eip_address | def allocate_eip_address(domain=None, region=None, key=None, keyid=None, profile=None):
'''
Allocate a new Elastic IP address and associate it with your account.
domain
(string) Optional param - if set to exactly 'vpc', the address will be
allocated to the VPC. The default simply maps the EIP to your
account container.
returns
(dict) dict of 'interesting' information about the newly allocated EIP,
with probably the most interesting keys being 'public_ip'; and
'allocation_id' iff 'domain=vpc' was passed.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.allocate_eip_address domain=vpc
.. versionadded:: 2016.3.0
'''
if domain and domain != 'vpc':
raise SaltInvocationError('The only permitted value for the \'domain\' param is \'vpc\'.')
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
address = conn.allocate_address(domain=domain)
except boto.exception.BotoServerError as e:
log.error(e)
return False
interesting = ['allocation_id', 'association_id', 'domain', 'instance_id',
'network_interface_id', 'network_interface_owner_id', 'public_ip',
'private_ip_address']
return dict([(x, getattr(address, x)) for x in interesting]) | python | def allocate_eip_address(domain=None, region=None, key=None, keyid=None, profile=None):
'''
Allocate a new Elastic IP address and associate it with your account.
domain
(string) Optional param - if set to exactly 'vpc', the address will be
allocated to the VPC. The default simply maps the EIP to your
account container.
returns
(dict) dict of 'interesting' information about the newly allocated EIP,
with probably the most interesting keys being 'public_ip'; and
'allocation_id' iff 'domain=vpc' was passed.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.allocate_eip_address domain=vpc
.. versionadded:: 2016.3.0
'''
if domain and domain != 'vpc':
raise SaltInvocationError('The only permitted value for the \'domain\' param is \'vpc\'.')
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
address = conn.allocate_address(domain=domain)
except boto.exception.BotoServerError as e:
log.error(e)
return False
interesting = ['allocation_id', 'association_id', 'domain', 'instance_id',
'network_interface_id', 'network_interface_owner_id', 'public_ip',
'private_ip_address']
return dict([(x, getattr(address, x)) for x in interesting]) | [
"def",
"allocate_eip_address",
"(",
"domain",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"domain",
"and",
"domain",
"!=",
"'vpc'",
":",
"raise",
"SaltInvocat... | Allocate a new Elastic IP address and associate it with your account.
domain
(string) Optional param - if set to exactly 'vpc', the address will be
allocated to the VPC. The default simply maps the EIP to your
account container.
returns
(dict) dict of 'interesting' information about the newly allocated EIP,
with probably the most interesting keys being 'public_ip'; and
'allocation_id' iff 'domain=vpc' was passed.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.allocate_eip_address domain=vpc
.. versionadded:: 2016.3.0 | [
"Allocate",
"a",
"new",
"Elastic",
"IP",
"address",
"and",
"associate",
"it",
"with",
"your",
"account",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L235-L272 | train |
saltstack/salt | salt/modules/boto_ec2.py | release_eip_address | def release_eip_address(public_ip=None, allocation_id=None, region=None, key=None,
keyid=None, profile=None):
'''
Free an Elastic IP address. Pass either a public IP address to release an
EC2 Classic EIP, or an AllocationId to release a VPC EIP.
public_ip
(string) - The public IP address - for EC2 elastic IPs.
allocation_id
(string) - The Allocation ID - for VPC elastic IPs.
returns
(bool) - True on success, False on failure
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.release_eip_address allocation_id=eipalloc-ef382c8a
.. versionadded:: 2016.3.0
'''
if not salt.utils.data.exactly_one((public_ip, allocation_id)):
raise SaltInvocationError("Exactly one of 'public_ip' OR "
"'allocation_id' must be provided")
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.release_address(public_ip, allocation_id)
except boto.exception.BotoServerError as e:
log.error(e)
return False | python | def release_eip_address(public_ip=None, allocation_id=None, region=None, key=None,
keyid=None, profile=None):
'''
Free an Elastic IP address. Pass either a public IP address to release an
EC2 Classic EIP, or an AllocationId to release a VPC EIP.
public_ip
(string) - The public IP address - for EC2 elastic IPs.
allocation_id
(string) - The Allocation ID - for VPC elastic IPs.
returns
(bool) - True on success, False on failure
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.release_eip_address allocation_id=eipalloc-ef382c8a
.. versionadded:: 2016.3.0
'''
if not salt.utils.data.exactly_one((public_ip, allocation_id)):
raise SaltInvocationError("Exactly one of 'public_ip' OR "
"'allocation_id' must be provided")
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.release_address(public_ip, allocation_id)
except boto.exception.BotoServerError as e:
log.error(e)
return False | [
"def",
"release_eip_address",
"(",
"public_ip",
"=",
"None",
",",
"allocation_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"not",
"salt",
".",
"utils",
... | Free an Elastic IP address. Pass either a public IP address to release an
EC2 Classic EIP, or an AllocationId to release a VPC EIP.
public_ip
(string) - The public IP address - for EC2 elastic IPs.
allocation_id
(string) - The Allocation ID - for VPC elastic IPs.
returns
(bool) - True on success, False on failure
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.release_eip_address allocation_id=eipalloc-ef382c8a
.. versionadded:: 2016.3.0 | [
"Free",
"an",
"Elastic",
"IP",
"address",
".",
"Pass",
"either",
"a",
"public",
"IP",
"address",
"to",
"release",
"an",
"EC2",
"Classic",
"EIP",
"or",
"an",
"AllocationId",
"to",
"release",
"a",
"VPC",
"EIP",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L275-L307 | train |
saltstack/salt | salt/modules/boto_ec2.py | associate_eip_address | def associate_eip_address(instance_id=None, instance_name=None, public_ip=None,
allocation_id=None, network_interface_id=None,
network_interface_name=None, private_ip_address=None,
allow_reassociation=False, region=None, key=None,
keyid=None, profile=None):
'''
Associate an Elastic IP address with a currently running instance or a network interface.
This requires exactly one of either 'public_ip' or 'allocation_id', depending
on whether you’re associating a VPC address or a plain EC2 address.
instance_id
(string) – ID of the instance to associate with (exclusive with 'instance_name')
instance_name
(string) – Name tag of the instance to associate with (exclusive with 'instance_id')
public_ip
(string) – Public IP address, for standard EC2 based allocations.
allocation_id
(string) – Allocation ID for a VPC-based EIP.
network_interface_id
(string) - ID of the network interface to associate the EIP with
network_interface_name
(string) - Name of the network interface to associate the EIP with
private_ip_address
(string) – The primary or secondary private IP address to associate with the Elastic IP address.
allow_reassociation
(bool) – Allow a currently associated EIP to be re-associated with the new instance or interface.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.associate_eip_address instance_name=bubba.ho.tep allocation_id=eipalloc-ef382c8a
.. versionadded:: 2016.3.0
'''
if not salt.utils.data.exactly_one((instance_id, instance_name,
network_interface_id,
network_interface_name)):
raise SaltInvocationError("Exactly one of 'instance_id', "
"'instance_name', 'network_interface_id', "
"'network_interface_name' must be provided")
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if instance_name:
try:
instance_id = get_id(name=instance_name, region=region, key=key,
keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.error(e)
return False
if not instance_id:
log.error(
"Given instance_name '%s' cannot be mapped to an instance_id",
instance_name
)
return False
if network_interface_name:
try:
network_interface_id = get_network_interface_id(
network_interface_name, region=region, key=key, keyid=keyid,
profile=profile)
except boto.exception.BotoServerError as e:
log.error(e)
return False
if not network_interface_id:
log.error("Given network_interface_name '%s' cannot be mapped to "
"an network_interface_id", network_interface_name)
return False
try:
return conn.associate_address(instance_id=instance_id,
public_ip=public_ip,
allocation_id=allocation_id,
network_interface_id=network_interface_id,
private_ip_address=private_ip_address,
allow_reassociation=allow_reassociation)
except boto.exception.BotoServerError as e:
log.error(e)
return False | python | def associate_eip_address(instance_id=None, instance_name=None, public_ip=None,
allocation_id=None, network_interface_id=None,
network_interface_name=None, private_ip_address=None,
allow_reassociation=False, region=None, key=None,
keyid=None, profile=None):
'''
Associate an Elastic IP address with a currently running instance or a network interface.
This requires exactly one of either 'public_ip' or 'allocation_id', depending
on whether you’re associating a VPC address or a plain EC2 address.
instance_id
(string) – ID of the instance to associate with (exclusive with 'instance_name')
instance_name
(string) – Name tag of the instance to associate with (exclusive with 'instance_id')
public_ip
(string) – Public IP address, for standard EC2 based allocations.
allocation_id
(string) – Allocation ID for a VPC-based EIP.
network_interface_id
(string) - ID of the network interface to associate the EIP with
network_interface_name
(string) - Name of the network interface to associate the EIP with
private_ip_address
(string) – The primary or secondary private IP address to associate with the Elastic IP address.
allow_reassociation
(bool) – Allow a currently associated EIP to be re-associated with the new instance or interface.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.associate_eip_address instance_name=bubba.ho.tep allocation_id=eipalloc-ef382c8a
.. versionadded:: 2016.3.0
'''
if not salt.utils.data.exactly_one((instance_id, instance_name,
network_interface_id,
network_interface_name)):
raise SaltInvocationError("Exactly one of 'instance_id', "
"'instance_name', 'network_interface_id', "
"'network_interface_name' must be provided")
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if instance_name:
try:
instance_id = get_id(name=instance_name, region=region, key=key,
keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.error(e)
return False
if not instance_id:
log.error(
"Given instance_name '%s' cannot be mapped to an instance_id",
instance_name
)
return False
if network_interface_name:
try:
network_interface_id = get_network_interface_id(
network_interface_name, region=region, key=key, keyid=keyid,
profile=profile)
except boto.exception.BotoServerError as e:
log.error(e)
return False
if not network_interface_id:
log.error("Given network_interface_name '%s' cannot be mapped to "
"an network_interface_id", network_interface_name)
return False
try:
return conn.associate_address(instance_id=instance_id,
public_ip=public_ip,
allocation_id=allocation_id,
network_interface_id=network_interface_id,
private_ip_address=private_ip_address,
allow_reassociation=allow_reassociation)
except boto.exception.BotoServerError as e:
log.error(e)
return False | [
"def",
"associate_eip_address",
"(",
"instance_id",
"=",
"None",
",",
"instance_name",
"=",
"None",
",",
"public_ip",
"=",
"None",
",",
"allocation_id",
"=",
"None",
",",
"network_interface_id",
"=",
"None",
",",
"network_interface_name",
"=",
"None",
",",
"priv... | Associate an Elastic IP address with a currently running instance or a network interface.
This requires exactly one of either 'public_ip' or 'allocation_id', depending
on whether you’re associating a VPC address or a plain EC2 address.
instance_id
(string) – ID of the instance to associate with (exclusive with 'instance_name')
instance_name
(string) – Name tag of the instance to associate with (exclusive with 'instance_id')
public_ip
(string) – Public IP address, for standard EC2 based allocations.
allocation_id
(string) – Allocation ID for a VPC-based EIP.
network_interface_id
(string) - ID of the network interface to associate the EIP with
network_interface_name
(string) - Name of the network interface to associate the EIP with
private_ip_address
(string) – The primary or secondary private IP address to associate with the Elastic IP address.
allow_reassociation
(bool) – Allow a currently associated EIP to be re-associated with the new instance or interface.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.associate_eip_address instance_name=bubba.ho.tep allocation_id=eipalloc-ef382c8a
.. versionadded:: 2016.3.0 | [
"Associate",
"an",
"Elastic",
"IP",
"address",
"with",
"a",
"currently",
"running",
"instance",
"or",
"a",
"network",
"interface",
".",
"This",
"requires",
"exactly",
"one",
"of",
"either",
"public_ip",
"or",
"allocation_id",
"depending",
"on",
"whether",
"you’r... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L310-L393 | train |
saltstack/salt | salt/modules/boto_ec2.py | disassociate_eip_address | def disassociate_eip_address(public_ip=None, association_id=None, region=None,
key=None, keyid=None, profile=None):
'''
Disassociate an Elastic IP address from a currently running instance. This
requires exactly one of either 'association_id' or 'public_ip', depending
on whether you’re dealing with a VPC or EC2 Classic address.
public_ip
(string) – Public IP address, for EC2 Classic allocations.
association_id
(string) – Association ID for a VPC-bound EIP.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.disassociate_eip_address association_id=eipassoc-e3ba2d16
.. versionadded:: 2016.3.0
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.disassociate_address(public_ip, association_id)
except boto.exception.BotoServerError as e:
log.error(e)
return False | python | def disassociate_eip_address(public_ip=None, association_id=None, region=None,
key=None, keyid=None, profile=None):
'''
Disassociate an Elastic IP address from a currently running instance. This
requires exactly one of either 'association_id' or 'public_ip', depending
on whether you’re dealing with a VPC or EC2 Classic address.
public_ip
(string) – Public IP address, for EC2 Classic allocations.
association_id
(string) – Association ID for a VPC-bound EIP.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.disassociate_eip_address association_id=eipassoc-e3ba2d16
.. versionadded:: 2016.3.0
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.disassociate_address(public_ip, association_id)
except boto.exception.BotoServerError as e:
log.error(e)
return False | [
"def",
"disassociate_eip_address",
"(",
"public_ip",
"=",
"None",
",",
"association_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
... | Disassociate an Elastic IP address from a currently running instance. This
requires exactly one of either 'association_id' or 'public_ip', depending
on whether you’re dealing with a VPC or EC2 Classic address.
public_ip
(string) – Public IP address, for EC2 Classic allocations.
association_id
(string) – Association ID for a VPC-bound EIP.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.disassociate_eip_address association_id=eipassoc-e3ba2d16
.. versionadded:: 2016.3.0 | [
"Disassociate",
"an",
"Elastic",
"IP",
"address",
"from",
"a",
"currently",
"running",
"instance",
".",
"This",
"requires",
"exactly",
"one",
"of",
"either",
"association_id",
"or",
"public_ip",
"depending",
"on",
"whether",
"you’re",
"dealing",
"with",
"a",
"VP... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L396-L425 | train |
saltstack/salt | salt/modules/boto_ec2.py | assign_private_ip_addresses | def assign_private_ip_addresses(network_interface_name=None, network_interface_id=None,
private_ip_addresses=None, secondary_private_ip_address_count=None,
allow_reassignment=False, region=None, key=None,
keyid=None, profile=None):
'''
Assigns one or more secondary private IP addresses to a network interface.
network_interface_id
(string) - ID of the network interface to associate the IP with (exclusive with 'network_interface_name')
network_interface_name
(string) - Name of the network interface to associate the IP with (exclusive with 'network_interface_id')
private_ip_addresses
(list) - Assigns the specified IP addresses as secondary IP addresses to the network interface (exclusive with 'secondary_private_ip_address_count')
secondary_private_ip_address_count
(int) - The number of secondary IP addresses to assign to the network interface. (exclusive with 'private_ip_addresses')
allow_reassociation
(bool) – Allow a currently associated EIP to be re-associated with the new instance or interface.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.assign_private_ip_addresses network_interface_name=my_eni private_ip_addresses=private_ip
salt myminion boto_ec2.assign_private_ip_addresses network_interface_name=my_eni secondary_private_ip_address_count=2
.. versionadded:: 2017.7.0
'''
if not salt.utils.data.exactly_one((network_interface_name,
network_interface_id)):
raise SaltInvocationError("Exactly one of 'network_interface_name', "
"'network_interface_id' must be provided")
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if network_interface_name:
try:
network_interface_id = get_network_interface_id(
network_interface_name, region=region, key=key, keyid=keyid,
profile=profile)
except boto.exception.BotoServerError as e:
log.error(e)
return False
if not network_interface_id:
log.error("Given network_interface_name '%s' cannot be mapped to "
"an network_interface_id", network_interface_name)
return False
try:
return conn.assign_private_ip_addresses(network_interface_id=network_interface_id,
private_ip_addresses=private_ip_addresses,
secondary_private_ip_address_count=secondary_private_ip_address_count,
allow_reassignment=allow_reassignment)
except boto.exception.BotoServerError as e:
log.error(e)
return False | python | def assign_private_ip_addresses(network_interface_name=None, network_interface_id=None,
private_ip_addresses=None, secondary_private_ip_address_count=None,
allow_reassignment=False, region=None, key=None,
keyid=None, profile=None):
'''
Assigns one or more secondary private IP addresses to a network interface.
network_interface_id
(string) - ID of the network interface to associate the IP with (exclusive with 'network_interface_name')
network_interface_name
(string) - Name of the network interface to associate the IP with (exclusive with 'network_interface_id')
private_ip_addresses
(list) - Assigns the specified IP addresses as secondary IP addresses to the network interface (exclusive with 'secondary_private_ip_address_count')
secondary_private_ip_address_count
(int) - The number of secondary IP addresses to assign to the network interface. (exclusive with 'private_ip_addresses')
allow_reassociation
(bool) – Allow a currently associated EIP to be re-associated with the new instance or interface.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.assign_private_ip_addresses network_interface_name=my_eni private_ip_addresses=private_ip
salt myminion boto_ec2.assign_private_ip_addresses network_interface_name=my_eni secondary_private_ip_address_count=2
.. versionadded:: 2017.7.0
'''
if not salt.utils.data.exactly_one((network_interface_name,
network_interface_id)):
raise SaltInvocationError("Exactly one of 'network_interface_name', "
"'network_interface_id' must be provided")
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if network_interface_name:
try:
network_interface_id = get_network_interface_id(
network_interface_name, region=region, key=key, keyid=keyid,
profile=profile)
except boto.exception.BotoServerError as e:
log.error(e)
return False
if not network_interface_id:
log.error("Given network_interface_name '%s' cannot be mapped to "
"an network_interface_id", network_interface_name)
return False
try:
return conn.assign_private_ip_addresses(network_interface_id=network_interface_id,
private_ip_addresses=private_ip_addresses,
secondary_private_ip_address_count=secondary_private_ip_address_count,
allow_reassignment=allow_reassignment)
except boto.exception.BotoServerError as e:
log.error(e)
return False | [
"def",
"assign_private_ip_addresses",
"(",
"network_interface_name",
"=",
"None",
",",
"network_interface_id",
"=",
"None",
",",
"private_ip_addresses",
"=",
"None",
",",
"secondary_private_ip_address_count",
"=",
"None",
",",
"allow_reassignment",
"=",
"False",
",",
"r... | Assigns one or more secondary private IP addresses to a network interface.
network_interface_id
(string) - ID of the network interface to associate the IP with (exclusive with 'network_interface_name')
network_interface_name
(string) - Name of the network interface to associate the IP with (exclusive with 'network_interface_id')
private_ip_addresses
(list) - Assigns the specified IP addresses as secondary IP addresses to the network interface (exclusive with 'secondary_private_ip_address_count')
secondary_private_ip_address_count
(int) - The number of secondary IP addresses to assign to the network interface. (exclusive with 'private_ip_addresses')
allow_reassociation
(bool) – Allow a currently associated EIP to be re-associated with the new instance or interface.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.assign_private_ip_addresses network_interface_name=my_eni private_ip_addresses=private_ip
salt myminion boto_ec2.assign_private_ip_addresses network_interface_name=my_eni secondary_private_ip_address_count=2
.. versionadded:: 2017.7.0 | [
"Assigns",
"one",
"or",
"more",
"secondary",
"private",
"IP",
"addresses",
"to",
"a",
"network",
"interface",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L428-L485 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_zones | def get_zones(region=None, key=None, keyid=None, profile=None):
'''
Get a list of AZs for the configured region.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_zones
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
return [z.name for z in conn.get_all_zones()] | python | def get_zones(region=None, key=None, keyid=None, profile=None):
'''
Get a list of AZs for the configured region.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_zones
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
return [z.name for z in conn.get_all_zones()] | [
"def",
"get_zones",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
... | Get a list of AZs for the configured region.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_zones | [
"Get",
"a",
"list",
"of",
"AZs",
"for",
"the",
"configured",
"region",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L540-L552 | train |
saltstack/salt | salt/modules/boto_ec2.py | find_instances | def find_instances(instance_id=None, name=None, tags=None, region=None,
key=None, keyid=None, profile=None, return_objs=False,
in_states=None, filters=None):
'''
Given instance properties, find and return matching instance ids
CLI Examples:
.. code-block:: bash
salt myminion boto_ec2.find_instances # Lists all instances
salt myminion boto_ec2.find_instances name=myinstance
salt myminion boto_ec2.find_instances tags='{"mytag": "value"}'
salt myminion boto_ec2.find_instances filters='{"vpc-id": "vpc-12345678"}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
filter_parameters = {'filters': {}}
if instance_id:
filter_parameters['instance_ids'] = [instance_id]
if name:
filter_parameters['filters']['tag:Name'] = name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
if filters:
filter_parameters['filters'].update(filters)
reservations = conn.get_all_reservations(**filter_parameters)
instances = [i for r in reservations for i in r.instances]
log.debug('The filters criteria %s matched the following '
'instances:%s', filter_parameters, instances)
if in_states:
instances = [i for i in instances if i.state in in_states]
log.debug(
'Limiting instance matches to those in the requested states: %s',
instances
)
if instances:
if return_objs:
return instances
return [instance.id for instance in instances]
else:
return []
except boto.exception.BotoServerError as exc:
log.error(exc)
return [] | python | def find_instances(instance_id=None, name=None, tags=None, region=None,
key=None, keyid=None, profile=None, return_objs=False,
in_states=None, filters=None):
'''
Given instance properties, find and return matching instance ids
CLI Examples:
.. code-block:: bash
salt myminion boto_ec2.find_instances # Lists all instances
salt myminion boto_ec2.find_instances name=myinstance
salt myminion boto_ec2.find_instances tags='{"mytag": "value"}'
salt myminion boto_ec2.find_instances filters='{"vpc-id": "vpc-12345678"}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
filter_parameters = {'filters': {}}
if instance_id:
filter_parameters['instance_ids'] = [instance_id]
if name:
filter_parameters['filters']['tag:Name'] = name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
if filters:
filter_parameters['filters'].update(filters)
reservations = conn.get_all_reservations(**filter_parameters)
instances = [i for r in reservations for i in r.instances]
log.debug('The filters criteria %s matched the following '
'instances:%s', filter_parameters, instances)
if in_states:
instances = [i for i in instances if i.state in in_states]
log.debug(
'Limiting instance matches to those in the requested states: %s',
instances
)
if instances:
if return_objs:
return instances
return [instance.id for instance in instances]
else:
return []
except boto.exception.BotoServerError as exc:
log.error(exc)
return [] | [
"def",
"find_instances",
"(",
"instance_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"return_objs",
"=",
"False... | Given instance properties, find and return matching instance ids
CLI Examples:
.. code-block:: bash
salt myminion boto_ec2.find_instances # Lists all instances
salt myminion boto_ec2.find_instances name=myinstance
salt myminion boto_ec2.find_instances tags='{"mytag": "value"}'
salt myminion boto_ec2.find_instances filters='{"vpc-id": "vpc-12345678"}' | [
"Given",
"instance",
"properties",
"find",
"and",
"return",
"matching",
"instance",
"ids"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L555-L609 | train |
saltstack/salt | salt/modules/boto_ec2.py | create_image | def create_image(ami_name, instance_id=None, instance_name=None, tags=None, region=None,
key=None, keyid=None, profile=None, description=None, no_reboot=False,
dry_run=False, filters=None):
'''
Given instance properties that define exactly one instance, create AMI and return AMI-id.
CLI Examples:
.. code-block:: bash
salt myminion boto_ec2.create_image ami_name instance_name=myinstance
salt myminion boto_ec2.create_image another_ami_name tags='{"mytag": "value"}' description='this is my ami'
'''
instances = find_instances(instance_id=instance_id, name=instance_name, tags=tags,
region=region, key=key, keyid=keyid, profile=profile,
return_objs=True, filters=filters)
if not instances:
log.error('Source instance not found')
return False
if len(instances) > 1:
log.error('Multiple instances found, must match exactly only one instance to create an image from')
return False
instance = instances[0]
try:
return instance.create_image(ami_name, description=description,
no_reboot=no_reboot, dry_run=dry_run)
except boto.exception.BotoServerError as exc:
log.error(exc)
return False | python | def create_image(ami_name, instance_id=None, instance_name=None, tags=None, region=None,
key=None, keyid=None, profile=None, description=None, no_reboot=False,
dry_run=False, filters=None):
'''
Given instance properties that define exactly one instance, create AMI and return AMI-id.
CLI Examples:
.. code-block:: bash
salt myminion boto_ec2.create_image ami_name instance_name=myinstance
salt myminion boto_ec2.create_image another_ami_name tags='{"mytag": "value"}' description='this is my ami'
'''
instances = find_instances(instance_id=instance_id, name=instance_name, tags=tags,
region=region, key=key, keyid=keyid, profile=profile,
return_objs=True, filters=filters)
if not instances:
log.error('Source instance not found')
return False
if len(instances) > 1:
log.error('Multiple instances found, must match exactly only one instance to create an image from')
return False
instance = instances[0]
try:
return instance.create_image(ami_name, description=description,
no_reboot=no_reboot, dry_run=dry_run)
except boto.exception.BotoServerError as exc:
log.error(exc)
return False | [
"def",
"create_image",
"(",
"ami_name",
",",
"instance_id",
"=",
"None",
",",
"instance_name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"d... | Given instance properties that define exactly one instance, create AMI and return AMI-id.
CLI Examples:
.. code-block:: bash
salt myminion boto_ec2.create_image ami_name instance_name=myinstance
salt myminion boto_ec2.create_image another_ami_name tags='{"mytag": "value"}' description='this is my ami' | [
"Given",
"instance",
"properties",
"that",
"define",
"exactly",
"one",
"instance",
"create",
"AMI",
"and",
"return",
"AMI",
"-",
"id",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L612-L644 | train |
saltstack/salt | salt/modules/boto_ec2.py | find_images | def find_images(ami_name=None, executable_by=None, owners=None, image_ids=None, tags=None,
region=None, key=None, keyid=None, profile=None, return_objs=False):
'''
Given image properties, find and return matching AMI ids
CLI Examples:
.. code-block:: bash
salt myminion boto_ec2.find_images tags='{"mytag": "value"}'
'''
retries = 30
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
while retries:
try:
filter_parameters = {'filters': {}}
if image_ids:
filter_parameters['image_ids'] = [image_ids]
if executable_by:
filter_parameters['executable_by'] = [executable_by]
if owners:
filter_parameters['owners'] = [owners]
if ami_name:
filter_parameters['filters']['name'] = ami_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
images = conn.get_all_images(**filter_parameters)
log.debug('The filters criteria %s matched the following '
'images:%s', filter_parameters, images)
if images:
if return_objs:
return images
return [image.id for image in images]
else:
return False
except boto.exception.BotoServerError as exc:
if exc.error_code == 'Throttling':
log.debug("Throttled by AWS API, will retry in 5 seconds...")
time.sleep(5)
retries -= 1
continue
log.error('Failed to convert AMI name `%s` to an AMI ID: %s', ami_name, exc)
return False
return False | python | def find_images(ami_name=None, executable_by=None, owners=None, image_ids=None, tags=None,
region=None, key=None, keyid=None, profile=None, return_objs=False):
'''
Given image properties, find and return matching AMI ids
CLI Examples:
.. code-block:: bash
salt myminion boto_ec2.find_images tags='{"mytag": "value"}'
'''
retries = 30
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
while retries:
try:
filter_parameters = {'filters': {}}
if image_ids:
filter_parameters['image_ids'] = [image_ids]
if executable_by:
filter_parameters['executable_by'] = [executable_by]
if owners:
filter_parameters['owners'] = [owners]
if ami_name:
filter_parameters['filters']['name'] = ami_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
images = conn.get_all_images(**filter_parameters)
log.debug('The filters criteria %s matched the following '
'images:%s', filter_parameters, images)
if images:
if return_objs:
return images
return [image.id for image in images]
else:
return False
except boto.exception.BotoServerError as exc:
if exc.error_code == 'Throttling':
log.debug("Throttled by AWS API, will retry in 5 seconds...")
time.sleep(5)
retries -= 1
continue
log.error('Failed to convert AMI name `%s` to an AMI ID: %s', ami_name, exc)
return False
return False | [
"def",
"find_images",
"(",
"ami_name",
"=",
"None",
",",
"executable_by",
"=",
"None",
",",
"owners",
"=",
"None",
",",
"image_ids",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None"... | Given image properties, find and return matching AMI ids
CLI Examples:
.. code-block:: bash
salt myminion boto_ec2.find_images tags='{"mytag": "value"}' | [
"Given",
"image",
"properties",
"find",
"and",
"return",
"matching",
"AMI",
"ids"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L647-L693 | train |
saltstack/salt | salt/modules/boto_ec2.py | terminate | def terminate(instance_id=None, name=None, region=None,
key=None, keyid=None, profile=None, filters=None):
'''
Terminate the instance described by instance_id or name.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.terminate name=myinstance
salt myminion boto_ec2.terminate instance_id=i-a46b9f
'''
instances = find_instances(instance_id=instance_id, name=name,
region=region, key=key, keyid=keyid,
profile=profile, return_objs=True,
filters=filters)
if instances in (False, None, []):
return instances
if len(instances) == 1:
instances[0].terminate()
return True
else:
log.warning('Refusing to terminate multiple instances at once')
return False | python | def terminate(instance_id=None, name=None, region=None,
key=None, keyid=None, profile=None, filters=None):
'''
Terminate the instance described by instance_id or name.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.terminate name=myinstance
salt myminion boto_ec2.terminate instance_id=i-a46b9f
'''
instances = find_instances(instance_id=instance_id, name=name,
region=region, key=key, keyid=keyid,
profile=profile, return_objs=True,
filters=filters)
if instances in (False, None, []):
return instances
if len(instances) == 1:
instances[0].terminate()
return True
else:
log.warning('Refusing to terminate multiple instances at once')
return False | [
"def",
"terminate",
"(",
"instance_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":",
"instances",
"=",
"fi... | Terminate the instance described by instance_id or name.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.terminate name=myinstance
salt myminion boto_ec2.terminate instance_id=i-a46b9f | [
"Terminate",
"the",
"instance",
"described",
"by",
"instance_id",
"or",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L696-L720 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_id | def get_id(name=None, tags=None, region=None, key=None,
keyid=None, profile=None, in_states=None, filters=None):
'''
Given instance properties, return the instance id if it exists.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_id myinstance
'''
instance_ids = find_instances(name=name, tags=tags, region=region, key=key,
keyid=keyid, profile=profile, in_states=in_states,
filters=filters)
if instance_ids:
log.info("Instance ids: %s", " ".join(instance_ids))
if len(instance_ids) == 1:
return instance_ids[0]
else:
raise CommandExecutionError('Found more than one instance '
'matching the criteria.')
else:
log.warning('Could not find instance.')
return None | python | def get_id(name=None, tags=None, region=None, key=None,
keyid=None, profile=None, in_states=None, filters=None):
'''
Given instance properties, return the instance id if it exists.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_id myinstance
'''
instance_ids = find_instances(name=name, tags=tags, region=region, key=key,
keyid=keyid, profile=profile, in_states=in_states,
filters=filters)
if instance_ids:
log.info("Instance ids: %s", " ".join(instance_ids))
if len(instance_ids) == 1:
return instance_ids[0]
else:
raise CommandExecutionError('Found more than one instance '
'matching the criteria.')
else:
log.warning('Could not find instance.')
return None | [
"def",
"get_id",
"(",
"name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"in_states",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":"... | Given instance properties, return the instance id if it exists.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_id myinstance | [
"Given",
"instance",
"properties",
"return",
"the",
"instance",
"id",
"if",
"it",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L723-L748 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_tags | def get_tags(instance_id=None, keyid=None, key=None, profile=None,
region=None):
'''
Given an instance_id, return a list of tags associated with that instance.
returns
(list) - list of tags as key/value pairs
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_tags instance_id
'''
tags = []
client = _get_conn(key=key, keyid=keyid, profile=profile, region=region)
result = client.get_all_tags(filters={"resource-id": instance_id})
if result:
for tag in result:
tags.append({tag.name: tag.value})
else:
log.info("No tags found for instance_id %s", instance_id)
return tags | python | def get_tags(instance_id=None, keyid=None, key=None, profile=None,
region=None):
'''
Given an instance_id, return a list of tags associated with that instance.
returns
(list) - list of tags as key/value pairs
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_tags instance_id
'''
tags = []
client = _get_conn(key=key, keyid=keyid, profile=profile, region=region)
result = client.get_all_tags(filters={"resource-id": instance_id})
if result:
for tag in result:
tags.append({tag.name: tag.value})
else:
log.info("No tags found for instance_id %s", instance_id)
return tags | [
"def",
"get_tags",
"(",
"instance_id",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"key",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"region",
"=",
"None",
")",
":",
"tags",
"=",
"[",
"]",
"client",
"=",
"_get_conn",
"(",
"key",
"=",
"key",
... | Given an instance_id, return a list of tags associated with that instance.
returns
(list) - list of tags as key/value pairs
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_tags instance_id | [
"Given",
"an",
"instance_id",
"return",
"a",
"list",
"of",
"tags",
"associated",
"with",
"that",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L751-L773 | train |
saltstack/salt | salt/modules/boto_ec2.py | exists | def exists(instance_id=None, name=None, tags=None, region=None, key=None,
keyid=None, profile=None, in_states=None, filters=None):
'''
Given an instance id, check to see if the given instance id exists.
Returns True if the given instance with the given id, name, or tags
exists; otherwise, False is returned.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.exists myinstance
'''
instances = find_instances(instance_id=instance_id, name=name, tags=tags,
region=region, key=key, keyid=keyid,
profile=profile, in_states=in_states, filters=filters)
if instances:
log.info('Instance exists.')
return True
else:
log.warning('Instance does not exist.')
return False | python | def exists(instance_id=None, name=None, tags=None, region=None, key=None,
keyid=None, profile=None, in_states=None, filters=None):
'''
Given an instance id, check to see if the given instance id exists.
Returns True if the given instance with the given id, name, or tags
exists; otherwise, False is returned.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.exists myinstance
'''
instances = find_instances(instance_id=instance_id, name=name, tags=tags,
region=region, key=key, keyid=keyid,
profile=profile, in_states=in_states, filters=filters)
if instances:
log.info('Instance exists.')
return True
else:
log.warning('Instance does not exist.')
return False | [
"def",
"exists",
"(",
"instance_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"in_states",
"=",
"None",
",",
... | Given an instance id, check to see if the given instance id exists.
Returns True if the given instance with the given id, name, or tags
exists; otherwise, False is returned.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.exists myinstance | [
"Given",
"an",
"instance",
"id",
"check",
"to",
"see",
"if",
"the",
"given",
"instance",
"id",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L776-L798 | train |
saltstack/salt | salt/modules/boto_ec2.py | _to_blockdev_map | def _to_blockdev_map(thing):
'''
Convert a string, or a json payload, or a dict in the right
format, into a boto.ec2.blockdevicemapping.BlockDeviceMapping as
needed by instance_present(). The following YAML is a direct
representation of what is expected by the underlying boto EC2 code.
YAML example:
.. code-block:: yaml
device-maps:
/dev/sdb:
ephemeral_name: ephemeral0
/dev/sdc:
ephemeral_name: ephemeral1
/dev/sdd:
ephemeral_name: ephemeral2
/dev/sde:
ephemeral_name: ephemeral3
/dev/sdf:
size: 20
volume_type: gp2
'''
if not thing:
return None
if isinstance(thing, BlockDeviceMapping):
return thing
if isinstance(thing, six.string_types):
thing = salt.utils.json.loads(thing)
if not isinstance(thing, dict):
log.error("Can't convert '%s' of type %s to a "
"boto.ec2.blockdevicemapping.BlockDeviceMapping", thing, type(thing))
return None
bdm = BlockDeviceMapping()
for d, t in six.iteritems(thing):
bdt = BlockDeviceType(ephemeral_name=t.get('ephemeral_name'),
no_device=t.get('no_device', False),
volume_id=t.get('volume_id'),
snapshot_id=t.get('snapshot_id'),
status=t.get('status'),
attach_time=t.get('attach_time'),
delete_on_termination=t.get('delete_on_termination', False),
size=t.get('size'),
volume_type=t.get('volume_type'),
iops=t.get('iops'),
encrypted=t.get('encrypted'))
bdm[d] = bdt
return bdm | python | def _to_blockdev_map(thing):
'''
Convert a string, or a json payload, or a dict in the right
format, into a boto.ec2.blockdevicemapping.BlockDeviceMapping as
needed by instance_present(). The following YAML is a direct
representation of what is expected by the underlying boto EC2 code.
YAML example:
.. code-block:: yaml
device-maps:
/dev/sdb:
ephemeral_name: ephemeral0
/dev/sdc:
ephemeral_name: ephemeral1
/dev/sdd:
ephemeral_name: ephemeral2
/dev/sde:
ephemeral_name: ephemeral3
/dev/sdf:
size: 20
volume_type: gp2
'''
if not thing:
return None
if isinstance(thing, BlockDeviceMapping):
return thing
if isinstance(thing, six.string_types):
thing = salt.utils.json.loads(thing)
if not isinstance(thing, dict):
log.error("Can't convert '%s' of type %s to a "
"boto.ec2.blockdevicemapping.BlockDeviceMapping", thing, type(thing))
return None
bdm = BlockDeviceMapping()
for d, t in six.iteritems(thing):
bdt = BlockDeviceType(ephemeral_name=t.get('ephemeral_name'),
no_device=t.get('no_device', False),
volume_id=t.get('volume_id'),
snapshot_id=t.get('snapshot_id'),
status=t.get('status'),
attach_time=t.get('attach_time'),
delete_on_termination=t.get('delete_on_termination', False),
size=t.get('size'),
volume_type=t.get('volume_type'),
iops=t.get('iops'),
encrypted=t.get('encrypted'))
bdm[d] = bdt
return bdm | [
"def",
"_to_blockdev_map",
"(",
"thing",
")",
":",
"if",
"not",
"thing",
":",
"return",
"None",
"if",
"isinstance",
"(",
"thing",
",",
"BlockDeviceMapping",
")",
":",
"return",
"thing",
"if",
"isinstance",
"(",
"thing",
",",
"six",
".",
"string_types",
")"... | Convert a string, or a json payload, or a dict in the right
format, into a boto.ec2.blockdevicemapping.BlockDeviceMapping as
needed by instance_present(). The following YAML is a direct
representation of what is expected by the underlying boto EC2 code.
YAML example:
.. code-block:: yaml
device-maps:
/dev/sdb:
ephemeral_name: ephemeral0
/dev/sdc:
ephemeral_name: ephemeral1
/dev/sdd:
ephemeral_name: ephemeral2
/dev/sde:
ephemeral_name: ephemeral3
/dev/sdf:
size: 20
volume_type: gp2 | [
"Convert",
"a",
"string",
"or",
"a",
"json",
"payload",
"or",
"a",
"dict",
"in",
"the",
"right",
"format",
"into",
"a",
"boto",
".",
"ec2",
".",
"blockdevicemapping",
".",
"BlockDeviceMapping",
"as",
"needed",
"by",
"instance_present",
"()",
".",
"The",
"f... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L801-L851 | train |
saltstack/salt | salt/modules/boto_ec2.py | run | def run(image_id, name=None, tags=None, key_name=None, security_groups=None,
user_data=None, instance_type='m1.small', placement=None,
kernel_id=None, ramdisk_id=None, monitoring_enabled=None, vpc_id=None,
vpc_name=None, subnet_id=None, subnet_name=None, private_ip_address=None,
block_device_map=None, disable_api_termination=None,
instance_initiated_shutdown_behavior=None, placement_group=None,
client_token=None, security_group_ids=None, security_group_names=None,
additional_info=None, tenancy=None, instance_profile_arn=None,
instance_profile_name=None, ebs_optimized=None,
network_interface_id=None, network_interface_name=None,
region=None, key=None, keyid=None, profile=None, network_interfaces=None):
#TODO: support multi-instance reservations
'''
Create and start an EC2 instance.
Returns True if the instance was created; otherwise False.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.run ami-b80c2b87 name=myinstance
image_id
(string) – The ID of the image to run.
name
(string) - The name of the instance.
tags
(dict of key: value pairs) - tags to apply to the instance.
key_name
(string) – The name of the key pair with which to launch instances.
security_groups
(list of strings) – The names of the EC2 classic security groups with
which to associate instances
user_data
(string) – The Base64-encoded MIME user data to be made available to the
instance(s) in this reservation.
instance_type
(string) – The type of instance to run. Note that some image types
(e.g. hvm) only run on some instance types.
placement
(string) – The Availability Zone to launch the instance into.
kernel_id
(string) – The ID of the kernel with which to launch the instances.
ramdisk_id
(string) – The ID of the RAM disk with which to launch the instances.
monitoring_enabled
(bool) – Enable detailed CloudWatch monitoring on the instance.
vpc_id
(string) - ID of a VPC to bind the instance to. Exclusive with vpc_name.
vpc_name
(string) - Name of a VPC to bind the instance to. Exclusive with vpc_id.
subnet_id
(string) – The subnet ID within which to launch the instances for VPC.
subnet_name
(string) – The name of a subnet within which to launch the instances for VPC.
private_ip_address
(string) – If you’re using VPC, you can optionally use this parameter to
assign the instance a specific available IP address from the subnet
(e.g. 10.0.0.25).
block_device_map
(boto.ec2.blockdevicemapping.BlockDeviceMapping) – A BlockDeviceMapping
data structure describing the EBS volumes associated with the Image.
(string) - A string representation of a BlockDeviceMapping structure
(dict) - A dict describing a BlockDeviceMapping structure
YAML example:
.. code-block:: yaml
device-maps:
/dev/sdb:
ephemeral_name: ephemeral0
/dev/sdc:
ephemeral_name: ephemeral1
/dev/sdd:
ephemeral_name: ephemeral2
/dev/sde:
ephemeral_name: ephemeral3
/dev/sdf:
size: 20
volume_type: gp2
disable_api_termination
(bool) – If True, the instances will be locked and will not be able to
be terminated via the API.
instance_initiated_shutdown_behavior
(string) – Specifies whether the instance stops or terminates on
instance-initiated shutdown. Valid values are: stop, terminate
placement_group
(string) – If specified, this is the name of the placement group in
which the instance(s) will be launched.
client_token
(string) – Unique, case-sensitive identifier you provide to ensure
idempotency of the request. Maximum 64 ASCII characters.
security_group_ids
(list of strings) – The ID(s) of the VPC security groups with which to
associate instances.
security_group_names
(list of strings) – The name(s) of the VPC security groups with which to
associate instances.
additional_info
(string) – Specifies additional information to make available to the
instance(s).
tenancy
(string) – The tenancy of the instance you want to launch. An instance
with a tenancy of ‘dedicated’ runs on single-tenant hardware and can
only be launched into a VPC. Valid values are:”default” or “dedicated”.
NOTE: To use dedicated tenancy you MUST specify a VPC subnet-ID as well.
instance_profile_arn
(string) – The Amazon resource name (ARN) of the IAM Instance Profile
(IIP) to associate with the instances.
instance_profile_name
(string) – The name of the IAM Instance Profile (IIP) to associate with
the instances.
ebs_optimized
(bool) – Whether the instance is optimized for EBS I/O. This
optimization provides dedicated throughput to Amazon EBS and an
optimized configuration stack to provide optimal EBS I/O performance.
This optimization isn’t available with all instance types.
network_interfaces
(boto.ec2.networkinterface.NetworkInterfaceCollection) – A
NetworkInterfaceCollection data structure containing the ENI
specifications for the instance.
network_interface_id
(string) - ID of the network interface to attach to the instance
network_interface_name
(string) - Name of the network interface to attach to the instance
'''
if all((subnet_id, subnet_name)):
raise SaltInvocationError('Only one of subnet_name or subnet_id may be '
'provided.')
if subnet_name:
r = __salt__['boto_vpc.get_resource_id']('subnet', subnet_name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'id' not in r:
log.warning('Couldn\'t resolve subnet name %s.', subnet_name)
return False
subnet_id = r['id']
if all((security_group_ids, security_group_names)):
raise SaltInvocationError('Only one of security_group_ids or '
'security_group_names may be provided.')
if security_group_names:
security_group_ids = []
for sgn in security_group_names:
r = __salt__['boto_secgroup.get_group_id'](sgn, vpc_name=vpc_name,
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
log.warning('Couldn\'t resolve security group name %s', sgn)
return False
security_group_ids += [r]
network_interface_args = list(map(int, [network_interface_id is not None,
network_interface_name is not None,
network_interfaces is not None]))
if sum(network_interface_args) > 1:
raise SaltInvocationError('Only one of network_interface_id, '
'network_interface_name or '
'network_interfaces may be provided.')
if network_interface_name:
result = get_network_interface_id(network_interface_name,
region=region, key=key,
keyid=keyid,
profile=profile)
network_interface_id = result['result']
if not network_interface_id:
log.warning(
"Given network_interface_name '%s' cannot be mapped to an "
"network_interface_id", network_interface_name
)
if network_interface_id:
interface = NetworkInterfaceSpecification(
network_interface_id=network_interface_id,
device_index=0)
else:
interface = NetworkInterfaceSpecification(
subnet_id=subnet_id,
groups=security_group_ids,
device_index=0)
if network_interfaces:
interfaces_specs = [NetworkInterfaceSpecification(**x) for x in network_interfaces]
interfaces = NetworkInterfaceCollection(*interfaces_specs)
else:
interfaces = NetworkInterfaceCollection(interface)
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
reservation = conn.run_instances(image_id, key_name=key_name, security_groups=security_groups,
user_data=user_data, instance_type=instance_type,
placement=placement, kernel_id=kernel_id, ramdisk_id=ramdisk_id,
monitoring_enabled=monitoring_enabled,
private_ip_address=private_ip_address,
block_device_map=_to_blockdev_map(block_device_map),
disable_api_termination=disable_api_termination,
instance_initiated_shutdown_behavior=instance_initiated_shutdown_behavior,
placement_group=placement_group, client_token=client_token,
additional_info=additional_info,
tenancy=tenancy, instance_profile_arn=instance_profile_arn,
instance_profile_name=instance_profile_name, ebs_optimized=ebs_optimized,
network_interfaces=interfaces)
if not reservation:
log.warning('Instance could not be reserved')
return False
instance = reservation.instances[0]
status = 'pending'
while status == 'pending':
time.sleep(5)
status = instance.update()
if status == 'running':
if name:
instance.add_tag('Name', name)
if tags:
instance.add_tags(tags)
return {'instance_id': instance.id}
else:
log.warning(
'Instance could not be started -- status is "%s"',
status
) | python | def run(image_id, name=None, tags=None, key_name=None, security_groups=None,
user_data=None, instance_type='m1.small', placement=None,
kernel_id=None, ramdisk_id=None, monitoring_enabled=None, vpc_id=None,
vpc_name=None, subnet_id=None, subnet_name=None, private_ip_address=None,
block_device_map=None, disable_api_termination=None,
instance_initiated_shutdown_behavior=None, placement_group=None,
client_token=None, security_group_ids=None, security_group_names=None,
additional_info=None, tenancy=None, instance_profile_arn=None,
instance_profile_name=None, ebs_optimized=None,
network_interface_id=None, network_interface_name=None,
region=None, key=None, keyid=None, profile=None, network_interfaces=None):
#TODO: support multi-instance reservations
'''
Create and start an EC2 instance.
Returns True if the instance was created; otherwise False.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.run ami-b80c2b87 name=myinstance
image_id
(string) – The ID of the image to run.
name
(string) - The name of the instance.
tags
(dict of key: value pairs) - tags to apply to the instance.
key_name
(string) – The name of the key pair with which to launch instances.
security_groups
(list of strings) – The names of the EC2 classic security groups with
which to associate instances
user_data
(string) – The Base64-encoded MIME user data to be made available to the
instance(s) in this reservation.
instance_type
(string) – The type of instance to run. Note that some image types
(e.g. hvm) only run on some instance types.
placement
(string) – The Availability Zone to launch the instance into.
kernel_id
(string) – The ID of the kernel with which to launch the instances.
ramdisk_id
(string) – The ID of the RAM disk with which to launch the instances.
monitoring_enabled
(bool) – Enable detailed CloudWatch monitoring on the instance.
vpc_id
(string) - ID of a VPC to bind the instance to. Exclusive with vpc_name.
vpc_name
(string) - Name of a VPC to bind the instance to. Exclusive with vpc_id.
subnet_id
(string) – The subnet ID within which to launch the instances for VPC.
subnet_name
(string) – The name of a subnet within which to launch the instances for VPC.
private_ip_address
(string) – If you’re using VPC, you can optionally use this parameter to
assign the instance a specific available IP address from the subnet
(e.g. 10.0.0.25).
block_device_map
(boto.ec2.blockdevicemapping.BlockDeviceMapping) – A BlockDeviceMapping
data structure describing the EBS volumes associated with the Image.
(string) - A string representation of a BlockDeviceMapping structure
(dict) - A dict describing a BlockDeviceMapping structure
YAML example:
.. code-block:: yaml
device-maps:
/dev/sdb:
ephemeral_name: ephemeral0
/dev/sdc:
ephemeral_name: ephemeral1
/dev/sdd:
ephemeral_name: ephemeral2
/dev/sde:
ephemeral_name: ephemeral3
/dev/sdf:
size: 20
volume_type: gp2
disable_api_termination
(bool) – If True, the instances will be locked and will not be able to
be terminated via the API.
instance_initiated_shutdown_behavior
(string) – Specifies whether the instance stops or terminates on
instance-initiated shutdown. Valid values are: stop, terminate
placement_group
(string) – If specified, this is the name of the placement group in
which the instance(s) will be launched.
client_token
(string) – Unique, case-sensitive identifier you provide to ensure
idempotency of the request. Maximum 64 ASCII characters.
security_group_ids
(list of strings) – The ID(s) of the VPC security groups with which to
associate instances.
security_group_names
(list of strings) – The name(s) of the VPC security groups with which to
associate instances.
additional_info
(string) – Specifies additional information to make available to the
instance(s).
tenancy
(string) – The tenancy of the instance you want to launch. An instance
with a tenancy of ‘dedicated’ runs on single-tenant hardware and can
only be launched into a VPC. Valid values are:”default” or “dedicated”.
NOTE: To use dedicated tenancy you MUST specify a VPC subnet-ID as well.
instance_profile_arn
(string) – The Amazon resource name (ARN) of the IAM Instance Profile
(IIP) to associate with the instances.
instance_profile_name
(string) – The name of the IAM Instance Profile (IIP) to associate with
the instances.
ebs_optimized
(bool) – Whether the instance is optimized for EBS I/O. This
optimization provides dedicated throughput to Amazon EBS and an
optimized configuration stack to provide optimal EBS I/O performance.
This optimization isn’t available with all instance types.
network_interfaces
(boto.ec2.networkinterface.NetworkInterfaceCollection) – A
NetworkInterfaceCollection data structure containing the ENI
specifications for the instance.
network_interface_id
(string) - ID of the network interface to attach to the instance
network_interface_name
(string) - Name of the network interface to attach to the instance
'''
if all((subnet_id, subnet_name)):
raise SaltInvocationError('Only one of subnet_name or subnet_id may be '
'provided.')
if subnet_name:
r = __salt__['boto_vpc.get_resource_id']('subnet', subnet_name,
region=region, key=key,
keyid=keyid, profile=profile)
if 'id' not in r:
log.warning('Couldn\'t resolve subnet name %s.', subnet_name)
return False
subnet_id = r['id']
if all((security_group_ids, security_group_names)):
raise SaltInvocationError('Only one of security_group_ids or '
'security_group_names may be provided.')
if security_group_names:
security_group_ids = []
for sgn in security_group_names:
r = __salt__['boto_secgroup.get_group_id'](sgn, vpc_name=vpc_name,
region=region, key=key,
keyid=keyid, profile=profile)
if not r:
log.warning('Couldn\'t resolve security group name %s', sgn)
return False
security_group_ids += [r]
network_interface_args = list(map(int, [network_interface_id is not None,
network_interface_name is not None,
network_interfaces is not None]))
if sum(network_interface_args) > 1:
raise SaltInvocationError('Only one of network_interface_id, '
'network_interface_name or '
'network_interfaces may be provided.')
if network_interface_name:
result = get_network_interface_id(network_interface_name,
region=region, key=key,
keyid=keyid,
profile=profile)
network_interface_id = result['result']
if not network_interface_id:
log.warning(
"Given network_interface_name '%s' cannot be mapped to an "
"network_interface_id", network_interface_name
)
if network_interface_id:
interface = NetworkInterfaceSpecification(
network_interface_id=network_interface_id,
device_index=0)
else:
interface = NetworkInterfaceSpecification(
subnet_id=subnet_id,
groups=security_group_ids,
device_index=0)
if network_interfaces:
interfaces_specs = [NetworkInterfaceSpecification(**x) for x in network_interfaces]
interfaces = NetworkInterfaceCollection(*interfaces_specs)
else:
interfaces = NetworkInterfaceCollection(interface)
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
reservation = conn.run_instances(image_id, key_name=key_name, security_groups=security_groups,
user_data=user_data, instance_type=instance_type,
placement=placement, kernel_id=kernel_id, ramdisk_id=ramdisk_id,
monitoring_enabled=monitoring_enabled,
private_ip_address=private_ip_address,
block_device_map=_to_blockdev_map(block_device_map),
disable_api_termination=disable_api_termination,
instance_initiated_shutdown_behavior=instance_initiated_shutdown_behavior,
placement_group=placement_group, client_token=client_token,
additional_info=additional_info,
tenancy=tenancy, instance_profile_arn=instance_profile_arn,
instance_profile_name=instance_profile_name, ebs_optimized=ebs_optimized,
network_interfaces=interfaces)
if not reservation:
log.warning('Instance could not be reserved')
return False
instance = reservation.instances[0]
status = 'pending'
while status == 'pending':
time.sleep(5)
status = instance.update()
if status == 'running':
if name:
instance.add_tag('Name', name)
if tags:
instance.add_tags(tags)
return {'instance_id': instance.id}
else:
log.warning(
'Instance could not be started -- status is "%s"',
status
) | [
"def",
"run",
"(",
"image_id",
",",
"name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"key_name",
"=",
"None",
",",
"security_groups",
"=",
"None",
",",
"user_data",
"=",
"None",
",",
"instance_type",
"=",
"'m1.small'",
",",
"placement",
"=",
"None",
... | Create and start an EC2 instance.
Returns True if the instance was created; otherwise False.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.run ami-b80c2b87 name=myinstance
image_id
(string) – The ID of the image to run.
name
(string) - The name of the instance.
tags
(dict of key: value pairs) - tags to apply to the instance.
key_name
(string) – The name of the key pair with which to launch instances.
security_groups
(list of strings) – The names of the EC2 classic security groups with
which to associate instances
user_data
(string) – The Base64-encoded MIME user data to be made available to the
instance(s) in this reservation.
instance_type
(string) – The type of instance to run. Note that some image types
(e.g. hvm) only run on some instance types.
placement
(string) – The Availability Zone to launch the instance into.
kernel_id
(string) – The ID of the kernel with which to launch the instances.
ramdisk_id
(string) – The ID of the RAM disk with which to launch the instances.
monitoring_enabled
(bool) – Enable detailed CloudWatch monitoring on the instance.
vpc_id
(string) - ID of a VPC to bind the instance to. Exclusive with vpc_name.
vpc_name
(string) - Name of a VPC to bind the instance to. Exclusive with vpc_id.
subnet_id
(string) – The subnet ID within which to launch the instances for VPC.
subnet_name
(string) – The name of a subnet within which to launch the instances for VPC.
private_ip_address
(string) – If you’re using VPC, you can optionally use this parameter to
assign the instance a specific available IP address from the subnet
(e.g. 10.0.0.25).
block_device_map
(boto.ec2.blockdevicemapping.BlockDeviceMapping) – A BlockDeviceMapping
data structure describing the EBS volumes associated with the Image.
(string) - A string representation of a BlockDeviceMapping structure
(dict) - A dict describing a BlockDeviceMapping structure
YAML example:
.. code-block:: yaml
device-maps:
/dev/sdb:
ephemeral_name: ephemeral0
/dev/sdc:
ephemeral_name: ephemeral1
/dev/sdd:
ephemeral_name: ephemeral2
/dev/sde:
ephemeral_name: ephemeral3
/dev/sdf:
size: 20
volume_type: gp2
disable_api_termination
(bool) – If True, the instances will be locked and will not be able to
be terminated via the API.
instance_initiated_shutdown_behavior
(string) – Specifies whether the instance stops or terminates on
instance-initiated shutdown. Valid values are: stop, terminate
placement_group
(string) – If specified, this is the name of the placement group in
which the instance(s) will be launched.
client_token
(string) – Unique, case-sensitive identifier you provide to ensure
idempotency of the request. Maximum 64 ASCII characters.
security_group_ids
(list of strings) – The ID(s) of the VPC security groups with which to
associate instances.
security_group_names
(list of strings) – The name(s) of the VPC security groups with which to
associate instances.
additional_info
(string) – Specifies additional information to make available to the
instance(s).
tenancy
(string) – The tenancy of the instance you want to launch. An instance
with a tenancy of ‘dedicated’ runs on single-tenant hardware and can
only be launched into a VPC. Valid values are:”default” or “dedicated”.
NOTE: To use dedicated tenancy you MUST specify a VPC subnet-ID as well.
instance_profile_arn
(string) – The Amazon resource name (ARN) of the IAM Instance Profile
(IIP) to associate with the instances.
instance_profile_name
(string) – The name of the IAM Instance Profile (IIP) to associate with
the instances.
ebs_optimized
(bool) – Whether the instance is optimized for EBS I/O. This
optimization provides dedicated throughput to Amazon EBS and an
optimized configuration stack to provide optimal EBS I/O performance.
This optimization isn’t available with all instance types.
network_interfaces
(boto.ec2.networkinterface.NetworkInterfaceCollection) – A
NetworkInterfaceCollection data structure containing the ENI
specifications for the instance.
network_interface_id
(string) - ID of the network interface to attach to the instance
network_interface_name
(string) - Name of the network interface to attach to the instance | [
"Create",
"and",
"start",
"an",
"EC2",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L854-L1081 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_key | def get_key(key_name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a key exists. Returns fingerprint and name if
it does and False if it doesn't
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_key mykey
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
key = conn.get_key_pair(key_name)
log.debug("the key to return is : %s", key)
if key is None:
return False
return key.name, key.fingerprint
except boto.exception.BotoServerError as e:
log.debug(e)
return False | python | def get_key(key_name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a key exists. Returns fingerprint and name if
it does and False if it doesn't
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_key mykey
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
key = conn.get_key_pair(key_name)
log.debug("the key to return is : %s", key)
if key is None:
return False
return key.name, key.fingerprint
except boto.exception.BotoServerError as e:
log.debug(e)
return False | [
"def",
"get_key",
"(",
"key_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
... | Check to see if a key exists. Returns fingerprint and name if
it does and False if it doesn't
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_key mykey | [
"Check",
"to",
"see",
"if",
"a",
"key",
"exists",
".",
"Returns",
"fingerprint",
"and",
"name",
"if",
"it",
"does",
"and",
"False",
"if",
"it",
"doesn",
"t",
"CLI",
"Example",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1084-L1104 | train |
saltstack/salt | salt/modules/boto_ec2.py | create_key | def create_key(key_name, save_path, region=None, key=None, keyid=None,
profile=None):
'''
Creates a key and saves it to a given path.
Returns the private key.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.create_key mykey /root/
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
key = conn.create_key_pair(key_name)
log.debug("the key to return is : %s", key)
key.save(save_path)
return key.material
except boto.exception.BotoServerError as e:
log.debug(e)
return False | python | def create_key(key_name, save_path, region=None, key=None, keyid=None,
profile=None):
'''
Creates a key and saves it to a given path.
Returns the private key.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.create_key mykey /root/
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
key = conn.create_key_pair(key_name)
log.debug("the key to return is : %s", key)
key.save(save_path)
return key.material
except boto.exception.BotoServerError as e:
log.debug(e)
return False | [
"def",
"create_key",
"(",
"key_name",
",",
"save_path",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | Creates a key and saves it to a given path.
Returns the private key.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.create_key mykey /root/ | [
"Creates",
"a",
"key",
"and",
"saves",
"it",
"to",
"a",
"given",
"path",
".",
"Returns",
"the",
"private",
"key",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1107-L1128 | train |
saltstack/salt | salt/modules/boto_ec2.py | import_key | def import_key(key_name, public_key_material, region=None, key=None,
keyid=None, profile=None):
'''
Imports the public key from an RSA key pair that you created with a third-party tool.
Supported formats:
- OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys)
- Base64 encoded DER format
- SSH public key file format as specified in RFC4716
- DSA keys are not supported. Make sure your key generator is set up to create RSA keys.
Supported lengths: 1024, 2048, and 4096.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.import mykey publickey
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
key = conn.import_key_pair(key_name, public_key_material)
log.debug("the key to return is : %s", key)
return key.fingerprint
except boto.exception.BotoServerError as e:
log.debug(e)
return False | python | def import_key(key_name, public_key_material, region=None, key=None,
keyid=None, profile=None):
'''
Imports the public key from an RSA key pair that you created with a third-party tool.
Supported formats:
- OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys)
- Base64 encoded DER format
- SSH public key file format as specified in RFC4716
- DSA keys are not supported. Make sure your key generator is set up to create RSA keys.
Supported lengths: 1024, 2048, and 4096.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.import mykey publickey
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
key = conn.import_key_pair(key_name, public_key_material)
log.debug("the key to return is : %s", key)
return key.fingerprint
except boto.exception.BotoServerError as e:
log.debug(e)
return False | [
"def",
"import_key",
"(",
"key_name",
",",
"public_key_material",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",... | Imports the public key from an RSA key pair that you created with a third-party tool.
Supported formats:
- OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys)
- Base64 encoded DER format
- SSH public key file format as specified in RFC4716
- DSA keys are not supported. Make sure your key generator is set up to create RSA keys.
Supported lengths: 1024, 2048, and 4096.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.import mykey publickey | [
"Imports",
"the",
"public",
"key",
"from",
"an",
"RSA",
"key",
"pair",
"that",
"you",
"created",
"with",
"a",
"third",
"-",
"party",
"tool",
".",
"Supported",
"formats",
":",
"-",
"OpenSSH",
"public",
"key",
"format",
"(",
"e",
".",
"g",
".",
"the",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1131-L1156 | train |
saltstack/salt | salt/modules/boto_ec2.py | delete_key | def delete_key(key_name, region=None, key=None, keyid=None, profile=None):
'''
Deletes a key. Always returns True
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.delete_key mykey
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
key = conn.delete_key_pair(key_name)
log.debug("the key to return is : %s", key)
return key
except boto.exception.BotoServerError as e:
log.debug(e)
return False | python | def delete_key(key_name, region=None, key=None, keyid=None, profile=None):
'''
Deletes a key. Always returns True
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.delete_key mykey
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
key = conn.delete_key_pair(key_name)
log.debug("the key to return is : %s", key)
return key
except boto.exception.BotoServerError as e:
log.debug(e)
return False | [
"def",
"delete_key",
"(",
"key_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid... | Deletes a key. Always returns True
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.delete_key mykey | [
"Deletes",
"a",
"key",
".",
"Always",
"returns",
"True"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1159-L1177 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_keys | def get_keys(keynames=None, filters=None, region=None, key=None,
keyid=None, profile=None):
'''
Gets all keys or filters them by name and returns a list.
keynames (list):: A list of the names of keypairs to retrieve.
If not provided, all key pairs will be returned.
filters (dict) :: Optional filters that can be used to limit the
results returned. Filters are provided in the form of a dictionary
consisting of filter names as the key and filter values as the
value. The set of allowable filter names/values is dependent on
the request being performed. Check the EC2 API guide for details.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_keys
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
keys = conn.get_all_key_pairs(keynames, filters)
log.debug("the key to return is : %s", keys)
key_values = []
if keys:
for key in keys:
key_values.append(key.name)
return key_values
except boto.exception.BotoServerError as e:
log.debug(e)
return False | python | def get_keys(keynames=None, filters=None, region=None, key=None,
keyid=None, profile=None):
'''
Gets all keys or filters them by name and returns a list.
keynames (list):: A list of the names of keypairs to retrieve.
If not provided, all key pairs will be returned.
filters (dict) :: Optional filters that can be used to limit the
results returned. Filters are provided in the form of a dictionary
consisting of filter names as the key and filter values as the
value. The set of allowable filter names/values is dependent on
the request being performed. Check the EC2 API guide for details.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_keys
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
keys = conn.get_all_key_pairs(keynames, filters)
log.debug("the key to return is : %s", keys)
key_values = []
if keys:
for key in keys:
key_values.append(key.name)
return key_values
except boto.exception.BotoServerError as e:
log.debug(e)
return False | [
"def",
"get_keys",
"(",
"keynames",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"regi... | Gets all keys or filters them by name and returns a list.
keynames (list):: A list of the names of keypairs to retrieve.
If not provided, all key pairs will be returned.
filters (dict) :: Optional filters that can be used to limit the
results returned. Filters are provided in the form of a dictionary
consisting of filter names as the key and filter values as the
value. The set of allowable filter names/values is dependent on
the request being performed. Check the EC2 API guide for details.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_keys | [
"Gets",
"all",
"keys",
"or",
"filters",
"them",
"by",
"name",
"and",
"returns",
"a",
"list",
".",
"keynames",
"(",
"list",
")",
"::",
"A",
"list",
"of",
"the",
"names",
"of",
"keypairs",
"to",
"retrieve",
".",
"If",
"not",
"provided",
"all",
"key",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1180-L1210 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_attribute | def get_attribute(attribute, instance_name=None, instance_id=None, region=None, key=None,
keyid=None, profile=None, filters=None):
'''
Get an EC2 instance attribute.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_attribute sourceDestCheck instance_name=my_instance
Available attributes:
* instanceType
* kernel
* ramdisk
* userData
* disableApiTermination
* instanceInitiatedShutdownBehavior
* rootDeviceName
* blockDeviceMapping
* productCodes
* sourceDestCheck
* groupSet
* ebsOptimized
* sriovNetSupport
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
attribute_list = ['instanceType', 'kernel', 'ramdisk', 'userData', 'disableApiTermination',
'instanceInitiatedShutdownBehavior', 'rootDeviceName', 'blockDeviceMapping', 'productCodes',
'sourceDestCheck', 'groupSet', 'ebsOptimized', 'sriovNetSupport']
if not any((instance_name, instance_id)):
raise SaltInvocationError('At least one of the following must be specified: '
'instance_name or instance_id.')
if instance_name and instance_id:
raise SaltInvocationError('Both instance_name and instance_id can not be specified in the same command.')
if attribute not in attribute_list:
raise SaltInvocationError('Attribute must be one of: {0}.'.format(attribute_list))
try:
if instance_name:
instances = find_instances(name=instance_name, region=region, key=key, keyid=keyid, profile=profile,
filters=filters)
if len(instances) > 1:
log.error('Found more than one EC2 instance matching the criteria.')
return False
elif not instances:
log.error('Found no EC2 instance matching the criteria.')
return False
instance_id = instances[0]
instance_attribute = conn.get_instance_attribute(instance_id, attribute)
if not instance_attribute:
return False
return {attribute: instance_attribute[attribute]}
except boto.exception.BotoServerError as exc:
log.error(exc)
return False | python | def get_attribute(attribute, instance_name=None, instance_id=None, region=None, key=None,
keyid=None, profile=None, filters=None):
'''
Get an EC2 instance attribute.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_attribute sourceDestCheck instance_name=my_instance
Available attributes:
* instanceType
* kernel
* ramdisk
* userData
* disableApiTermination
* instanceInitiatedShutdownBehavior
* rootDeviceName
* blockDeviceMapping
* productCodes
* sourceDestCheck
* groupSet
* ebsOptimized
* sriovNetSupport
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
attribute_list = ['instanceType', 'kernel', 'ramdisk', 'userData', 'disableApiTermination',
'instanceInitiatedShutdownBehavior', 'rootDeviceName', 'blockDeviceMapping', 'productCodes',
'sourceDestCheck', 'groupSet', 'ebsOptimized', 'sriovNetSupport']
if not any((instance_name, instance_id)):
raise SaltInvocationError('At least one of the following must be specified: '
'instance_name or instance_id.')
if instance_name and instance_id:
raise SaltInvocationError('Both instance_name and instance_id can not be specified in the same command.')
if attribute not in attribute_list:
raise SaltInvocationError('Attribute must be one of: {0}.'.format(attribute_list))
try:
if instance_name:
instances = find_instances(name=instance_name, region=region, key=key, keyid=keyid, profile=profile,
filters=filters)
if len(instances) > 1:
log.error('Found more than one EC2 instance matching the criteria.')
return False
elif not instances:
log.error('Found no EC2 instance matching the criteria.')
return False
instance_id = instances[0]
instance_attribute = conn.get_instance_attribute(instance_id, attribute)
if not instance_attribute:
return False
return {attribute: instance_attribute[attribute]}
except boto.exception.BotoServerError as exc:
log.error(exc)
return False | [
"def",
"get_attribute",
"(",
"attribute",
",",
"instance_name",
"=",
"None",
",",
"instance_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"filters",
"=",
"None",
")",... | Get an EC2 instance attribute.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_attribute sourceDestCheck instance_name=my_instance
Available attributes:
* instanceType
* kernel
* ramdisk
* userData
* disableApiTermination
* instanceInitiatedShutdownBehavior
* rootDeviceName
* blockDeviceMapping
* productCodes
* sourceDestCheck
* groupSet
* ebsOptimized
* sriovNetSupport | [
"Get",
"an",
"EC2",
"instance",
"attribute",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1213-L1268 | train |
saltstack/salt | salt/modules/boto_ec2.py | set_attribute | def set_attribute(attribute, attribute_value, instance_name=None, instance_id=None, region=None, key=None, keyid=None,
profile=None, filters=None):
'''
Set an EC2 instance attribute.
Returns whether the operation succeeded or not.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.set_attribute sourceDestCheck False instance_name=my_instance
Available attributes:
* instanceType
* kernel
* ramdisk
* userData
* disableApiTermination
* instanceInitiatedShutdownBehavior
* rootDeviceName
* blockDeviceMapping
* productCodes
* sourceDestCheck
* groupSet
* ebsOptimized
* sriovNetSupport
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
attribute_list = ['instanceType', 'kernel', 'ramdisk', 'userData', 'disableApiTermination',
'instanceInitiatedShutdownBehavior', 'rootDeviceName', 'blockDeviceMapping', 'productCodes',
'sourceDestCheck', 'groupSet', 'ebsOptimized', 'sriovNetSupport']
if not any((instance_name, instance_id)):
raise SaltInvocationError('At least one of the following must be specified: instance_name or instance_id.')
if instance_name and instance_id:
raise SaltInvocationError('Both instance_name and instance_id can not be specified in the same command.')
if attribute not in attribute_list:
raise SaltInvocationError('Attribute must be one of: {0}.'.format(attribute_list))
try:
if instance_name:
instances = find_instances(name=instance_name, region=region, key=key, keyid=keyid, profile=profile,
filters=filters)
if len(instances) != 1:
raise CommandExecutionError('Found more than one EC2 instance matching the criteria.')
instance_id = instances[0]
attribute = conn.modify_instance_attribute(instance_id, attribute, attribute_value)
if not attribute:
return False
return attribute
except boto.exception.BotoServerError as exc:
log.error(exc)
return False | python | def set_attribute(attribute, attribute_value, instance_name=None, instance_id=None, region=None, key=None, keyid=None,
profile=None, filters=None):
'''
Set an EC2 instance attribute.
Returns whether the operation succeeded or not.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.set_attribute sourceDestCheck False instance_name=my_instance
Available attributes:
* instanceType
* kernel
* ramdisk
* userData
* disableApiTermination
* instanceInitiatedShutdownBehavior
* rootDeviceName
* blockDeviceMapping
* productCodes
* sourceDestCheck
* groupSet
* ebsOptimized
* sriovNetSupport
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
attribute_list = ['instanceType', 'kernel', 'ramdisk', 'userData', 'disableApiTermination',
'instanceInitiatedShutdownBehavior', 'rootDeviceName', 'blockDeviceMapping', 'productCodes',
'sourceDestCheck', 'groupSet', 'ebsOptimized', 'sriovNetSupport']
if not any((instance_name, instance_id)):
raise SaltInvocationError('At least one of the following must be specified: instance_name or instance_id.')
if instance_name and instance_id:
raise SaltInvocationError('Both instance_name and instance_id can not be specified in the same command.')
if attribute not in attribute_list:
raise SaltInvocationError('Attribute must be one of: {0}.'.format(attribute_list))
try:
if instance_name:
instances = find_instances(name=instance_name, region=region, key=key, keyid=keyid, profile=profile,
filters=filters)
if len(instances) != 1:
raise CommandExecutionError('Found more than one EC2 instance matching the criteria.')
instance_id = instances[0]
attribute = conn.modify_instance_attribute(instance_id, attribute, attribute_value)
if not attribute:
return False
return attribute
except boto.exception.BotoServerError as exc:
log.error(exc)
return False | [
"def",
"set_attribute",
"(",
"attribute",
",",
"attribute_value",
",",
"instance_name",
"=",
"None",
",",
"instance_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"filte... | Set an EC2 instance attribute.
Returns whether the operation succeeded or not.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.set_attribute sourceDestCheck False instance_name=my_instance
Available attributes:
* instanceType
* kernel
* ramdisk
* userData
* disableApiTermination
* instanceInitiatedShutdownBehavior
* rootDeviceName
* blockDeviceMapping
* productCodes
* sourceDestCheck
* groupSet
* ebsOptimized
* sriovNetSupport | [
"Set",
"an",
"EC2",
"instance",
"attribute",
".",
"Returns",
"whether",
"the",
"operation",
"succeeded",
"or",
"not",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1271-L1322 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_network_interface_id | def get_network_interface_id(name, region=None, key=None, keyid=None,
profile=None):
'''
Get an Elastic Network Interface id from its name tag.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_network_interface_id name=my_eni
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
enis = conn.get_all_network_interfaces(filters={'tag:Name': name})
if not enis:
r['error'] = {'message': 'No ENIs found.'}
elif len(enis) > 1:
r['error'] = {'message': 'Name specified is tagged on multiple ENIs.'}
else:
eni = enis[0]
r['result'] = eni.id
except boto.exception.EC2ResponseError as e:
r['error'] = __utils__['boto.get_error'](e)
return r | python | def get_network_interface_id(name, region=None, key=None, keyid=None,
profile=None):
'''
Get an Elastic Network Interface id from its name tag.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_network_interface_id name=my_eni
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
enis = conn.get_all_network_interfaces(filters={'tag:Name': name})
if not enis:
r['error'] = {'message': 'No ENIs found.'}
elif len(enis) > 1:
r['error'] = {'message': 'Name specified is tagged on multiple ENIs.'}
else:
eni = enis[0]
r['result'] = eni.id
except boto.exception.EC2ResponseError as e:
r['error'] = __utils__['boto.get_error'](e)
return r | [
"def",
"get_network_interface_id",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
","... | Get an Elastic Network Interface id from its name tag.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_network_interface_id name=my_eni | [
"Get",
"an",
"Elastic",
"Network",
"Interface",
"id",
"from",
"its",
"name",
"tag",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1325-L1351 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_network_interface | def get_network_interface(name=None, network_interface_id=None, region=None,
key=None, keyid=None, profile=None):
'''
Get an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_network_interface name=my_eni
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
result = _get_network_interface(conn, name, network_interface_id)
if 'error' in result:
if result['error']['message'] == 'No ENIs found.':
r['result'] = None
return r
return result
eni = result['result']
r['result'] = _describe_network_interface(eni)
return r | python | def get_network_interface(name=None, network_interface_id=None, region=None,
key=None, keyid=None, profile=None):
'''
Get an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_network_interface name=my_eni
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
result = _get_network_interface(conn, name, network_interface_id)
if 'error' in result:
if result['error']['message'] == 'No ENIs found.':
r['result'] = None
return r
return result
eni = result['result']
r['result'] = _describe_network_interface(eni)
return r | [
"def",
"get_network_interface",
"(",
"name",
"=",
"None",
",",
"network_interface_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"r... | Get an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_network_interface name=my_eni | [
"Get",
"an",
"Elastic",
"Network",
"Interface",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1354-L1377 | train |
saltstack/salt | salt/modules/boto_ec2.py | create_network_interface | def create_network_interface(name, subnet_id=None, subnet_name=None,
private_ip_address=None, description=None,
groups=None, region=None, key=None, keyid=None,
profile=None):
'''
Create an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.create_network_interface my_eni subnet-12345 description=my_eni groups=['my_group']
'''
if not salt.utils.data.exactly_one((subnet_id, subnet_name)):
raise SaltInvocationError('One (but not both) of subnet_id or '
'subnet_name must be provided.')
if subnet_name:
resource = __salt__['boto_vpc.get_resource_id']('subnet', subnet_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if 'id' not in resource:
log.warning('Couldn\'t resolve subnet name %s.', subnet_name)
return False
subnet_id = resource['id']
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
result = _get_network_interface(conn, name)
if 'result' in result:
r['error'] = {'message': 'An ENI with this Name tag already exists.'}
return r
vpc_id = __salt__['boto_vpc.get_subnet_association'](
[subnet_id], region=region, key=key, keyid=keyid, profile=profile
)
vpc_id = vpc_id.get('vpc_id')
if not vpc_id:
msg = 'subnet_id {0} does not map to a valid vpc id.'.format(subnet_id)
r['error'] = {'message': msg}
return r
_groups = __salt__['boto_secgroup.convert_to_group_ids'](
groups, vpc_id=vpc_id, region=region, key=key,
keyid=keyid, profile=profile
)
try:
eni = conn.create_network_interface(
subnet_id,
private_ip_address=private_ip_address,
description=description,
groups=_groups
)
eni.add_tag('Name', name)
except boto.exception.EC2ResponseError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
r['result'] = _describe_network_interface(eni)
return r | python | def create_network_interface(name, subnet_id=None, subnet_name=None,
private_ip_address=None, description=None,
groups=None, region=None, key=None, keyid=None,
profile=None):
'''
Create an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.create_network_interface my_eni subnet-12345 description=my_eni groups=['my_group']
'''
if not salt.utils.data.exactly_one((subnet_id, subnet_name)):
raise SaltInvocationError('One (but not both) of subnet_id or '
'subnet_name must be provided.')
if subnet_name:
resource = __salt__['boto_vpc.get_resource_id']('subnet', subnet_name,
region=region, key=key,
keyid=keyid,
profile=profile)
if 'id' not in resource:
log.warning('Couldn\'t resolve subnet name %s.', subnet_name)
return False
subnet_id = resource['id']
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
result = _get_network_interface(conn, name)
if 'result' in result:
r['error'] = {'message': 'An ENI with this Name tag already exists.'}
return r
vpc_id = __salt__['boto_vpc.get_subnet_association'](
[subnet_id], region=region, key=key, keyid=keyid, profile=profile
)
vpc_id = vpc_id.get('vpc_id')
if not vpc_id:
msg = 'subnet_id {0} does not map to a valid vpc id.'.format(subnet_id)
r['error'] = {'message': msg}
return r
_groups = __salt__['boto_secgroup.convert_to_group_ids'](
groups, vpc_id=vpc_id, region=region, key=key,
keyid=keyid, profile=profile
)
try:
eni = conn.create_network_interface(
subnet_id,
private_ip_address=private_ip_address,
description=description,
groups=_groups
)
eni.add_tag('Name', name)
except boto.exception.EC2ResponseError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
r['result'] = _describe_network_interface(eni)
return r | [
"def",
"create_network_interface",
"(",
"name",
",",
"subnet_id",
"=",
"None",
",",
"subnet_name",
"=",
"None",
",",
"private_ip_address",
"=",
"None",
",",
"description",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"="... | Create an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.create_network_interface my_eni subnet-12345 description=my_eni groups=['my_group'] | [
"Create",
"an",
"Elastic",
"Network",
"Interface",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1432-L1491 | train |
saltstack/salt | salt/modules/boto_ec2.py | delete_network_interface | def delete_network_interface(
name=None, network_interface_id=None, region=None, key=None,
keyid=None, profile=None):
'''
Create an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.create_network_interface my_eni subnet-12345 description=my_eni groups=['my_group']
'''
if not (name or network_interface_id):
raise SaltInvocationError(
'Either name or network_interface_id must be provided.'
)
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
result = _get_network_interface(conn, name, network_interface_id)
if 'error' in result:
return result
eni = result['result']
try:
info = _describe_network_interface(eni)
network_interface_id = info['id']
except KeyError:
r['error'] = {'message': 'ID not found for this network interface.'}
return r
try:
r['result'] = conn.delete_network_interface(network_interface_id)
except boto.exception.EC2ResponseError as e:
r['error'] = __utils__['boto.get_error'](e)
return r | python | def delete_network_interface(
name=None, network_interface_id=None, region=None, key=None,
keyid=None, profile=None):
'''
Create an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.create_network_interface my_eni subnet-12345 description=my_eni groups=['my_group']
'''
if not (name or network_interface_id):
raise SaltInvocationError(
'Either name or network_interface_id must be provided.'
)
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
result = _get_network_interface(conn, name, network_interface_id)
if 'error' in result:
return result
eni = result['result']
try:
info = _describe_network_interface(eni)
network_interface_id = info['id']
except KeyError:
r['error'] = {'message': 'ID not found for this network interface.'}
return r
try:
r['result'] = conn.delete_network_interface(network_interface_id)
except boto.exception.EC2ResponseError as e:
r['error'] = __utils__['boto.get_error'](e)
return r | [
"def",
"delete_network_interface",
"(",
"name",
"=",
"None",
",",
"network_interface_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"not",
"(",
"name",
"or"... | Create an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.create_network_interface my_eni subnet-12345 description=my_eni groups=['my_group'] | [
"Create",
"an",
"Elastic",
"Network",
"Interface",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1494-L1528 | train |
saltstack/salt | salt/modules/boto_ec2.py | attach_network_interface | def attach_network_interface(device_index, name=None, network_interface_id=None,
instance_name=None, instance_id=None,
region=None, key=None, keyid=None, profile=None):
'''
Attach an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.attach_network_interface my_eni instance_name=salt-master device_index=0
'''
if not salt.utils.data.exactly_one((name, network_interface_id)):
raise SaltInvocationError(
"Exactly one (but not both) of 'name' or 'network_interface_id' "
"must be provided."
)
if not salt.utils.data.exactly_one((instance_name, instance_id)):
raise SaltInvocationError(
"Exactly one (but not both) of 'instance_name' or 'instance_id' "
"must be provided."
)
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
result = _get_network_interface(conn, name, network_interface_id)
if 'error' in result:
return result
eni = result['result']
try:
info = _describe_network_interface(eni)
network_interface_id = info['id']
except KeyError:
r['error'] = {'message': 'ID not found for this network interface.'}
return r
if instance_name:
try:
instance_id = get_id(name=instance_name, region=region, key=key,
keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.error(e)
return False
try:
r['result'] = conn.attach_network_interface(
network_interface_id, instance_id, device_index
)
except boto.exception.EC2ResponseError as e:
r['error'] = __utils__['boto.get_error'](e)
return r | python | def attach_network_interface(device_index, name=None, network_interface_id=None,
instance_name=None, instance_id=None,
region=None, key=None, keyid=None, profile=None):
'''
Attach an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.attach_network_interface my_eni instance_name=salt-master device_index=0
'''
if not salt.utils.data.exactly_one((name, network_interface_id)):
raise SaltInvocationError(
"Exactly one (but not both) of 'name' or 'network_interface_id' "
"must be provided."
)
if not salt.utils.data.exactly_one((instance_name, instance_id)):
raise SaltInvocationError(
"Exactly one (but not both) of 'instance_name' or 'instance_id' "
"must be provided."
)
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
result = _get_network_interface(conn, name, network_interface_id)
if 'error' in result:
return result
eni = result['result']
try:
info = _describe_network_interface(eni)
network_interface_id = info['id']
except KeyError:
r['error'] = {'message': 'ID not found for this network interface.'}
return r
if instance_name:
try:
instance_id = get_id(name=instance_name, region=region, key=key,
keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.error(e)
return False
try:
r['result'] = conn.attach_network_interface(
network_interface_id, instance_id, device_index
)
except boto.exception.EC2ResponseError as e:
r['error'] = __utils__['boto.get_error'](e)
return r | [
"def",
"attach_network_interface",
"(",
"device_index",
",",
"name",
"=",
"None",
",",
"network_interface_id",
"=",
"None",
",",
"instance_name",
"=",
"None",
",",
"instance_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",... | Attach an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.attach_network_interface my_eni instance_name=salt-master device_index=0 | [
"Attach",
"an",
"Elastic",
"Network",
"Interface",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1531-L1584 | train |
saltstack/salt | salt/modules/boto_ec2.py | modify_network_interface_attribute | def modify_network_interface_attribute(
name=None, network_interface_id=None, attr=None,
value=None, region=None, key=None, keyid=None, profile=None):
'''
Modify an attribute of an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.modify_network_interface_attribute my_eni attr=description value='example description'
'''
if not (name or network_interface_id):
raise SaltInvocationError(
'Either name or network_interface_id must be provided.'
)
if attr is None and value is None:
raise SaltInvocationError(
'attr and value must be provided.'
)
r = {}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = _get_network_interface(conn, name, network_interface_id)
if 'error' in result:
return result
eni = result['result']
info = _describe_network_interface(eni)
network_interface_id = info['id']
# munge attr into what the API requires
if attr == 'groups':
_attr = 'groupSet'
elif attr == 'source_dest_check':
_attr = 'sourceDestCheck'
elif attr == 'delete_on_termination':
_attr = 'deleteOnTermination'
else:
_attr = attr
_value = value
if info.get('vpc_id') and _attr == 'groupSet':
_value = __salt__['boto_secgroup.convert_to_group_ids'](
value, vpc_id=info.get('vpc_id'), region=region, key=key,
keyid=keyid, profile=profile
)
if not _value:
r['error'] = {
'message': ('Security groups do not map to valid security'
' group ids')
}
return r
_attachment_id = None
if _attr == 'deleteOnTermination':
try:
_attachment_id = info['attachment']['id']
except KeyError:
r['error'] = {
'message': ('No attachment id found for this ENI. The ENI must'
' be attached before delete_on_termination can be'
' modified')
}
return r
try:
r['result'] = conn.modify_network_interface_attribute(
network_interface_id, _attr, _value, attachment_id=_attachment_id
)
except boto.exception.EC2ResponseError as e:
r['error'] = __utils__['boto.get_error'](e)
return r | python | def modify_network_interface_attribute(
name=None, network_interface_id=None, attr=None,
value=None, region=None, key=None, keyid=None, profile=None):
'''
Modify an attribute of an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.modify_network_interface_attribute my_eni attr=description value='example description'
'''
if not (name or network_interface_id):
raise SaltInvocationError(
'Either name or network_interface_id must be provided.'
)
if attr is None and value is None:
raise SaltInvocationError(
'attr and value must be provided.'
)
r = {}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = _get_network_interface(conn, name, network_interface_id)
if 'error' in result:
return result
eni = result['result']
info = _describe_network_interface(eni)
network_interface_id = info['id']
# munge attr into what the API requires
if attr == 'groups':
_attr = 'groupSet'
elif attr == 'source_dest_check':
_attr = 'sourceDestCheck'
elif attr == 'delete_on_termination':
_attr = 'deleteOnTermination'
else:
_attr = attr
_value = value
if info.get('vpc_id') and _attr == 'groupSet':
_value = __salt__['boto_secgroup.convert_to_group_ids'](
value, vpc_id=info.get('vpc_id'), region=region, key=key,
keyid=keyid, profile=profile
)
if not _value:
r['error'] = {
'message': ('Security groups do not map to valid security'
' group ids')
}
return r
_attachment_id = None
if _attr == 'deleteOnTermination':
try:
_attachment_id = info['attachment']['id']
except KeyError:
r['error'] = {
'message': ('No attachment id found for this ENI. The ENI must'
' be attached before delete_on_termination can be'
' modified')
}
return r
try:
r['result'] = conn.modify_network_interface_attribute(
network_interface_id, _attr, _value, attachment_id=_attachment_id
)
except boto.exception.EC2ResponseError as e:
r['error'] = __utils__['boto.get_error'](e)
return r | [
"def",
"modify_network_interface_attribute",
"(",
"name",
"=",
"None",
",",
"network_interface_id",
"=",
"None",
",",
"attr",
"=",
"None",
",",
"value",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"pr... | Modify an attribute of an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.modify_network_interface_attribute my_eni attr=description value='example description' | [
"Modify",
"an",
"attribute",
"of",
"an",
"Elastic",
"Network",
"Interface",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1626-L1694 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_all_volumes | def get_all_volumes(volume_ids=None, filters=None, return_objs=False,
region=None, key=None, keyid=None, profile=None):
'''
Get a list of all EBS volumes, optionally filtered by provided 'filters' param
.. versionadded:: 2016.11.0
volume_ids
(list) - Optional list of volume_ids. If provided, only the volumes
associated with those in the list will be returned.
filters
(dict) - Additional constraints on which volumes to return. Valid filters are:
- attachment.attach-time - The time stamp when the attachment initiated.
- attachment.delete-on-termination - Whether the volume is deleted on instance termination.
- attachment.device - The device name that is exposed to the instance (for example, /dev/sda1).
- attachment.instance-id - The ID of the instance the volume is attached to.
- attachment.status - The attachment state (attaching | attached | detaching | detached).
- availability-zone - The Availability Zone in which the volume was created.
- create-time - The time stamp when the volume was created.
- encrypted - The encryption status of the volume.
- size - The size of the volume, in GiB.
- snapshot-id - The snapshot from which the volume was created.
- status - The status of the volume (creating | available | in-use | deleting | deleted | error).
- tag:key=value - The key/value combination of a tag assigned to the resource.
- volume-id - The volume ID.
- volume-type - The Amazon EBS volume type. This can be ``gp2`` for General
Purpose SSD, ``io1`` for Provisioned IOPS SSD, ``st1`` for Throughput
Optimized HDD, ``sc1`` for Cold HDD, or ``standard`` for Magnetic volumes.
return_objs
(bool) - Changes the return type from list of volume IDs to list of
boto.ec2.volume.Volume objects
returns
(list) - A list of the requested values: Either the volume IDs or, if
return_objs is ``True``, boto.ec2.volume.Volume objects.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_all_volumes filters='{"tag:Name": "myVolume01"}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = conn.get_all_volumes(volume_ids=volume_ids, filters=filters)
return ret if return_objs else [r.id for r in ret]
except boto.exception.BotoServerError as e:
log.error(e)
return [] | python | def get_all_volumes(volume_ids=None, filters=None, return_objs=False,
region=None, key=None, keyid=None, profile=None):
'''
Get a list of all EBS volumes, optionally filtered by provided 'filters' param
.. versionadded:: 2016.11.0
volume_ids
(list) - Optional list of volume_ids. If provided, only the volumes
associated with those in the list will be returned.
filters
(dict) - Additional constraints on which volumes to return. Valid filters are:
- attachment.attach-time - The time stamp when the attachment initiated.
- attachment.delete-on-termination - Whether the volume is deleted on instance termination.
- attachment.device - The device name that is exposed to the instance (for example, /dev/sda1).
- attachment.instance-id - The ID of the instance the volume is attached to.
- attachment.status - The attachment state (attaching | attached | detaching | detached).
- availability-zone - The Availability Zone in which the volume was created.
- create-time - The time stamp when the volume was created.
- encrypted - The encryption status of the volume.
- size - The size of the volume, in GiB.
- snapshot-id - The snapshot from which the volume was created.
- status - The status of the volume (creating | available | in-use | deleting | deleted | error).
- tag:key=value - The key/value combination of a tag assigned to the resource.
- volume-id - The volume ID.
- volume-type - The Amazon EBS volume type. This can be ``gp2`` for General
Purpose SSD, ``io1`` for Provisioned IOPS SSD, ``st1`` for Throughput
Optimized HDD, ``sc1`` for Cold HDD, or ``standard`` for Magnetic volumes.
return_objs
(bool) - Changes the return type from list of volume IDs to list of
boto.ec2.volume.Volume objects
returns
(list) - A list of the requested values: Either the volume IDs or, if
return_objs is ``True``, boto.ec2.volume.Volume objects.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_all_volumes filters='{"tag:Name": "myVolume01"}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = conn.get_all_volumes(volume_ids=volume_ids, filters=filters)
return ret if return_objs else [r.id for r in ret]
except boto.exception.BotoServerError as e:
log.error(e)
return [] | [
"def",
"get_all_volumes",
"(",
"volume_ids",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"return_objs",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=... | Get a list of all EBS volumes, optionally filtered by provided 'filters' param
.. versionadded:: 2016.11.0
volume_ids
(list) - Optional list of volume_ids. If provided, only the volumes
associated with those in the list will be returned.
filters
(dict) - Additional constraints on which volumes to return. Valid filters are:
- attachment.attach-time - The time stamp when the attachment initiated.
- attachment.delete-on-termination - Whether the volume is deleted on instance termination.
- attachment.device - The device name that is exposed to the instance (for example, /dev/sda1).
- attachment.instance-id - The ID of the instance the volume is attached to.
- attachment.status - The attachment state (attaching | attached | detaching | detached).
- availability-zone - The Availability Zone in which the volume was created.
- create-time - The time stamp when the volume was created.
- encrypted - The encryption status of the volume.
- size - The size of the volume, in GiB.
- snapshot-id - The snapshot from which the volume was created.
- status - The status of the volume (creating | available | in-use | deleting | deleted | error).
- tag:key=value - The key/value combination of a tag assigned to the resource.
- volume-id - The volume ID.
- volume-type - The Amazon EBS volume type. This can be ``gp2`` for General
Purpose SSD, ``io1`` for Provisioned IOPS SSD, ``st1`` for Throughput
Optimized HDD, ``sc1`` for Cold HDD, or ``standard`` for Magnetic volumes.
return_objs
(bool) - Changes the return type from list of volume IDs to list of
boto.ec2.volume.Volume objects
returns
(list) - A list of the requested values: Either the volume IDs or, if
return_objs is ``True``, boto.ec2.volume.Volume objects.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_all_volumes filters='{"tag:Name": "myVolume01"}' | [
"Get",
"a",
"list",
"of",
"all",
"EBS",
"volumes",
"optionally",
"filtered",
"by",
"provided",
"filters",
"param"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1697-L1749 | train |
saltstack/salt | salt/modules/boto_ec2.py | set_volumes_tags | def set_volumes_tags(tag_maps, authoritative=False, dry_run=False,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
tag_maps (list)
List of dicts of filters and tags, where 'filters' is a dict suitable for passing to the
'filters' argument of get_all_volumes() above, and 'tags' is a dict of tags to be set on
volumes (via create_tags/delete_tags) as matched by the given filters. The filter syntax
is extended to permit passing either a list of volume_ids or an instance_name (with
instance_name being the Name tag of the instance to which the desired volumes are mapped).
Each mapping in the list is applied separately, so multiple sets of volumes can be all
tagged differently with one call to this function. If filtering by instance Name, You may
additionally limit the instances matched by passing in a list of desired instance states.
The default set of states is ('pending', 'rebooting', 'running', 'stopping', 'stopped').
YAML example fragment:
.. code-block:: yaml
- filters:
attachment.instance_id: i-abcdef12
tags:
Name: dev-int-abcdef12.aws-foo.com
- filters:
attachment.device: /dev/sdf
tags:
ManagedSnapshots: true
BillingGroup: bubba.hotep@aws-foo.com
in_states:
- stopped
- terminated
- filters:
instance_name: prd-foo-01.aws-foo.com
tags:
Name: prd-foo-01.aws-foo.com
BillingGroup: infra-team@aws-foo.com
- filters:
volume_ids: [ vol-12345689, vol-abcdef12 ]
tags:
BillingGroup: infra-team@aws-foo.com
authoritative (bool)
If true, any existing tags on the matched volumes, and not explicitly requested here, will
be removed.
dry_run (bool)
If true, don't change anything, just return a dictionary describing any changes which
would have been applied.
returns (dict)
A dict describing status and any changes.
'''
ret = {'success': True, 'comment': '', 'changes': {}}
running_states = ('pending', 'rebooting', 'running', 'stopping', 'stopped')
### First creeate a dictionary mapping all changes for a given volume to it's volume ID...
tag_sets = {}
for tm in tag_maps:
filters = dict(tm.get('filters', {}))
tags = dict(tm.get('tags', {}))
args = {'return_objs': True, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
new_filters = {}
log.debug('got filters: %s', filters)
instance_id = None
in_states = tm.get('in_states', running_states)
try:
for k, v in filters.items():
if k == 'volume_ids':
args['volume_ids'] = v
elif k == 'instance_name':
instance_id = get_id(name=v, in_states=in_states, region=region, key=key,
keyid=keyid, profile=profile)
if not instance_id:
msg = "Couldn't resolve instance Name {0} to an ID.".format(v)
raise CommandExecutionError(msg)
new_filters['attachment.instance_id'] = instance_id
else:
new_filters[k] = v
except CommandExecutionError as e:
log.warning(e)
continue # Hmme, abort or do what we can...? Guess the latter for now.
args['filters'] = new_filters
volumes = get_all_volumes(**args)
log.debug('got volume list: %s', volumes)
for vol in volumes:
tag_sets.setdefault(vol.id.replace('-', '_'), {'vol': vol, 'tags': tags.copy()})['tags'].update(tags.copy())
log.debug('tag_sets after munging: %s', tag_sets)
### ...then loop through all those volume->tag pairs and apply them.
changes = {'old': {}, 'new': {}}
for volume in tag_sets.values():
vol, tags = volume['vol'], volume['tags']
log.debug('current tags on vol.id %s: %s', vol.id, dict(getattr(vol, 'tags', {})))
curr = set(dict(getattr(vol, 'tags', {})).keys())
log.debug('requested tags on vol.id %s: %s', vol.id, tags)
req = set(tags.keys())
add = list(req - curr)
update = [r for r in (req & curr) if vol.tags[r] != tags[r]]
remove = list(curr - req)
if add or update or (authoritative and remove):
changes['old'][vol.id] = dict(getattr(vol, 'tags', {}))
changes['new'][vol.id] = tags
else:
log.debug('No changes needed for vol.id %s', vol.id)
if add:
d = dict((k, tags[k]) for k in add)
log.debug('New tags for vol.id %s: %s', vol.id, d)
if update:
d = dict((k, tags[k]) for k in update)
log.debug('Updated tags for vol.id %s: %s', vol.id, d)
if not dry_run:
if not create_tags(vol.id, tags, region=region, key=key, keyid=keyid, profile=profile):
ret['success'] = False
ret['comment'] = "Failed to set tags on vol.id {0}: {1}".format(vol.id, tags)
return ret
if authoritative:
if remove:
log.debug('Removed tags for vol.id %s: %s', vol.id, remove)
if not delete_tags(vol.id, remove, region=region, key=key, keyid=keyid, profile=profile):
ret['success'] = False
ret['comment'] = "Failed to remove tags on vol.id {0}: {1}".format(vol.id, remove)
return ret
ret['changes'].update(changes) if changes['old'] or changes['new'] else None # pylint: disable=W0106
return ret | python | def set_volumes_tags(tag_maps, authoritative=False, dry_run=False,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
tag_maps (list)
List of dicts of filters and tags, where 'filters' is a dict suitable for passing to the
'filters' argument of get_all_volumes() above, and 'tags' is a dict of tags to be set on
volumes (via create_tags/delete_tags) as matched by the given filters. The filter syntax
is extended to permit passing either a list of volume_ids or an instance_name (with
instance_name being the Name tag of the instance to which the desired volumes are mapped).
Each mapping in the list is applied separately, so multiple sets of volumes can be all
tagged differently with one call to this function. If filtering by instance Name, You may
additionally limit the instances matched by passing in a list of desired instance states.
The default set of states is ('pending', 'rebooting', 'running', 'stopping', 'stopped').
YAML example fragment:
.. code-block:: yaml
- filters:
attachment.instance_id: i-abcdef12
tags:
Name: dev-int-abcdef12.aws-foo.com
- filters:
attachment.device: /dev/sdf
tags:
ManagedSnapshots: true
BillingGroup: bubba.hotep@aws-foo.com
in_states:
- stopped
- terminated
- filters:
instance_name: prd-foo-01.aws-foo.com
tags:
Name: prd-foo-01.aws-foo.com
BillingGroup: infra-team@aws-foo.com
- filters:
volume_ids: [ vol-12345689, vol-abcdef12 ]
tags:
BillingGroup: infra-team@aws-foo.com
authoritative (bool)
If true, any existing tags on the matched volumes, and not explicitly requested here, will
be removed.
dry_run (bool)
If true, don't change anything, just return a dictionary describing any changes which
would have been applied.
returns (dict)
A dict describing status and any changes.
'''
ret = {'success': True, 'comment': '', 'changes': {}}
running_states = ('pending', 'rebooting', 'running', 'stopping', 'stopped')
### First creeate a dictionary mapping all changes for a given volume to it's volume ID...
tag_sets = {}
for tm in tag_maps:
filters = dict(tm.get('filters', {}))
tags = dict(tm.get('tags', {}))
args = {'return_objs': True, 'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
new_filters = {}
log.debug('got filters: %s', filters)
instance_id = None
in_states = tm.get('in_states', running_states)
try:
for k, v in filters.items():
if k == 'volume_ids':
args['volume_ids'] = v
elif k == 'instance_name':
instance_id = get_id(name=v, in_states=in_states, region=region, key=key,
keyid=keyid, profile=profile)
if not instance_id:
msg = "Couldn't resolve instance Name {0} to an ID.".format(v)
raise CommandExecutionError(msg)
new_filters['attachment.instance_id'] = instance_id
else:
new_filters[k] = v
except CommandExecutionError as e:
log.warning(e)
continue # Hmme, abort or do what we can...? Guess the latter for now.
args['filters'] = new_filters
volumes = get_all_volumes(**args)
log.debug('got volume list: %s', volumes)
for vol in volumes:
tag_sets.setdefault(vol.id.replace('-', '_'), {'vol': vol, 'tags': tags.copy()})['tags'].update(tags.copy())
log.debug('tag_sets after munging: %s', tag_sets)
### ...then loop through all those volume->tag pairs and apply them.
changes = {'old': {}, 'new': {}}
for volume in tag_sets.values():
vol, tags = volume['vol'], volume['tags']
log.debug('current tags on vol.id %s: %s', vol.id, dict(getattr(vol, 'tags', {})))
curr = set(dict(getattr(vol, 'tags', {})).keys())
log.debug('requested tags on vol.id %s: %s', vol.id, tags)
req = set(tags.keys())
add = list(req - curr)
update = [r for r in (req & curr) if vol.tags[r] != tags[r]]
remove = list(curr - req)
if add or update or (authoritative and remove):
changes['old'][vol.id] = dict(getattr(vol, 'tags', {}))
changes['new'][vol.id] = tags
else:
log.debug('No changes needed for vol.id %s', vol.id)
if add:
d = dict((k, tags[k]) for k in add)
log.debug('New tags for vol.id %s: %s', vol.id, d)
if update:
d = dict((k, tags[k]) for k in update)
log.debug('Updated tags for vol.id %s: %s', vol.id, d)
if not dry_run:
if not create_tags(vol.id, tags, region=region, key=key, keyid=keyid, profile=profile):
ret['success'] = False
ret['comment'] = "Failed to set tags on vol.id {0}: {1}".format(vol.id, tags)
return ret
if authoritative:
if remove:
log.debug('Removed tags for vol.id %s: %s', vol.id, remove)
if not delete_tags(vol.id, remove, region=region, key=key, keyid=keyid, profile=profile):
ret['success'] = False
ret['comment'] = "Failed to remove tags on vol.id {0}: {1}".format(vol.id, remove)
return ret
ret['changes'].update(changes) if changes['old'] or changes['new'] else None # pylint: disable=W0106
return ret | [
"def",
"set_volumes_tags",
"(",
"tag_maps",
",",
"authoritative",
"=",
"False",
",",
"dry_run",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'su... | .. versionadded:: 2016.11.0
tag_maps (list)
List of dicts of filters and tags, where 'filters' is a dict suitable for passing to the
'filters' argument of get_all_volumes() above, and 'tags' is a dict of tags to be set on
volumes (via create_tags/delete_tags) as matched by the given filters. The filter syntax
is extended to permit passing either a list of volume_ids or an instance_name (with
instance_name being the Name tag of the instance to which the desired volumes are mapped).
Each mapping in the list is applied separately, so multiple sets of volumes can be all
tagged differently with one call to this function. If filtering by instance Name, You may
additionally limit the instances matched by passing in a list of desired instance states.
The default set of states is ('pending', 'rebooting', 'running', 'stopping', 'stopped').
YAML example fragment:
.. code-block:: yaml
- filters:
attachment.instance_id: i-abcdef12
tags:
Name: dev-int-abcdef12.aws-foo.com
- filters:
attachment.device: /dev/sdf
tags:
ManagedSnapshots: true
BillingGroup: bubba.hotep@aws-foo.com
in_states:
- stopped
- terminated
- filters:
instance_name: prd-foo-01.aws-foo.com
tags:
Name: prd-foo-01.aws-foo.com
BillingGroup: infra-team@aws-foo.com
- filters:
volume_ids: [ vol-12345689, vol-abcdef12 ]
tags:
BillingGroup: infra-team@aws-foo.com
authoritative (bool)
If true, any existing tags on the matched volumes, and not explicitly requested here, will
be removed.
dry_run (bool)
If true, don't change anything, just return a dictionary describing any changes which
would have been applied.
returns (dict)
A dict describing status and any changes. | [
"..",
"versionadded",
"::",
"2016",
".",
"11",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1752-L1876 | train |
saltstack/salt | salt/modules/boto_ec2.py | get_all_tags | def get_all_tags(filters=None, region=None, key=None, keyid=None, profile=None):
'''
Describe all tags matching the filter criteria, or all tags in the account otherwise.
.. versionadded:: 2018.3.0
filters
(dict) - Additional constraints on which volumes to return. Note that valid filters vary
extensively depending on the resource type. When in doubt, search first without a filter
and then use the returned data to help fine-tune your search. You can generally garner the
resource type from its ID (e.g. `vol-XXXXX` is a volume, `i-XXXXX` is an instance, etc.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_all_tags '{"tag:Name": myInstanceNameTag, resource-type: instance}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = conn.get_all_tags(filters)
tags = {}
for t in ret:
if t.res_id not in tags:
tags[t.res_id] = {}
tags[t.res_id][t.name] = t.value
return tags
except boto.exception.BotoServerError as e:
log.error(e)
return {} | python | def get_all_tags(filters=None, region=None, key=None, keyid=None, profile=None):
'''
Describe all tags matching the filter criteria, or all tags in the account otherwise.
.. versionadded:: 2018.3.0
filters
(dict) - Additional constraints on which volumes to return. Note that valid filters vary
extensively depending on the resource type. When in doubt, search first without a filter
and then use the returned data to help fine-tune your search. You can generally garner the
resource type from its ID (e.g. `vol-XXXXX` is a volume, `i-XXXXX` is an instance, etc.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_all_tags '{"tag:Name": myInstanceNameTag, resource-type: instance}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = conn.get_all_tags(filters)
tags = {}
for t in ret:
if t.res_id not in tags:
tags[t.res_id] = {}
tags[t.res_id][t.name] = t.value
return tags
except boto.exception.BotoServerError as e:
log.error(e)
return {} | [
"def",
"get_all_tags",
"(",
"filters",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key... | Describe all tags matching the filter criteria, or all tags in the account otherwise.
.. versionadded:: 2018.3.0
filters
(dict) - Additional constraints on which volumes to return. Note that valid filters vary
extensively depending on the resource type. When in doubt, search first without a filter
and then use the returned data to help fine-tune your search. You can generally garner the
resource type from its ID (e.g. `vol-XXXXX` is a volume, `i-XXXXX` is an instance, etc.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_all_tags '{"tag:Name": myInstanceNameTag, resource-type: instance}' | [
"Describe",
"all",
"tags",
"matching",
"the",
"filter",
"criteria",
"or",
"all",
"tags",
"in",
"the",
"account",
"otherwise",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1879-L1909 | train |
saltstack/salt | salt/modules/boto_ec2.py | create_tags | def create_tags(resource_ids, tags, region=None, key=None, keyid=None, profile=None):
'''
Create new metadata tags for the specified resource ids.
.. versionadded:: 2016.11.0
resource_ids
(string) or (list) – List of resource IDs. A plain string will be converted to a list of one element.
tags
(dict) – Dictionary of name/value pairs. To create only a tag name, pass '' as the value.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.create_tags vol-12345678 '{"Name": "myVolume01"}'
'''
if not isinstance(resource_ids, list):
resource_ids = [resource_ids]
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
conn.create_tags(resource_ids, tags)
return True
except boto.exception.BotoServerError as e:
log.error(e)
return False | python | def create_tags(resource_ids, tags, region=None, key=None, keyid=None, profile=None):
'''
Create new metadata tags for the specified resource ids.
.. versionadded:: 2016.11.0
resource_ids
(string) or (list) – List of resource IDs. A plain string will be converted to a list of one element.
tags
(dict) – Dictionary of name/value pairs. To create only a tag name, pass '' as the value.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.create_tags vol-12345678 '{"Name": "myVolume01"}'
'''
if not isinstance(resource_ids, list):
resource_ids = [resource_ids]
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
conn.create_tags(resource_ids, tags)
return True
except boto.exception.BotoServerError as e:
log.error(e)
return False | [
"def",
"create_tags",
"(",
"resource_ids",
",",
"tags",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"resource_ids",
",",
"list",
")",
":",
"res... | Create new metadata tags for the specified resource ids.
.. versionadded:: 2016.11.0
resource_ids
(string) or (list) – List of resource IDs. A plain string will be converted to a list of one element.
tags
(dict) – Dictionary of name/value pairs. To create only a tag name, pass '' as the value.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.create_tags vol-12345678 '{"Name": "myVolume01"}' | [
"Create",
"new",
"metadata",
"tags",
"for",
"the",
"specified",
"resource",
"ids",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1912-L1942 | train |
saltstack/salt | salt/modules/boto_ec2.py | detach_volume | def detach_volume(volume_id, instance_id=None, device=None, force=False,
wait_for_detachement=False, region=None, key=None, keyid=None, profile=None):
'''
Detach an EBS volume from an EC2 instance.
.. versionadded:: 2016.11.0
volume_id
(string) – The ID of the EBS volume to be detached.
instance_id
(string) – The ID of the EC2 instance from which it will be detached.
device
(string) – The device on the instance through which the volume is exposted (e.g. /dev/sdh)
force
(bool) – Forces detachment if the previous detachment attempt did not occur cleanly.
This option can lead to data loss or a corrupted file system. Use this option
only as a last resort to detach a volume from a failed instance. The instance
will not have an opportunity to flush file system caches nor file system meta data.
If you use this option, you must perform file system check and repair procedures.
wait_for_detachement
(bool) - Whether or not to wait for volume detachement to complete.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.detach_volume vol-12345678 i-87654321
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = conn.detach_volume(volume_id, instance_id, device, force)
if ret and wait_for_detachement and not _wait_for_volume_available(conn, volume_id):
timeout_msg = 'Timed out waiting for the volume status "available".'
log.error(timeout_msg)
return False
return ret
except boto.exception.BotoServerError as e:
log.error(e)
return False | python | def detach_volume(volume_id, instance_id=None, device=None, force=False,
wait_for_detachement=False, region=None, key=None, keyid=None, profile=None):
'''
Detach an EBS volume from an EC2 instance.
.. versionadded:: 2016.11.0
volume_id
(string) – The ID of the EBS volume to be detached.
instance_id
(string) – The ID of the EC2 instance from which it will be detached.
device
(string) – The device on the instance through which the volume is exposted (e.g. /dev/sdh)
force
(bool) – Forces detachment if the previous detachment attempt did not occur cleanly.
This option can lead to data loss or a corrupted file system. Use this option
only as a last resort to detach a volume from a failed instance. The instance
will not have an opportunity to flush file system caches nor file system meta data.
If you use this option, you must perform file system check and repair procedures.
wait_for_detachement
(bool) - Whether or not to wait for volume detachement to complete.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.detach_volume vol-12345678 i-87654321
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ret = conn.detach_volume(volume_id, instance_id, device, force)
if ret and wait_for_detachement and not _wait_for_volume_available(conn, volume_id):
timeout_msg = 'Timed out waiting for the volume status "available".'
log.error(timeout_msg)
return False
return ret
except boto.exception.BotoServerError as e:
log.error(e)
return False | [
"def",
"detach_volume",
"(",
"volume_id",
",",
"instance_id",
"=",
"None",
",",
"device",
"=",
"None",
",",
"force",
"=",
"False",
",",
"wait_for_detachement",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
... | Detach an EBS volume from an EC2 instance.
.. versionadded:: 2016.11.0
volume_id
(string) – The ID of the EBS volume to be detached.
instance_id
(string) – The ID of the EC2 instance from which it will be detached.
device
(string) – The device on the instance through which the volume is exposted (e.g. /dev/sdh)
force
(bool) – Forces detachment if the previous detachment attempt did not occur cleanly.
This option can lead to data loss or a corrupted file system. Use this option
only as a last resort to detach a volume from a failed instance. The instance
will not have an opportunity to flush file system caches nor file system meta data.
If you use this option, you must perform file system check and repair procedures.
wait_for_detachement
(bool) - Whether or not to wait for volume detachement to complete.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.detach_volume vol-12345678 i-87654321 | [
"Detach",
"an",
"EBS",
"volume",
"from",
"an",
"EC2",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L1982-L2024 | train |
saltstack/salt | salt/modules/boto_ec2.py | delete_volume | def delete_volume(volume_id, instance_id=None, device=None, force=False,
region=None, key=None, keyid=None, profile=None):
'''
Detach an EBS volume from an EC2 instance.
.. versionadded:: 2016.11.0
volume_id
(string) – The ID of the EBS volume to be deleted.
force
(bool) – Forces deletion even if the device has not yet been detached from its instance.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.delete_volume vol-12345678
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.delete_volume(volume_id)
except boto.exception.BotoServerError as e:
if not force:
log.error(e)
return False
try:
conn.detach_volume(volume_id, force=force)
return conn.delete_volume(volume_id)
except boto.exception.BotoServerError as e:
log.error(e)
return False | python | def delete_volume(volume_id, instance_id=None, device=None, force=False,
region=None, key=None, keyid=None, profile=None):
'''
Detach an EBS volume from an EC2 instance.
.. versionadded:: 2016.11.0
volume_id
(string) – The ID of the EBS volume to be deleted.
force
(bool) – Forces deletion even if the device has not yet been detached from its instance.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.delete_volume vol-12345678
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.delete_volume(volume_id)
except boto.exception.BotoServerError as e:
if not force:
log.error(e)
return False
try:
conn.detach_volume(volume_id, force=force)
return conn.delete_volume(volume_id)
except boto.exception.BotoServerError as e:
log.error(e)
return False | [
"def",
"delete_volume",
"(",
"volume_id",
",",
"instance_id",
"=",
"None",
",",
"device",
"=",
"None",
",",
"force",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
... | Detach an EBS volume from an EC2 instance.
.. versionadded:: 2016.11.0
volume_id
(string) – The ID of the EBS volume to be deleted.
force
(bool) – Forces deletion even if the device has not yet been detached from its instance.
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.delete_volume vol-12345678 | [
"Detach",
"an",
"EBS",
"volume",
"from",
"an",
"EC2",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L2027-L2061 | train |
saltstack/salt | salt/modules/boto_ec2.py | attach_volume | def attach_volume(volume_id, instance_id, device,
region=None, key=None, keyid=None, profile=None):
'''
Attach an EBS volume to an EC2 instance.
..
volume_id
(string) – The ID of the EBS volume to be attached.
instance_id
(string) – The ID of the EC2 instance to attach the volume to.
device
(string) – The device on the instance through which the volume is exposed (e.g. /dev/sdh)
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.attach_volume vol-12345678 i-87654321 /dev/sdh
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.attach_volume(volume_id, instance_id, device)
except boto.exception.BotoServerError as error:
log.error(error)
return False | python | def attach_volume(volume_id, instance_id, device,
region=None, key=None, keyid=None, profile=None):
'''
Attach an EBS volume to an EC2 instance.
..
volume_id
(string) – The ID of the EBS volume to be attached.
instance_id
(string) – The ID of the EC2 instance to attach the volume to.
device
(string) – The device on the instance through which the volume is exposed (e.g. /dev/sdh)
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.attach_volume vol-12345678 i-87654321 /dev/sdh
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.attach_volume(volume_id, instance_id, device)
except boto.exception.BotoServerError as error:
log.error(error)
return False | [
"def",
"attach_volume",
"(",
"volume_id",
",",
"instance_id",
",",
"device",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
... | Attach an EBS volume to an EC2 instance.
..
volume_id
(string) – The ID of the EBS volume to be attached.
instance_id
(string) – The ID of the EC2 instance to attach the volume to.
device
(string) – The device on the instance through which the volume is exposed (e.g. /dev/sdh)
returns
(bool) - True on success, False on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.attach_volume vol-12345678 i-87654321 /dev/sdh | [
"Attach",
"an",
"EBS",
"volume",
"to",
"an",
"EC2",
"instance",
".",
".."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L2079-L2107 | train |
saltstack/salt | salt/modules/boto_ec2.py | create_volume | def create_volume(zone_name, size=None, snapshot_id=None, volume_type=None,
iops=None, encrypted=False, kms_key_id=None, wait_for_creation=False,
region=None, key=None, keyid=None, profile=None):
'''
Create an EBS volume to an availability zone.
..
zone_name
(string) – The Availability zone name of the EBS volume to be created.
size
(int) – The size of the new volume, in GiB. If you're creating the
volume from a snapshot and don't specify a volume size, the
default is the snapshot size.
snapshot_id
(string) – The snapshot ID from which the new volume will be created.
volume_type
(string) - The type of the volume. Valid volume types for AWS can be found here:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html
iops
(int) - The provisioned IOPS you want to associate with this volume.
encrypted
(bool) - Specifies whether the volume should be encrypted.
kms_key_id
(string) - If encrypted is True, this KMS Key ID may be specified to
encrypt volume with this key
e.g.: arn:aws:kms:us-east-1:012345678910:key/abcd1234-a123-456a-a12b-a123b4cd56ef
wait_for_creation
(bool) - Whether or not to wait for volume creation to complete.
returns
(string) - created volume id on success, error message on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.create_volume us-east-1a size=10
salt-call boto_ec2.create_volume us-east-1a snapshot_id=snap-0123abcd
'''
if size is None and snapshot_id is None:
raise SaltInvocationError(
'Size must be provided if not created from snapshot.'
)
ret = {}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
vol = conn.create_volume(size=size, zone=zone_name, snapshot=snapshot_id,
volume_type=volume_type, iops=iops, encrypted=encrypted,
kms_key_id=kms_key_id)
if wait_for_creation and not _wait_for_volume_available(conn, vol.id):
timeout_msg = 'Timed out waiting for the volume status "available".'
log.error(timeout_msg)
ret['error'] = timeout_msg
else:
ret['result'] = vol.id
except boto.exception.BotoServerError as error:
ret['error'] = __utils__['boto.get_error'](error)
return ret | python | def create_volume(zone_name, size=None, snapshot_id=None, volume_type=None,
iops=None, encrypted=False, kms_key_id=None, wait_for_creation=False,
region=None, key=None, keyid=None, profile=None):
'''
Create an EBS volume to an availability zone.
..
zone_name
(string) – The Availability zone name of the EBS volume to be created.
size
(int) – The size of the new volume, in GiB. If you're creating the
volume from a snapshot and don't specify a volume size, the
default is the snapshot size.
snapshot_id
(string) – The snapshot ID from which the new volume will be created.
volume_type
(string) - The type of the volume. Valid volume types for AWS can be found here:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html
iops
(int) - The provisioned IOPS you want to associate with this volume.
encrypted
(bool) - Specifies whether the volume should be encrypted.
kms_key_id
(string) - If encrypted is True, this KMS Key ID may be specified to
encrypt volume with this key
e.g.: arn:aws:kms:us-east-1:012345678910:key/abcd1234-a123-456a-a12b-a123b4cd56ef
wait_for_creation
(bool) - Whether or not to wait for volume creation to complete.
returns
(string) - created volume id on success, error message on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.create_volume us-east-1a size=10
salt-call boto_ec2.create_volume us-east-1a snapshot_id=snap-0123abcd
'''
if size is None and snapshot_id is None:
raise SaltInvocationError(
'Size must be provided if not created from snapshot.'
)
ret = {}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
vol = conn.create_volume(size=size, zone=zone_name, snapshot=snapshot_id,
volume_type=volume_type, iops=iops, encrypted=encrypted,
kms_key_id=kms_key_id)
if wait_for_creation and not _wait_for_volume_available(conn, vol.id):
timeout_msg = 'Timed out waiting for the volume status "available".'
log.error(timeout_msg)
ret['error'] = timeout_msg
else:
ret['result'] = vol.id
except boto.exception.BotoServerError as error:
ret['error'] = __utils__['boto.get_error'](error)
return ret | [
"def",
"create_volume",
"(",
"zone_name",
",",
"size",
"=",
"None",
",",
"snapshot_id",
"=",
"None",
",",
"volume_type",
"=",
"None",
",",
"iops",
"=",
"None",
",",
"encrypted",
"=",
"False",
",",
"kms_key_id",
"=",
"None",
",",
"wait_for_creation",
"=",
... | Create an EBS volume to an availability zone.
..
zone_name
(string) – The Availability zone name of the EBS volume to be created.
size
(int) – The size of the new volume, in GiB. If you're creating the
volume from a snapshot and don't specify a volume size, the
default is the snapshot size.
snapshot_id
(string) – The snapshot ID from which the new volume will be created.
volume_type
(string) - The type of the volume. Valid volume types for AWS can be found here:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html
iops
(int) - The provisioned IOPS you want to associate with this volume.
encrypted
(bool) - Specifies whether the volume should be encrypted.
kms_key_id
(string) - If encrypted is True, this KMS Key ID may be specified to
encrypt volume with this key
e.g.: arn:aws:kms:us-east-1:012345678910:key/abcd1234-a123-456a-a12b-a123b4cd56ef
wait_for_creation
(bool) - Whether or not to wait for volume creation to complete.
returns
(string) - created volume id on success, error message on failure.
CLI Example:
.. code-block:: bash
salt-call boto_ec2.create_volume us-east-1a size=10
salt-call boto_ec2.create_volume us-east-1a snapshot_id=snap-0123abcd | [
"Create",
"an",
"EBS",
"volume",
"to",
"an",
"availability",
"zone",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L2110-L2169 | train |
saltstack/salt | salt/modules/hg.py | revision | def revision(cwd, rev='tip', short=False, user=None):
'''
Returns the long hash of a given identifier (hash, branch, tag, HEAD, etc)
cwd
The path to the Mercurial repository
rev: tip
The revision
short: False
Return an abbreviated commit hash
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt '*' hg.revision /path/to/repo mybranch
'''
cmd = [
'hg',
'id',
'-i',
'--debug' if not short else '',
'-r',
'{0}'.format(rev)]
result = __salt__['cmd.run_all'](
cmd,
cwd=cwd,
runas=user,
python_shell=False)
if result['retcode'] == 0:
return result['stdout']
else:
return '' | python | def revision(cwd, rev='tip', short=False, user=None):
'''
Returns the long hash of a given identifier (hash, branch, tag, HEAD, etc)
cwd
The path to the Mercurial repository
rev: tip
The revision
short: False
Return an abbreviated commit hash
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt '*' hg.revision /path/to/repo mybranch
'''
cmd = [
'hg',
'id',
'-i',
'--debug' if not short else '',
'-r',
'{0}'.format(rev)]
result = __salt__['cmd.run_all'](
cmd,
cwd=cwd,
runas=user,
python_shell=False)
if result['retcode'] == 0:
return result['stdout']
else:
return '' | [
"def",
"revision",
"(",
"cwd",
",",
"rev",
"=",
"'tip'",
",",
"short",
"=",
"False",
",",
"user",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'hg'",
",",
"'id'",
",",
"'-i'",
",",
"'--debug'",
"if",
"not",
"short",
"else",
"''",
",",
"'-r'",
",",
... | Returns the long hash of a given identifier (hash, branch, tag, HEAD, etc)
cwd
The path to the Mercurial repository
rev: tip
The revision
short: False
Return an abbreviated commit hash
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt '*' hg.revision /path/to/repo mybranch | [
"Returns",
"the",
"long",
"hash",
"of",
"a",
"given",
"identifier",
"(",
"hash",
"branch",
"tag",
"HEAD",
"etc",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/hg.py#L33-L72 | train |
saltstack/salt | salt/modules/hg.py | describe | def describe(cwd, rev='tip', user=None):
'''
Mimic git describe and return an identifier for the given revision
cwd
The path to the Mercurial repository
rev: tip
The path to the archive tarball
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt '*' hg.describe /path/to/repo
'''
cmd = [
'hg',
'log',
'-r',
'{0}'.format(rev),
'--template',
"'{{latesttag}}-{{latesttagdistance}}-{{node|short}}'"
]
desc = __salt__['cmd.run_stdout'](
cmd,
cwd=cwd,
runas=user,
python_shell=False)
return desc or revision(cwd, rev, short=True) | python | def describe(cwd, rev='tip', user=None):
'''
Mimic git describe and return an identifier for the given revision
cwd
The path to the Mercurial repository
rev: tip
The path to the archive tarball
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt '*' hg.describe /path/to/repo
'''
cmd = [
'hg',
'log',
'-r',
'{0}'.format(rev),
'--template',
"'{{latesttag}}-{{latesttagdistance}}-{{node|short}}'"
]
desc = __salt__['cmd.run_stdout'](
cmd,
cwd=cwd,
runas=user,
python_shell=False)
return desc or revision(cwd, rev, short=True) | [
"def",
"describe",
"(",
"cwd",
",",
"rev",
"=",
"'tip'",
",",
"user",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'hg'",
",",
"'log'",
",",
"'-r'",
",",
"'{0}'",
".",
"format",
"(",
"rev",
")",
",",
"'--template'",
",",
"\"'{{latesttag}}-{{latesttagdistan... | Mimic git describe and return an identifier for the given revision
cwd
The path to the Mercurial repository
rev: tip
The path to the archive tarball
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt '*' hg.describe /path/to/repo | [
"Mimic",
"git",
"describe",
"and",
"return",
"an",
"identifier",
"for",
"the",
"given",
"revision"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/hg.py#L75-L108 | train |
saltstack/salt | salt/modules/hg.py | archive | def archive(cwd, output, rev='tip', fmt=None, prefix=None, user=None):
'''
Export a tarball from the repository
cwd
The path to the Mercurial repository
output
The path to the archive tarball
rev: tip
The revision to create an archive from
fmt: None
Format of the resulting archive. Mercurial supports: tar,
tbz2, tgz, zip, uzip, and files formats.
prefix : None
Prepend <prefix>/ to every filename in the archive
user : None
Run hg as a user other than what the minion runs as
If ``prefix`` is not specified it defaults to the basename of the repo
directory.
CLI Example:
.. code-block:: bash
salt '*' hg.archive /path/to/repo output=/tmp/archive.tgz fmt=tgz
'''
cmd = [
'hg',
'archive',
'{0}'.format(output),
'--rev',
'{0}'.format(rev),
]
if fmt:
cmd.append('--type')
cmd.append('{0}'.format(fmt))
if prefix:
cmd.append('--prefix')
cmd.append('"{0}"'.format(prefix))
return __salt__['cmd.run'](cmd, cwd=cwd, runas=user, python_shell=False) | python | def archive(cwd, output, rev='tip', fmt=None, prefix=None, user=None):
'''
Export a tarball from the repository
cwd
The path to the Mercurial repository
output
The path to the archive tarball
rev: tip
The revision to create an archive from
fmt: None
Format of the resulting archive. Mercurial supports: tar,
tbz2, tgz, zip, uzip, and files formats.
prefix : None
Prepend <prefix>/ to every filename in the archive
user : None
Run hg as a user other than what the minion runs as
If ``prefix`` is not specified it defaults to the basename of the repo
directory.
CLI Example:
.. code-block:: bash
salt '*' hg.archive /path/to/repo output=/tmp/archive.tgz fmt=tgz
'''
cmd = [
'hg',
'archive',
'{0}'.format(output),
'--rev',
'{0}'.format(rev),
]
if fmt:
cmd.append('--type')
cmd.append('{0}'.format(fmt))
if prefix:
cmd.append('--prefix')
cmd.append('"{0}"'.format(prefix))
return __salt__['cmd.run'](cmd, cwd=cwd, runas=user, python_shell=False) | [
"def",
"archive",
"(",
"cwd",
",",
"output",
",",
"rev",
"=",
"'tip'",
",",
"fmt",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'hg'",
",",
"'archive'",
",",
"'{0}'",
".",
"format",
"(",
"output",... | Export a tarball from the repository
cwd
The path to the Mercurial repository
output
The path to the archive tarball
rev: tip
The revision to create an archive from
fmt: None
Format of the resulting archive. Mercurial supports: tar,
tbz2, tgz, zip, uzip, and files formats.
prefix : None
Prepend <prefix>/ to every filename in the archive
user : None
Run hg as a user other than what the minion runs as
If ``prefix`` is not specified it defaults to the basename of the repo
directory.
CLI Example:
.. code-block:: bash
salt '*' hg.archive /path/to/repo output=/tmp/archive.tgz fmt=tgz | [
"Export",
"a",
"tarball",
"from",
"the",
"repository"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/hg.py#L111-L156 | train |
saltstack/salt | salt/modules/hg.py | pull | def pull(cwd, opts=None, user=None, identity=None, repository=None):
'''
Perform a pull on the given repository
cwd
The path to the Mercurial repository
repository : None
Perform pull from the repository different from .hg/hgrc:[paths]:default
opts : None
Any additional options to add to the command line
user : None
Run hg as a user other than what the minion runs as
identity : None
Private SSH key on the minion server for authentication (ssh://)
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' hg.pull /path/to/repo opts=-u
'''
cmd = ['hg', 'pull']
if identity:
cmd.extend(_ssh_flag(identity))
if opts:
for opt in opts.split():
cmd.append(opt)
if repository is not None:
cmd.append(repository)
ret = __salt__['cmd.run_all'](cmd, cwd=cwd, runas=user, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Hg command failed: {0}'.format(ret.get('stderr', ret['stdout']))
)
return ret['stdout'] | python | def pull(cwd, opts=None, user=None, identity=None, repository=None):
'''
Perform a pull on the given repository
cwd
The path to the Mercurial repository
repository : None
Perform pull from the repository different from .hg/hgrc:[paths]:default
opts : None
Any additional options to add to the command line
user : None
Run hg as a user other than what the minion runs as
identity : None
Private SSH key on the minion server for authentication (ssh://)
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' hg.pull /path/to/repo opts=-u
'''
cmd = ['hg', 'pull']
if identity:
cmd.extend(_ssh_flag(identity))
if opts:
for opt in opts.split():
cmd.append(opt)
if repository is not None:
cmd.append(repository)
ret = __salt__['cmd.run_all'](cmd, cwd=cwd, runas=user, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Hg command failed: {0}'.format(ret.get('stderr', ret['stdout']))
)
return ret['stdout'] | [
"def",
"pull",
"(",
"cwd",
",",
"opts",
"=",
"None",
",",
"user",
"=",
"None",
",",
"identity",
"=",
"None",
",",
"repository",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'hg'",
",",
"'pull'",
"]",
"if",
"identity",
":",
"cmd",
".",
"extend",
"(",
... | Perform a pull on the given repository
cwd
The path to the Mercurial repository
repository : None
Perform pull from the repository different from .hg/hgrc:[paths]:default
opts : None
Any additional options to add to the command line
user : None
Run hg as a user other than what the minion runs as
identity : None
Private SSH key on the minion server for authentication (ssh://)
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' hg.pull /path/to/repo opts=-u | [
"Perform",
"a",
"pull",
"on",
"the",
"given",
"repository"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/hg.py#L159-L201 | train |
saltstack/salt | salt/modules/hg.py | update | def update(cwd, rev, force=False, user=None):
'''
Update to a given revision
cwd
The path to the Mercurial repository
rev
The revision to update to
force : False
Force an update
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt devserver1 hg.update /path/to/repo somebranch
'''
cmd = ['hg', 'update', '{0}'.format(rev)]
if force:
cmd.append('-C')
ret = __salt__['cmd.run_all'](cmd, cwd=cwd, runas=user, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Hg command failed: {0}'.format(ret.get('stderr', ret['stdout']))
)
return ret['stdout'] | python | def update(cwd, rev, force=False, user=None):
'''
Update to a given revision
cwd
The path to the Mercurial repository
rev
The revision to update to
force : False
Force an update
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt devserver1 hg.update /path/to/repo somebranch
'''
cmd = ['hg', 'update', '{0}'.format(rev)]
if force:
cmd.append('-C')
ret = __salt__['cmd.run_all'](cmd, cwd=cwd, runas=user, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Hg command failed: {0}'.format(ret.get('stderr', ret['stdout']))
)
return ret['stdout'] | [
"def",
"update",
"(",
"cwd",
",",
"rev",
",",
"force",
"=",
"False",
",",
"user",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'hg'",
",",
"'update'",
",",
"'{0}'",
".",
"format",
"(",
"rev",
")",
"]",
"if",
"force",
":",
"cmd",
".",
"append",
"(",... | Update to a given revision
cwd
The path to the Mercurial repository
rev
The revision to update to
force : False
Force an update
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt devserver1 hg.update /path/to/repo somebranch | [
"Update",
"to",
"a",
"given",
"revision"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/hg.py#L204-L236 | train |
saltstack/salt | salt/modules/hg.py | status | def status(cwd, opts=None, user=None):
'''
Show changed files of the given repository
cwd
The path to the Mercurial repository
opts : None
Any additional options to add to the command line
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt '*' hg.status /path/to/repo
'''
def _status(cwd):
cmd = ['hg', 'status']
if opts:
for opt in opts.split():
cmd.append('{0}'.format(opt))
out = __salt__['cmd.run_stdout'](
cmd, cwd=cwd, runas=user, python_shell=False)
types = {
'M': 'modified',
'A': 'added',
'R': 'removed',
'C': 'clean',
'!': 'missing',
'?': 'not tracked',
'I': 'ignored',
' ': 'origin of the previous file',
}
ret = {}
for line in out.splitlines():
t, f = types[line[0]], line[2:]
if t not in ret:
ret[t] = []
ret[t].append(f)
return ret
if salt.utils.data.is_iter(cwd):
return dict((cwd, _status(cwd)) for cwd in cwd)
else:
return _status(cwd) | python | def status(cwd, opts=None, user=None):
'''
Show changed files of the given repository
cwd
The path to the Mercurial repository
opts : None
Any additional options to add to the command line
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt '*' hg.status /path/to/repo
'''
def _status(cwd):
cmd = ['hg', 'status']
if opts:
for opt in opts.split():
cmd.append('{0}'.format(opt))
out = __salt__['cmd.run_stdout'](
cmd, cwd=cwd, runas=user, python_shell=False)
types = {
'M': 'modified',
'A': 'added',
'R': 'removed',
'C': 'clean',
'!': 'missing',
'?': 'not tracked',
'I': 'ignored',
' ': 'origin of the previous file',
}
ret = {}
for line in out.splitlines():
t, f = types[line[0]], line[2:]
if t not in ret:
ret[t] = []
ret[t].append(f)
return ret
if salt.utils.data.is_iter(cwd):
return dict((cwd, _status(cwd)) for cwd in cwd)
else:
return _status(cwd) | [
"def",
"status",
"(",
"cwd",
",",
"opts",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"def",
"_status",
"(",
"cwd",
")",
":",
"cmd",
"=",
"[",
"'hg'",
",",
"'status'",
"]",
"if",
"opts",
":",
"for",
"opt",
"in",
"opts",
".",
"split",
"(",
... | Show changed files of the given repository
cwd
The path to the Mercurial repository
opts : None
Any additional options to add to the command line
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt '*' hg.status /path/to/repo | [
"Show",
"changed",
"files",
"of",
"the",
"given",
"repository"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/hg.py#L282-L329 | train |
saltstack/salt | salt/beacons/network_settings.py | validate | def validate(config):
'''
Validate the beacon configuration
'''
if not isinstance(config, list):
return False, ('Configuration for network_settings '
'beacon must be a list.')
else:
_config = {}
list(map(_config.update, config))
interfaces = _config.get('interfaces', {})
if isinstance(interfaces, list):
#Old syntax
return False, ('interfaces section for network_settings beacon'
' must be a dictionary.')
for item in interfaces:
if not isinstance(_config['interfaces'][item], dict):
return False, ('Interface attributes for network_settings beacon'
' must be a dictionary.')
if not all(j in ATTRS for j in _config['interfaces'][item]):
return False, ('Invalid attributes in beacon configuration.')
return True, 'Valid beacon configuration' | python | def validate(config):
'''
Validate the beacon configuration
'''
if not isinstance(config, list):
return False, ('Configuration for network_settings '
'beacon must be a list.')
else:
_config = {}
list(map(_config.update, config))
interfaces = _config.get('interfaces', {})
if isinstance(interfaces, list):
#Old syntax
return False, ('interfaces section for network_settings beacon'
' must be a dictionary.')
for item in interfaces:
if not isinstance(_config['interfaces'][item], dict):
return False, ('Interface attributes for network_settings beacon'
' must be a dictionary.')
if not all(j in ATTRS for j in _config['interfaces'][item]):
return False, ('Invalid attributes in beacon configuration.')
return True, 'Valid beacon configuration' | [
"def",
"validate",
"(",
"config",
")",
":",
"if",
"not",
"isinstance",
"(",
"config",
",",
"list",
")",
":",
"return",
"False",
",",
"(",
"'Configuration for network_settings '",
"'beacon must be a list.'",
")",
"else",
":",
"_config",
"=",
"{",
"}",
"list",
... | Validate the beacon configuration | [
"Validate",
"the",
"beacon",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/network_settings.py#L50-L73 | train |
saltstack/salt | salt/beacons/network_settings.py | _copy_interfaces_info | def _copy_interfaces_info(interfaces):
'''
Return a dictionary with a copy of each interface attributes in ATTRS
'''
ret = {}
for interface in interfaces:
_interface_attrs_cpy = set()
for attr in ATTRS:
if attr in interfaces[interface]:
attr_dict = Hashabledict()
attr_dict[attr] = repr(interfaces[interface][attr])
_interface_attrs_cpy.add(attr_dict)
ret[interface] = _interface_attrs_cpy
return ret | python | def _copy_interfaces_info(interfaces):
'''
Return a dictionary with a copy of each interface attributes in ATTRS
'''
ret = {}
for interface in interfaces:
_interface_attrs_cpy = set()
for attr in ATTRS:
if attr in interfaces[interface]:
attr_dict = Hashabledict()
attr_dict[attr] = repr(interfaces[interface][attr])
_interface_attrs_cpy.add(attr_dict)
ret[interface] = _interface_attrs_cpy
return ret | [
"def",
"_copy_interfaces_info",
"(",
"interfaces",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"interface",
"in",
"interfaces",
":",
"_interface_attrs_cpy",
"=",
"set",
"(",
")",
"for",
"attr",
"in",
"ATTRS",
":",
"if",
"attr",
"in",
"interfaces",
"[",
"interfa... | Return a dictionary with a copy of each interface attributes in ATTRS | [
"Return",
"a",
"dictionary",
"with",
"a",
"copy",
"of",
"each",
"interface",
"attributes",
"in",
"ATTRS"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/network_settings.py#L76-L91 | train |
saltstack/salt | salt/beacons/network_settings.py | beacon | def beacon(config):
'''
Watch for changes on network settings
By default, the beacon will emit when there is a value change on one of the
settings on watch. The config also support the onvalue parameter for each
setting, which instruct the beacon to only emit if the setting changed to
the value defined.
Example Config
.. code-block:: yaml
beacons:
network_settings:
- interfaces:
eth0:
ipaddr:
promiscuity:
onvalue: 1
eth1:
linkmode:
The config above will check for value changes on eth0 ipaddr and eth1 linkmode. It will also
emit if the promiscuity value changes to 1.
Beacon items can use the * wildcard to make a definition apply to several interfaces. For
example an eth* would apply to all ethernet interfaces.
Setting the argument coalesce = True will combine all the beacon results on a single event.
The example below shows how to trigger coalesced results:
.. code-block:: yaml
beacons:
network_settings:
- coalesce: True
- interfaces:
eth0:
ipaddr:
promiscuity:
'''
_config = {}
list(map(_config.update, config))
ret = []
interfaces = []
expanded_config = {}
global LAST_STATS
coalesce = False
_stats = _copy_interfaces_info(IP.by_name)
if not LAST_STATS:
LAST_STATS = _stats
if 'coalesce' in _config and _config['coalesce']:
coalesce = True
changes = {}
log.debug('_stats %s', _stats)
# Get list of interfaces included in config that are registered in the
# system, including interfaces defined by wildcards (eth*, wlan*)
for interface in _config.get('interfaces', {}):
if interface in _stats:
interfaces.append(interface)
else:
# No direct match, try with * wildcard regexp
interface_regexp = interface.replace('*', '[0-9]+')
for _interface in _stats:
match = re.search(interface_regexp, _interface)
if match:
interfaces.append(match.group())
expanded_config[match.group()] = _config['interfaces'][interface]
if expanded_config:
_config['interfaces'].update(expanded_config)
log.debug('interfaces %s', interfaces)
for interface in interfaces:
_send_event = False
_diff_stats = _stats[interface] - LAST_STATS[interface]
_ret_diff = {}
interface_config = _config['interfaces'][interface]
log.debug('_diff_stats %s', _diff_stats)
if _diff_stats:
_diff_stats_dict = {}
LAST_STATS[interface] = _stats[interface]
for item in _diff_stats:
_diff_stats_dict.update(item)
for attr in interface_config:
if attr in _diff_stats_dict:
config_value = None
if interface_config[attr] and \
'onvalue' in interface_config[attr]:
config_value = interface_config[attr]['onvalue']
new_value = ast.literal_eval(_diff_stats_dict[attr])
if not config_value or config_value == new_value:
_send_event = True
_ret_diff[attr] = new_value
if _send_event:
if coalesce:
changes[interface] = _ret_diff
else:
ret.append({'tag': interface,
'interface': interface,
'change': _ret_diff})
if coalesce and changes:
grains_info = salt.loader.grains(__opts__, True)
__grains__.update(grains_info)
ret.append({'tag': 'result', 'changes': changes})
return ret | python | def beacon(config):
'''
Watch for changes on network settings
By default, the beacon will emit when there is a value change on one of the
settings on watch. The config also support the onvalue parameter for each
setting, which instruct the beacon to only emit if the setting changed to
the value defined.
Example Config
.. code-block:: yaml
beacons:
network_settings:
- interfaces:
eth0:
ipaddr:
promiscuity:
onvalue: 1
eth1:
linkmode:
The config above will check for value changes on eth0 ipaddr and eth1 linkmode. It will also
emit if the promiscuity value changes to 1.
Beacon items can use the * wildcard to make a definition apply to several interfaces. For
example an eth* would apply to all ethernet interfaces.
Setting the argument coalesce = True will combine all the beacon results on a single event.
The example below shows how to trigger coalesced results:
.. code-block:: yaml
beacons:
network_settings:
- coalesce: True
- interfaces:
eth0:
ipaddr:
promiscuity:
'''
_config = {}
list(map(_config.update, config))
ret = []
interfaces = []
expanded_config = {}
global LAST_STATS
coalesce = False
_stats = _copy_interfaces_info(IP.by_name)
if not LAST_STATS:
LAST_STATS = _stats
if 'coalesce' in _config and _config['coalesce']:
coalesce = True
changes = {}
log.debug('_stats %s', _stats)
# Get list of interfaces included in config that are registered in the
# system, including interfaces defined by wildcards (eth*, wlan*)
for interface in _config.get('interfaces', {}):
if interface in _stats:
interfaces.append(interface)
else:
# No direct match, try with * wildcard regexp
interface_regexp = interface.replace('*', '[0-9]+')
for _interface in _stats:
match = re.search(interface_regexp, _interface)
if match:
interfaces.append(match.group())
expanded_config[match.group()] = _config['interfaces'][interface]
if expanded_config:
_config['interfaces'].update(expanded_config)
log.debug('interfaces %s', interfaces)
for interface in interfaces:
_send_event = False
_diff_stats = _stats[interface] - LAST_STATS[interface]
_ret_diff = {}
interface_config = _config['interfaces'][interface]
log.debug('_diff_stats %s', _diff_stats)
if _diff_stats:
_diff_stats_dict = {}
LAST_STATS[interface] = _stats[interface]
for item in _diff_stats:
_diff_stats_dict.update(item)
for attr in interface_config:
if attr in _diff_stats_dict:
config_value = None
if interface_config[attr] and \
'onvalue' in interface_config[attr]:
config_value = interface_config[attr]['onvalue']
new_value = ast.literal_eval(_diff_stats_dict[attr])
if not config_value or config_value == new_value:
_send_event = True
_ret_diff[attr] = new_value
if _send_event:
if coalesce:
changes[interface] = _ret_diff
else:
ret.append({'tag': interface,
'interface': interface,
'change': _ret_diff})
if coalesce and changes:
grains_info = salt.loader.grains(__opts__, True)
__grains__.update(grains_info)
ret.append({'tag': 'result', 'changes': changes})
return ret | [
"def",
"beacon",
"(",
"config",
")",
":",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config",
".",
"update",
",",
"config",
")",
")",
"ret",
"=",
"[",
"]",
"interfaces",
"=",
"[",
"]",
"expanded_config",
"=",
"{",
"}",
"global",
"LAST_STA... | Watch for changes on network settings
By default, the beacon will emit when there is a value change on one of the
settings on watch. The config also support the onvalue parameter for each
setting, which instruct the beacon to only emit if the setting changed to
the value defined.
Example Config
.. code-block:: yaml
beacons:
network_settings:
- interfaces:
eth0:
ipaddr:
promiscuity:
onvalue: 1
eth1:
linkmode:
The config above will check for value changes on eth0 ipaddr and eth1 linkmode. It will also
emit if the promiscuity value changes to 1.
Beacon items can use the * wildcard to make a definition apply to several interfaces. For
example an eth* would apply to all ethernet interfaces.
Setting the argument coalesce = True will combine all the beacon results on a single event.
The example below shows how to trigger coalesced results:
.. code-block:: yaml
beacons:
network_settings:
- coalesce: True
- interfaces:
eth0:
ipaddr:
promiscuity: | [
"Watch",
"for",
"changes",
"on",
"network",
"settings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/network_settings.py#L94-L213 | train |
saltstack/salt | salt/sdb/memcached.py | set_ | def set_(key, value, profile=None):
'''
Set a key/value pair in memcached
'''
conn = salt.utils.memcached.get_conn(profile)
time = profile.get('expire', DEFAULT_EXPIRATION)
return salt.utils.memcached.set_(conn, key, value, time=time) | python | def set_(key, value, profile=None):
'''
Set a key/value pair in memcached
'''
conn = salt.utils.memcached.get_conn(profile)
time = profile.get('expire', DEFAULT_EXPIRATION)
return salt.utils.memcached.set_(conn, key, value, time=time) | [
"def",
"set_",
"(",
"key",
",",
"value",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"salt",
".",
"utils",
".",
"memcached",
".",
"get_conn",
"(",
"profile",
")",
"time",
"=",
"profile",
".",
"get",
"(",
"'expire'",
",",
"DEFAULT_EXPIRATION",
... | Set a key/value pair in memcached | [
"Set",
"a",
"key",
"/",
"value",
"pair",
"in",
"memcached"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/memcached.py#L62-L68 | train |
saltstack/salt | salt/sdb/memcached.py | get | def get(key, profile=None):
'''
Get a value from memcached
'''
conn = salt.utils.memcached.get_conn(profile)
return salt.utils.memcached.get(conn, key) | python | def get(key, profile=None):
'''
Get a value from memcached
'''
conn = salt.utils.memcached.get_conn(profile)
return salt.utils.memcached.get(conn, key) | [
"def",
"get",
"(",
"key",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"salt",
".",
"utils",
".",
"memcached",
".",
"get_conn",
"(",
"profile",
")",
"return",
"salt",
".",
"utils",
".",
"memcached",
".",
"get",
"(",
"conn",
",",
"key",
")"
] | Get a value from memcached | [
"Get",
"a",
"value",
"from",
"memcached"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/memcached.py#L71-L76 | train |
saltstack/salt | salt/states/proxy.py | managed | def managed(name, port, services=None, user=None, password=None, bypass_domains=None, network_service='Ethernet'):
'''
Manages proxy settings for this mininon
name
The proxy server to use
port
The port used by the proxy server
services
A list of the services that should use the given proxy settings, valid services include http, https and ftp.
If no service is given all of the valid services will be used.
user
The username to use for the proxy server if required
password
The password to use for the proxy server if required
bypass_domains
An array of the domains that should bypass the proxy
network_service
The network service to apply the changes to, this only necessary on
macOS
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
valid_services = ['http', 'https', 'ftp']
if services is None:
services = valid_services
# Darwin
if __grains__['os'] in ['MacOS', 'Darwin']:
ret['changes'] = {'new': []}
for service in services:
current_settings = __salt__['proxy.get_{0}_proxy'.format(service)]()
if current_settings.get('server') == name and current_settings.get('port') == six.text_type(port):
ret['comment'] += '{0} proxy settings already set.\n'.format(service)
elif __salt__['proxy.set_{0}_proxy'.format(service)](name, port, user, password, network_service):
ret['comment'] += '{0} proxy settings updated correctly\n'.format(service)
ret['changes']['new'].append({'service': service, 'server': name, 'port': port, 'user': user})
else:
ret['result'] = False
ret['comment'] += 'Failed to set {0} proxy settings.\n'
if bypass_domains is not None:
current_domains = __salt__['proxy.get_proxy_bypass']()
if len(set(current_domains).intersection(bypass_domains)) == len(bypass_domains):
ret['comment'] += 'Proxy bypass domains are already set correctly.\n'
elif __salt__['proxy.set_proxy_bypass'](bypass_domains, network_service):
ret['comment'] += 'Proxy bypass domains updated correctly\n'
ret['changes']['new'].append({'bypass_domains': list(set(bypass_domains).difference(current_domains))})
else:
ret['result'] = False
ret['comment'] += 'Failed to set bypass proxy domains.\n'
if not ret['changes']['new']:
del ret['changes']['new']
return ret
# Windows - Needs its own branch as all settings need to be set at the same time
if __grains__['os'] in ['Windows']:
changes_needed = False
current_settings = __salt__['proxy.get_proxy_win']()
current_domains = __salt__['proxy.get_proxy_bypass']()
if current_settings.get('enabled', False) is True:
for service in services:
# We need to update one of our proxy servers
if service not in current_settings:
changes_needed = True
break
if current_settings[service]['server'] != name or current_settings[service]['port'] != six.text_type(port):
changes_needed = True
break
else:
# Proxy settings aren't enabled
changes_needed = True
# We need to update our bypass domains
if len(set(current_domains).intersection(bypass_domains)) != len(bypass_domains):
changes_needed = True
if changes_needed:
if __salt__['proxy.set_proxy_win'](name, port, services, bypass_domains):
ret['comment'] = 'Proxy settings updated correctly'
else:
ret['result'] = False
ret['comment'] = 'Failed to set {0} proxy settings.'
else:
ret['comment'] = 'Proxy settings already correct.'
return ret | python | def managed(name, port, services=None, user=None, password=None, bypass_domains=None, network_service='Ethernet'):
'''
Manages proxy settings for this mininon
name
The proxy server to use
port
The port used by the proxy server
services
A list of the services that should use the given proxy settings, valid services include http, https and ftp.
If no service is given all of the valid services will be used.
user
The username to use for the proxy server if required
password
The password to use for the proxy server if required
bypass_domains
An array of the domains that should bypass the proxy
network_service
The network service to apply the changes to, this only necessary on
macOS
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
valid_services = ['http', 'https', 'ftp']
if services is None:
services = valid_services
# Darwin
if __grains__['os'] in ['MacOS', 'Darwin']:
ret['changes'] = {'new': []}
for service in services:
current_settings = __salt__['proxy.get_{0}_proxy'.format(service)]()
if current_settings.get('server') == name and current_settings.get('port') == six.text_type(port):
ret['comment'] += '{0} proxy settings already set.\n'.format(service)
elif __salt__['proxy.set_{0}_proxy'.format(service)](name, port, user, password, network_service):
ret['comment'] += '{0} proxy settings updated correctly\n'.format(service)
ret['changes']['new'].append({'service': service, 'server': name, 'port': port, 'user': user})
else:
ret['result'] = False
ret['comment'] += 'Failed to set {0} proxy settings.\n'
if bypass_domains is not None:
current_domains = __salt__['proxy.get_proxy_bypass']()
if len(set(current_domains).intersection(bypass_domains)) == len(bypass_domains):
ret['comment'] += 'Proxy bypass domains are already set correctly.\n'
elif __salt__['proxy.set_proxy_bypass'](bypass_domains, network_service):
ret['comment'] += 'Proxy bypass domains updated correctly\n'
ret['changes']['new'].append({'bypass_domains': list(set(bypass_domains).difference(current_domains))})
else:
ret['result'] = False
ret['comment'] += 'Failed to set bypass proxy domains.\n'
if not ret['changes']['new']:
del ret['changes']['new']
return ret
# Windows - Needs its own branch as all settings need to be set at the same time
if __grains__['os'] in ['Windows']:
changes_needed = False
current_settings = __salt__['proxy.get_proxy_win']()
current_domains = __salt__['proxy.get_proxy_bypass']()
if current_settings.get('enabled', False) is True:
for service in services:
# We need to update one of our proxy servers
if service not in current_settings:
changes_needed = True
break
if current_settings[service]['server'] != name or current_settings[service]['port'] != six.text_type(port):
changes_needed = True
break
else:
# Proxy settings aren't enabled
changes_needed = True
# We need to update our bypass domains
if len(set(current_domains).intersection(bypass_domains)) != len(bypass_domains):
changes_needed = True
if changes_needed:
if __salt__['proxy.set_proxy_win'](name, port, services, bypass_domains):
ret['comment'] = 'Proxy settings updated correctly'
else:
ret['result'] = False
ret['comment'] = 'Failed to set {0} proxy settings.'
else:
ret['comment'] = 'Proxy settings already correct.'
return ret | [
"def",
"managed",
"(",
"name",
",",
"port",
",",
"services",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"bypass_domains",
"=",
"None",
",",
"network_service",
"=",
"'Ethernet'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
... | Manages proxy settings for this mininon
name
The proxy server to use
port
The port used by the proxy server
services
A list of the services that should use the given proxy settings, valid services include http, https and ftp.
If no service is given all of the valid services will be used.
user
The username to use for the proxy server if required
password
The password to use for the proxy server if required
bypass_domains
An array of the domains that should bypass the proxy
network_service
The network service to apply the changes to, this only necessary on
macOS | [
"Manages",
"proxy",
"settings",
"for",
"this",
"mininon"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/proxy.py#L40-L144 | train |
saltstack/salt | salt/modules/saltsupport.py | SaltSupportModule._get_archive_name | def _get_archive_name(self, archname=None):
'''
Create default archive name.
:return:
'''
archname = re.sub('[^a-z0-9]', '', (archname or '').lower()) or 'support'
for grain in ['fqdn', 'host', 'localhost', 'nodename']:
host = __grains__.get(grain)
if host:
break
if not host:
host = 'localhost'
return os.path.join(tempfile.gettempdir(),
'{hostname}-{archname}-{date}-{time}.bz2'.format(archname=archname,
hostname=host,
date=time.strftime('%Y%m%d'),
time=time.strftime('%H%M%S'))) | python | def _get_archive_name(self, archname=None):
'''
Create default archive name.
:return:
'''
archname = re.sub('[^a-z0-9]', '', (archname or '').lower()) or 'support'
for grain in ['fqdn', 'host', 'localhost', 'nodename']:
host = __grains__.get(grain)
if host:
break
if not host:
host = 'localhost'
return os.path.join(tempfile.gettempdir(),
'{hostname}-{archname}-{date}-{time}.bz2'.format(archname=archname,
hostname=host,
date=time.strftime('%Y%m%d'),
time=time.strftime('%H%M%S'))) | [
"def",
"_get_archive_name",
"(",
"self",
",",
"archname",
"=",
"None",
")",
":",
"archname",
"=",
"re",
".",
"sub",
"(",
"'[^a-z0-9]'",
",",
"''",
",",
"(",
"archname",
"or",
"''",
")",
".",
"lower",
"(",
")",
")",
"or",
"'support'",
"for",
"grain",
... | Create default archive name.
:return: | [
"Create",
"default",
"archive",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltsupport.py#L109-L127 | train |
saltstack/salt | salt/modules/saltsupport.py | SaltSupportModule.archives | def archives(self):
'''
Get list of existing archives.
:return:
'''
arc_files = []
tmpdir = tempfile.gettempdir()
for filename in os.listdir(tmpdir):
mtc = re.match(r'\w+-\w+-\d+-\d+\.bz2', filename)
if mtc and len(filename) == mtc.span()[-1]:
arc_files.append(os.path.join(tmpdir, filename))
return arc_files | python | def archives(self):
'''
Get list of existing archives.
:return:
'''
arc_files = []
tmpdir = tempfile.gettempdir()
for filename in os.listdir(tmpdir):
mtc = re.match(r'\w+-\w+-\d+-\d+\.bz2', filename)
if mtc and len(filename) == mtc.span()[-1]:
arc_files.append(os.path.join(tmpdir, filename))
return arc_files | [
"def",
"archives",
"(",
"self",
")",
":",
"arc_files",
"=",
"[",
"]",
"tmpdir",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"tmpdir",
")",
":",
"mtc",
"=",
"re",
".",
"match",
"(",
"r'\\w+-\\w+-\\... | Get list of existing archives.
:return: | [
"Get",
"list",
"of",
"existing",
"archives",
".",
":",
"return",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltsupport.py#L142-L154 | train |
saltstack/salt | salt/modules/saltsupport.py | SaltSupportModule.last_archive | def last_archive(self):
'''
Get the last available archive
:return:
'''
archives = {}
for archive in self.archives():
archives[int(archive.split('.')[0].split('-')[-1])] = archive
return archives and archives[max(archives)] or None | python | def last_archive(self):
'''
Get the last available archive
:return:
'''
archives = {}
for archive in self.archives():
archives[int(archive.split('.')[0].split('-')[-1])] = archive
return archives and archives[max(archives)] or None | [
"def",
"last_archive",
"(",
"self",
")",
":",
"archives",
"=",
"{",
"}",
"for",
"archive",
"in",
"self",
".",
"archives",
"(",
")",
":",
"archives",
"[",
"int",
"(",
"archive",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
".",
"split",
"(",
"'-'... | Get the last available archive
:return: | [
"Get",
"the",
"last",
"available",
"archive",
":",
"return",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltsupport.py#L157-L166 | train |
saltstack/salt | salt/modules/saltsupport.py | SaltSupportModule.delete_archives | def delete_archives(self, *archives):
'''
Delete archives
:return:
'''
# Remove paths
_archives = []
for archive in archives:
_archives.append(os.path.basename(archive))
archives = _archives[:]
ret = {'files': {}, 'errors': {}}
for archive in self.archives():
arc_dir = os.path.dirname(archive)
archive = os.path.basename(archive)
if archives and archive in archives or not archives:
archive = os.path.join(arc_dir, archive)
try:
os.unlink(archive)
ret['files'][archive] = 'removed'
except Exception as err:
ret['errors'][archive] = str(err)
ret['files'][archive] = 'left'
return ret | python | def delete_archives(self, *archives):
'''
Delete archives
:return:
'''
# Remove paths
_archives = []
for archive in archives:
_archives.append(os.path.basename(archive))
archives = _archives[:]
ret = {'files': {}, 'errors': {}}
for archive in self.archives():
arc_dir = os.path.dirname(archive)
archive = os.path.basename(archive)
if archives and archive in archives or not archives:
archive = os.path.join(arc_dir, archive)
try:
os.unlink(archive)
ret['files'][archive] = 'removed'
except Exception as err:
ret['errors'][archive] = str(err)
ret['files'][archive] = 'left'
return ret | [
"def",
"delete_archives",
"(",
"self",
",",
"*",
"archives",
")",
":",
"# Remove paths",
"_archives",
"=",
"[",
"]",
"for",
"archive",
"in",
"archives",
":",
"_archives",
".",
"append",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"archive",
")",
")",
... | Delete archives
:return: | [
"Delete",
"archives",
":",
"return",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltsupport.py#L169-L193 | train |
saltstack/salt | salt/modules/saltsupport.py | SaltSupportModule.format_sync_stats | def format_sync_stats(self, cnt):
'''
Format stats of the sync output.
:param cnt:
:return:
'''
stats = salt.utils.odict.OrderedDict()
if cnt.get('retcode') == salt.defaults.exitcodes.EX_OK:
for line in cnt.get('stdout', '').split(os.linesep):
line = line.split(': ')
if len(line) == 2:
stats[line[0].lower().replace(' ', '_')] = line[1]
cnt['transfer'] = stats
del cnt['stdout']
# Remove empty
empty_sections = []
for section in cnt:
if not cnt[section] and section != 'retcode':
empty_sections.append(section)
for section in empty_sections:
del cnt[section]
return cnt | python | def format_sync_stats(self, cnt):
'''
Format stats of the sync output.
:param cnt:
:return:
'''
stats = salt.utils.odict.OrderedDict()
if cnt.get('retcode') == salt.defaults.exitcodes.EX_OK:
for line in cnt.get('stdout', '').split(os.linesep):
line = line.split(': ')
if len(line) == 2:
stats[line[0].lower().replace(' ', '_')] = line[1]
cnt['transfer'] = stats
del cnt['stdout']
# Remove empty
empty_sections = []
for section in cnt:
if not cnt[section] and section != 'retcode':
empty_sections.append(section)
for section in empty_sections:
del cnt[section]
return cnt | [
"def",
"format_sync_stats",
"(",
"self",
",",
"cnt",
")",
":",
"stats",
"=",
"salt",
".",
"utils",
".",
"odict",
".",
"OrderedDict",
"(",
")",
"if",
"cnt",
".",
"get",
"(",
"'retcode'",
")",
"==",
"salt",
".",
"defaults",
".",
"exitcodes",
".",
"EX_O... | Format stats of the sync output.
:param cnt:
:return: | [
"Format",
"stats",
"of",
"the",
"sync",
"output",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltsupport.py#L195-L219 | train |
saltstack/salt | salt/modules/saltsupport.py | SaltSupportModule.sync | def sync(self, group, name=None, host=None, location=None, move=False, all=False):
'''
Sync the latest archive to the host on given location.
CLI Example:
.. code-block:: bash
salt '*' support.sync group=test
salt '*' support.sync group=test name=/tmp/myspecial-12345-67890.bz2
salt '*' support.sync group=test name=/tmp/myspecial-12345-67890.bz2 host=allmystuff.lan
salt '*' support.sync group=test name=/tmp/myspecial-12345-67890.bz2 host=allmystuff.lan location=/opt/
:param group: name of the local directory to which sync is going to put the result files
:param name: name of the archive. Latest, if not specified.
:param host: name of the destination host for rsync. Default is master, if not specified.
:param location: local destination directory, default temporary if not specified
:param move: move archive file[s]. Default is False.
:param all: work with all available archives. Default is False (i.e. latest available)
:return:
'''
tfh, tfn = tempfile.mkstemp()
processed_archives = []
src_uri = uri = None
last_arc = self.last_archive()
if name:
archives = [name]
elif all:
archives = self.archives()
elif last_arc:
archives = [last_arc]
else:
archives = []
for name in archives:
err = None
if not name:
err = 'No support archive has been defined.'
elif not os.path.exists(name):
err = 'Support archive "{}" was not found'.format(name)
if err is not None:
log.error(err)
raise salt.exceptions.SaltInvocationError(err)
if not uri:
src_uri = os.path.dirname(name)
uri = '{host}:{loc}'.format(host=host or __opts__['master'],
loc=os.path.join(location or tempfile.gettempdir(), group))
os.write(tfh, salt.utils.stringutils.to_bytes(os.path.basename(name)))
os.write(tfh, salt.utils.stringutils.to_bytes(os.linesep))
processed_archives.append(name)
log.debug('Syncing %s to %s', name, uri)
os.close(tfh)
if not processed_archives:
raise salt.exceptions.SaltInvocationError('No archives found to transfer.')
ret = __salt__['rsync.rsync'](src=src_uri, dst=uri, additional_opts=['--stats', '--files-from={}'.format(tfn)])
ret['files'] = {}
for name in processed_archives:
if move:
salt.utils.dictupdate.update(ret, self.delete_archives(name))
log.debug('Deleting %s', name)
ret['files'][name] = 'moved'
else:
ret['files'][name] = 'copied'
try:
os.unlink(tfn)
except (OSError, IOError) as err:
log.error('Cannot remove temporary rsync file %s: %s', tfn, err)
return self.format_sync_stats(ret) | python | def sync(self, group, name=None, host=None, location=None, move=False, all=False):
'''
Sync the latest archive to the host on given location.
CLI Example:
.. code-block:: bash
salt '*' support.sync group=test
salt '*' support.sync group=test name=/tmp/myspecial-12345-67890.bz2
salt '*' support.sync group=test name=/tmp/myspecial-12345-67890.bz2 host=allmystuff.lan
salt '*' support.sync group=test name=/tmp/myspecial-12345-67890.bz2 host=allmystuff.lan location=/opt/
:param group: name of the local directory to which sync is going to put the result files
:param name: name of the archive. Latest, if not specified.
:param host: name of the destination host for rsync. Default is master, if not specified.
:param location: local destination directory, default temporary if not specified
:param move: move archive file[s]. Default is False.
:param all: work with all available archives. Default is False (i.e. latest available)
:return:
'''
tfh, tfn = tempfile.mkstemp()
processed_archives = []
src_uri = uri = None
last_arc = self.last_archive()
if name:
archives = [name]
elif all:
archives = self.archives()
elif last_arc:
archives = [last_arc]
else:
archives = []
for name in archives:
err = None
if not name:
err = 'No support archive has been defined.'
elif not os.path.exists(name):
err = 'Support archive "{}" was not found'.format(name)
if err is not None:
log.error(err)
raise salt.exceptions.SaltInvocationError(err)
if not uri:
src_uri = os.path.dirname(name)
uri = '{host}:{loc}'.format(host=host or __opts__['master'],
loc=os.path.join(location or tempfile.gettempdir(), group))
os.write(tfh, salt.utils.stringutils.to_bytes(os.path.basename(name)))
os.write(tfh, salt.utils.stringutils.to_bytes(os.linesep))
processed_archives.append(name)
log.debug('Syncing %s to %s', name, uri)
os.close(tfh)
if not processed_archives:
raise salt.exceptions.SaltInvocationError('No archives found to transfer.')
ret = __salt__['rsync.rsync'](src=src_uri, dst=uri, additional_opts=['--stats', '--files-from={}'.format(tfn)])
ret['files'] = {}
for name in processed_archives:
if move:
salt.utils.dictupdate.update(ret, self.delete_archives(name))
log.debug('Deleting %s', name)
ret['files'][name] = 'moved'
else:
ret['files'][name] = 'copied'
try:
os.unlink(tfn)
except (OSError, IOError) as err:
log.error('Cannot remove temporary rsync file %s: %s', tfn, err)
return self.format_sync_stats(ret) | [
"def",
"sync",
"(",
"self",
",",
"group",
",",
"name",
"=",
"None",
",",
"host",
"=",
"None",
",",
"location",
"=",
"None",
",",
"move",
"=",
"False",
",",
"all",
"=",
"False",
")",
":",
"tfh",
",",
"tfn",
"=",
"tempfile",
".",
"mkstemp",
"(",
... | Sync the latest archive to the host on given location.
CLI Example:
.. code-block:: bash
salt '*' support.sync group=test
salt '*' support.sync group=test name=/tmp/myspecial-12345-67890.bz2
salt '*' support.sync group=test name=/tmp/myspecial-12345-67890.bz2 host=allmystuff.lan
salt '*' support.sync group=test name=/tmp/myspecial-12345-67890.bz2 host=allmystuff.lan location=/opt/
:param group: name of the local directory to which sync is going to put the result files
:param name: name of the archive. Latest, if not specified.
:param host: name of the destination host for rsync. Default is master, if not specified.
:param location: local destination directory, default temporary if not specified
:param move: move archive file[s]. Default is False.
:param all: work with all available archives. Default is False (i.e. latest available)
:return: | [
"Sync",
"the",
"latest",
"archive",
"to",
"the",
"host",
"on",
"given",
"location",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltsupport.py#L223-L298 | train |
saltstack/salt | salt/modules/saltsupport.py | SaltSupportModule.run | def run(self, profile='default', pillar=None, archive=None, output='nested'):
'''
Run Salt Support on the minion.
profile
Set available profile name. Default is "default".
pillar
Set available profile from the pillars.
archive
Override archive name. Default is "support". This results to "hostname-support-YYYYMMDD-hhmmss.bz2".
output
Change the default outputter. Default is "nested".
CLI Example:
.. code-block:: bash
salt '*' support.run
salt '*' support.run profile=network
salt '*' support.run pillar=something_special
'''
class outputswitch(object):
'''
Output switcher on context
'''
def __init__(self, output_device):
self._tmp_out = output_device
self._orig_out = None
def __enter__(self):
self._orig_out = salt.cli.support.intfunc.out
salt.cli.support.intfunc.out = self._tmp_out
def __exit__(self, *args):
salt.cli.support.intfunc.out = self._orig_out
self.out = LogCollector()
with outputswitch(self.out):
self.collector = SupportDataCollector(archive or self._get_archive_name(archname=archive), output)
self.collector.out = self.out
self.collector.open()
self.collect_local_data(profile=profile, profile_source=__pillar__.get(pillar))
self.collect_internal_data()
self.collector.close()
return {'archive': self.collector.archive_path,
'messages': self.out.messages} | python | def run(self, profile='default', pillar=None, archive=None, output='nested'):
'''
Run Salt Support on the minion.
profile
Set available profile name. Default is "default".
pillar
Set available profile from the pillars.
archive
Override archive name. Default is "support". This results to "hostname-support-YYYYMMDD-hhmmss.bz2".
output
Change the default outputter. Default is "nested".
CLI Example:
.. code-block:: bash
salt '*' support.run
salt '*' support.run profile=network
salt '*' support.run pillar=something_special
'''
class outputswitch(object):
'''
Output switcher on context
'''
def __init__(self, output_device):
self._tmp_out = output_device
self._orig_out = None
def __enter__(self):
self._orig_out = salt.cli.support.intfunc.out
salt.cli.support.intfunc.out = self._tmp_out
def __exit__(self, *args):
salt.cli.support.intfunc.out = self._orig_out
self.out = LogCollector()
with outputswitch(self.out):
self.collector = SupportDataCollector(archive or self._get_archive_name(archname=archive), output)
self.collector.out = self.out
self.collector.open()
self.collect_local_data(profile=profile, profile_source=__pillar__.get(pillar))
self.collect_internal_data()
self.collector.close()
return {'archive': self.collector.archive_path,
'messages': self.out.messages} | [
"def",
"run",
"(",
"self",
",",
"profile",
"=",
"'default'",
",",
"pillar",
"=",
"None",
",",
"archive",
"=",
"None",
",",
"output",
"=",
"'nested'",
")",
":",
"class",
"outputswitch",
"(",
"object",
")",
":",
"'''\n Output switcher on context\n ... | Run Salt Support on the minion.
profile
Set available profile name. Default is "default".
pillar
Set available profile from the pillars.
archive
Override archive name. Default is "support". This results to "hostname-support-YYYYMMDD-hhmmss.bz2".
output
Change the default outputter. Default is "nested".
CLI Example:
.. code-block:: bash
salt '*' support.run
salt '*' support.run profile=network
salt '*' support.run pillar=something_special | [
"Run",
"Salt",
"Support",
"on",
"the",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltsupport.py#L301-L350 | train |
saltstack/salt | salt/utils/filebuffer.py | BufferedReader.next | def next(self):
'''
Return the next iteration by popping `chunk_size` from the left and
appending `chunk_size` to the right if there's info on the file left
to be read.
'''
if self.__buffered is None:
# Use floor division to force multiplier to an integer
multiplier = self.__max_in_mem // self.__chunk_size
self.__buffered = ""
else:
multiplier = 1
self.__buffered = self.__buffered[self.__chunk_size:]
data = self.__file.read(self.__chunk_size * multiplier)
# Data is a byte object in Python 3
# Decode it in order to append to self.__buffered str later
# Use the salt util in case it's already a string (Windows)
data = salt.utils.stringutils.to_str(data)
if not data:
self.__file.close()
raise StopIteration
self.__buffered += data
return self.__buffered | python | def next(self):
'''
Return the next iteration by popping `chunk_size` from the left and
appending `chunk_size` to the right if there's info on the file left
to be read.
'''
if self.__buffered is None:
# Use floor division to force multiplier to an integer
multiplier = self.__max_in_mem // self.__chunk_size
self.__buffered = ""
else:
multiplier = 1
self.__buffered = self.__buffered[self.__chunk_size:]
data = self.__file.read(self.__chunk_size * multiplier)
# Data is a byte object in Python 3
# Decode it in order to append to self.__buffered str later
# Use the salt util in case it's already a string (Windows)
data = salt.utils.stringutils.to_str(data)
if not data:
self.__file.close()
raise StopIteration
self.__buffered += data
return self.__buffered | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"__buffered",
"is",
"None",
":",
"# Use floor division to force multiplier to an integer",
"multiplier",
"=",
"self",
".",
"__max_in_mem",
"//",
"self",
".",
"__chunk_size",
"self",
".",
"__buffered",
"=",
... | Return the next iteration by popping `chunk_size` from the left and
appending `chunk_size` to the right if there's info on the file left
to be read. | [
"Return",
"the",
"next",
"iteration",
"by",
"popping",
"chunk_size",
"from",
"the",
"left",
"and",
"appending",
"chunk_size",
"to",
"the",
"right",
"if",
"there",
"s",
"info",
"on",
"the",
"file",
"left",
"to",
"be",
"read",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/filebuffer.py#L74-L99 | train |
saltstack/salt | salt/pillar/vmware_pillar.py | ext_pillar | def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
**kwargs):
'''
Check vmware/vcenter for all data
'''
vmware_pillar = {}
host = None
username = None
password = None
property_types = []
property_name = 'name'
protocol = None
port = None
pillar_key = 'vmware'
replace_default_attributes = False
type_specific_pillar_attributes = {
'VirtualMachine': [
{
'config':
[
'version',
'guestId',
'files',
'tools',
'flags',
'memoryHotAddEnabled',
'cpuHotAddEnabled',
'cpuHotRemoveEnabled',
'datastoreUrl',
'swapPlacement',
'bootOptions',
'scheduledHardwareUpgradeInfo',
'memoryAllocation',
'cpuAllocation',
]
},
{
'summary':
[
{
'runtime':
[
{
'host':
[
'name',
{'parent': 'name'},
]
},
'bootTime',
]
},
{
'guest':
[
'toolsStatus',
'toolsVersionStatus',
'toolsVersionStatus2',
'toolsRunningStatus',
]
},
{
'config':
[
'cpuReservation',
'memoryReservation',
]
},
{
'storage':
[
'committed',
'uncommitted',
'unshared',
]
},
{'dasVmProtection': ['dasProtected']},
]
},
{
'storage':
[
{
'perDatastoreUsage':
[
{
'datastore': 'name'
},
'committed',
'uncommitted',
'unshared',
]
}
]
},
],
'HostSystem': [
{
'datastore':
[
'name',
'overallStatus',
{
'summary':
[
'url',
'freeSpace',
'maxFileSize',
'maxVirtualDiskCapacity',
'maxPhysicalRDMFileSize',
'maxVirtualRDMFileSize',
{
'vmfs':
[
'capacity',
'blockSizeMb',
'maxBlocks',
'majorVersion',
'version',
'uuid',
{
'extent':
[
'diskName',
'partition',
]
},
'vmfsUpgradeable',
'ssd',
'local',
],
},
],
},
{'vm': 'name'}
]
},
{
'vm':
[
'name',
'overallStatus',
{
'summary':
[
{'runtime': 'powerState'},
]
},
]
},
]
}
pillar_attributes = [
{
'summary':
[
'overallStatus'
]
},
{
'network':
[
'name',
{'config': {'distributedVirtualSwitch': 'name'}},
]
},
{
'datastore':
[
'name',
]
},
{
'parent':
[
'name'
]
},
]
if 'pillar_key' in kwargs:
pillar_key = kwargs['pillar_key']
vmware_pillar[pillar_key] = {}
if 'host' not in kwargs:
log.error('VMWare external pillar configured but host is not specified in ext_pillar configuration.')
return vmware_pillar
else:
host = kwargs['host']
log.debug('vmware_pillar -- host = %s', host)
if 'username' not in kwargs:
log.error('VMWare external pillar requested but username is not specified in ext_pillar configuration.')
return vmware_pillar
else:
username = kwargs['username']
log.debug('vmware_pillar -- username = %s', username)
if 'password' not in kwargs:
log.error('VMWare external pillar requested but password is not specified in ext_pillar configuration.')
return vmware_pillar
else:
password = kwargs['password']
log.debug('vmware_pillar -- password = %s', password)
if 'replace_default_attributes' in kwargs:
replace_default_attributes = kwargs['replace_default_attributes']
if replace_default_attributes:
pillar_attributes = []
type_specific_pillar_attributes = {}
if 'property_types' in kwargs:
for prop_type in kwargs['property_types']:
if isinstance(prop_type, dict):
property_types.append(getattr(vim, prop_type.keys()[0]))
if isinstance(prop_type[prop_type.keys()[0]], list):
pillar_attributes = pillar_attributes + prop_type[prop_type.keys()[0]]
else:
log.warning('A property_type dict was specified, but its value is not a list')
else:
property_types.append(getattr(vim, prop_type))
else:
property_types = [vim.VirtualMachine]
log.debug('vmware_pillar -- property_types = %s', property_types)
if 'property_name' in kwargs:
property_name = kwargs['property_name']
else:
property_name = 'name'
log.debug('vmware_pillar -- property_name = %s', property_name)
if 'protocol' in kwargs:
protocol = kwargs['protocol']
log.debug('vmware_pillar -- protocol = %s', protocol)
if 'port' in kwargs:
port = kwargs['port']
log.debug('vmware_pillar -- port = %s', port)
virtualgrain = None
osgrain = None
if 'virtual' in __grains__:
virtualgrain = __grains__['virtual'].lower()
if 'os' in __grains__:
osgrain = __grains__['os'].lower()
if virtualgrain == 'vmware' or osgrain == 'vmware esxi' or osgrain == 'esxi':
vmware_pillar[pillar_key] = {}
try:
_conn = salt.utils.vmware.get_service_instance(host,
username,
password,
protocol,
port)
if _conn:
data = None
for prop_type in property_types:
data = salt.utils.vmware.get_mor_by_property(_conn,
prop_type,
minion_id,
property_name=property_name)
if data:
type_name = type(data).__name__.replace('vim.', '')
if hasattr(data, 'availableField'):
vmware_pillar[pillar_key]['annotations'] = {}
for availableField in data.availableField:
for customValue in data.customValue:
if availableField.key == customValue.key:
vmware_pillar[pillar_key]['annotations'][availableField.name] = customValue.value
type_specific_pillar_attribute = []
if type_name in type_specific_pillar_attributes:
type_specific_pillar_attribute = type_specific_pillar_attributes[type_name]
vmware_pillar[pillar_key] = dictupdate.update(vmware_pillar[pillar_key],
_crawl_attribute(data,
pillar_attributes +
type_specific_pillar_attribute))
break
# explicitly disconnect from vCenter when we are done, connections linger idle otherwise
Disconnect(_conn)
else:
log.error(
'Unable to obtain a connection with %s, please verify '
'your vmware ext_pillar configuration', host
)
except RuntimeError:
log.error(('A runtime error occurred in the vmware_pillar, '
'this is likely caused by an infinite recursion in '
'a requested attribute. Verify your requested attributes '
'and reconfigure the pillar.'))
return vmware_pillar
else:
return {} | python | def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
**kwargs):
'''
Check vmware/vcenter for all data
'''
vmware_pillar = {}
host = None
username = None
password = None
property_types = []
property_name = 'name'
protocol = None
port = None
pillar_key = 'vmware'
replace_default_attributes = False
type_specific_pillar_attributes = {
'VirtualMachine': [
{
'config':
[
'version',
'guestId',
'files',
'tools',
'flags',
'memoryHotAddEnabled',
'cpuHotAddEnabled',
'cpuHotRemoveEnabled',
'datastoreUrl',
'swapPlacement',
'bootOptions',
'scheduledHardwareUpgradeInfo',
'memoryAllocation',
'cpuAllocation',
]
},
{
'summary':
[
{
'runtime':
[
{
'host':
[
'name',
{'parent': 'name'},
]
},
'bootTime',
]
},
{
'guest':
[
'toolsStatus',
'toolsVersionStatus',
'toolsVersionStatus2',
'toolsRunningStatus',
]
},
{
'config':
[
'cpuReservation',
'memoryReservation',
]
},
{
'storage':
[
'committed',
'uncommitted',
'unshared',
]
},
{'dasVmProtection': ['dasProtected']},
]
},
{
'storage':
[
{
'perDatastoreUsage':
[
{
'datastore': 'name'
},
'committed',
'uncommitted',
'unshared',
]
}
]
},
],
'HostSystem': [
{
'datastore':
[
'name',
'overallStatus',
{
'summary':
[
'url',
'freeSpace',
'maxFileSize',
'maxVirtualDiskCapacity',
'maxPhysicalRDMFileSize',
'maxVirtualRDMFileSize',
{
'vmfs':
[
'capacity',
'blockSizeMb',
'maxBlocks',
'majorVersion',
'version',
'uuid',
{
'extent':
[
'diskName',
'partition',
]
},
'vmfsUpgradeable',
'ssd',
'local',
],
},
],
},
{'vm': 'name'}
]
},
{
'vm':
[
'name',
'overallStatus',
{
'summary':
[
{'runtime': 'powerState'},
]
},
]
},
]
}
pillar_attributes = [
{
'summary':
[
'overallStatus'
]
},
{
'network':
[
'name',
{'config': {'distributedVirtualSwitch': 'name'}},
]
},
{
'datastore':
[
'name',
]
},
{
'parent':
[
'name'
]
},
]
if 'pillar_key' in kwargs:
pillar_key = kwargs['pillar_key']
vmware_pillar[pillar_key] = {}
if 'host' not in kwargs:
log.error('VMWare external pillar configured but host is not specified in ext_pillar configuration.')
return vmware_pillar
else:
host = kwargs['host']
log.debug('vmware_pillar -- host = %s', host)
if 'username' not in kwargs:
log.error('VMWare external pillar requested but username is not specified in ext_pillar configuration.')
return vmware_pillar
else:
username = kwargs['username']
log.debug('vmware_pillar -- username = %s', username)
if 'password' not in kwargs:
log.error('VMWare external pillar requested but password is not specified in ext_pillar configuration.')
return vmware_pillar
else:
password = kwargs['password']
log.debug('vmware_pillar -- password = %s', password)
if 'replace_default_attributes' in kwargs:
replace_default_attributes = kwargs['replace_default_attributes']
if replace_default_attributes:
pillar_attributes = []
type_specific_pillar_attributes = {}
if 'property_types' in kwargs:
for prop_type in kwargs['property_types']:
if isinstance(prop_type, dict):
property_types.append(getattr(vim, prop_type.keys()[0]))
if isinstance(prop_type[prop_type.keys()[0]], list):
pillar_attributes = pillar_attributes + prop_type[prop_type.keys()[0]]
else:
log.warning('A property_type dict was specified, but its value is not a list')
else:
property_types.append(getattr(vim, prop_type))
else:
property_types = [vim.VirtualMachine]
log.debug('vmware_pillar -- property_types = %s', property_types)
if 'property_name' in kwargs:
property_name = kwargs['property_name']
else:
property_name = 'name'
log.debug('vmware_pillar -- property_name = %s', property_name)
if 'protocol' in kwargs:
protocol = kwargs['protocol']
log.debug('vmware_pillar -- protocol = %s', protocol)
if 'port' in kwargs:
port = kwargs['port']
log.debug('vmware_pillar -- port = %s', port)
virtualgrain = None
osgrain = None
if 'virtual' in __grains__:
virtualgrain = __grains__['virtual'].lower()
if 'os' in __grains__:
osgrain = __grains__['os'].lower()
if virtualgrain == 'vmware' or osgrain == 'vmware esxi' or osgrain == 'esxi':
vmware_pillar[pillar_key] = {}
try:
_conn = salt.utils.vmware.get_service_instance(host,
username,
password,
protocol,
port)
if _conn:
data = None
for prop_type in property_types:
data = salt.utils.vmware.get_mor_by_property(_conn,
prop_type,
minion_id,
property_name=property_name)
if data:
type_name = type(data).__name__.replace('vim.', '')
if hasattr(data, 'availableField'):
vmware_pillar[pillar_key]['annotations'] = {}
for availableField in data.availableField:
for customValue in data.customValue:
if availableField.key == customValue.key:
vmware_pillar[pillar_key]['annotations'][availableField.name] = customValue.value
type_specific_pillar_attribute = []
if type_name in type_specific_pillar_attributes:
type_specific_pillar_attribute = type_specific_pillar_attributes[type_name]
vmware_pillar[pillar_key] = dictupdate.update(vmware_pillar[pillar_key],
_crawl_attribute(data,
pillar_attributes +
type_specific_pillar_attribute))
break
# explicitly disconnect from vCenter when we are done, connections linger idle otherwise
Disconnect(_conn)
else:
log.error(
'Unable to obtain a connection with %s, please verify '
'your vmware ext_pillar configuration', host
)
except RuntimeError:
log.error(('A runtime error occurred in the vmware_pillar, '
'this is likely caused by an infinite recursion in '
'a requested attribute. Verify your requested attributes '
'and reconfigure the pillar.'))
return vmware_pillar
else:
return {} | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"# pylint: disable=W0613",
"*",
"*",
"kwargs",
")",
":",
"vmware_pillar",
"=",
"{",
"}",
"host",
"=",
"None",
"username",
"=",
"None",
"password",
"=",
"None",
"property_types",
"=",
"[",
"]",
"pro... | Check vmware/vcenter for all data | [
"Check",
"vmware",
"/",
"vcenter",
"for",
"all",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/vmware_pillar.py#L177-L470 | train |
saltstack/salt | salt/pillar/vmware_pillar.py | _recurse_config_to_dict | def _recurse_config_to_dict(t_data):
'''
helper function to recurse through a vim object and attempt to return all child objects
'''
if not isinstance(t_data, type(None)):
if isinstance(t_data, list):
t_list = []
for i in t_data:
t_list.append(_recurse_config_to_dict(i))
return t_list
elif isinstance(t_data, dict):
t_dict = {}
for k, v in six.iteritems(t_data):
t_dict[k] = _recurse_config_to_dict(v)
return t_dict
else:
if hasattr(t_data, '__dict__'):
return _recurse_config_to_dict(t_data.__dict__)
else:
return _serializer(t_data) | python | def _recurse_config_to_dict(t_data):
'''
helper function to recurse through a vim object and attempt to return all child objects
'''
if not isinstance(t_data, type(None)):
if isinstance(t_data, list):
t_list = []
for i in t_data:
t_list.append(_recurse_config_to_dict(i))
return t_list
elif isinstance(t_data, dict):
t_dict = {}
for k, v in six.iteritems(t_data):
t_dict[k] = _recurse_config_to_dict(v)
return t_dict
else:
if hasattr(t_data, '__dict__'):
return _recurse_config_to_dict(t_data.__dict__)
else:
return _serializer(t_data) | [
"def",
"_recurse_config_to_dict",
"(",
"t_data",
")",
":",
"if",
"not",
"isinstance",
"(",
"t_data",
",",
"type",
"(",
"None",
")",
")",
":",
"if",
"isinstance",
"(",
"t_data",
",",
"list",
")",
":",
"t_list",
"=",
"[",
"]",
"for",
"i",
"in",
"t_data... | helper function to recurse through a vim object and attempt to return all child objects | [
"helper",
"function",
"to",
"recurse",
"through",
"a",
"vim",
"object",
"and",
"attempt",
"to",
"return",
"all",
"child",
"objects"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/vmware_pillar.py#L473-L492 | train |
saltstack/salt | salt/pillar/vmware_pillar.py | _crawl_attribute | def _crawl_attribute(this_data, this_attr):
'''
helper function to crawl an attribute specified for retrieval
'''
if isinstance(this_data, list):
t_list = []
for d in this_data:
t_list.append(_crawl_attribute(d, this_attr))
return t_list
else:
if isinstance(this_attr, dict):
t_dict = {}
for k in this_attr:
if hasattr(this_data, k):
t_dict[k] = _crawl_attribute(getattr(this_data, k, None), this_attr[k])
return t_dict
elif isinstance(this_attr, list):
this_dict = {}
for l in this_attr:
this_dict = dictupdate.update(this_dict, _crawl_attribute(this_data, l))
return this_dict
else:
return {this_attr: _recurse_config_to_dict(getattr(this_data, this_attr, None))} | python | def _crawl_attribute(this_data, this_attr):
'''
helper function to crawl an attribute specified for retrieval
'''
if isinstance(this_data, list):
t_list = []
for d in this_data:
t_list.append(_crawl_attribute(d, this_attr))
return t_list
else:
if isinstance(this_attr, dict):
t_dict = {}
for k in this_attr:
if hasattr(this_data, k):
t_dict[k] = _crawl_attribute(getattr(this_data, k, None), this_attr[k])
return t_dict
elif isinstance(this_attr, list):
this_dict = {}
for l in this_attr:
this_dict = dictupdate.update(this_dict, _crawl_attribute(this_data, l))
return this_dict
else:
return {this_attr: _recurse_config_to_dict(getattr(this_data, this_attr, None))} | [
"def",
"_crawl_attribute",
"(",
"this_data",
",",
"this_attr",
")",
":",
"if",
"isinstance",
"(",
"this_data",
",",
"list",
")",
":",
"t_list",
"=",
"[",
"]",
"for",
"d",
"in",
"this_data",
":",
"t_list",
".",
"append",
"(",
"_crawl_attribute",
"(",
"d",... | helper function to crawl an attribute specified for retrieval | [
"helper",
"function",
"to",
"crawl",
"an",
"attribute",
"specified",
"for",
"retrieval"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/vmware_pillar.py#L495-L517 | train |
saltstack/salt | salt/pillar/vmware_pillar.py | _serializer | def _serializer(obj):
'''
helper function to serialize some objects for prettier return
'''
import datetime
if isinstance(obj, datetime.datetime):
if obj.utcoffset() is not None:
obj = obj - obj.utcoffset()
return obj.__str__()
return obj | python | def _serializer(obj):
'''
helper function to serialize some objects for prettier return
'''
import datetime
if isinstance(obj, datetime.datetime):
if obj.utcoffset() is not None:
obj = obj - obj.utcoffset()
return obj.__str__()
return obj | [
"def",
"_serializer",
"(",
"obj",
")",
":",
"import",
"datetime",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"datetime",
")",
":",
"if",
"obj",
".",
"utcoffset",
"(",
")",
"is",
"not",
"None",
":",
"obj",
"=",
"obj",
"-",
"obj",
".",
"ut... | helper function to serialize some objects for prettier return | [
"helper",
"function",
"to",
"serialize",
"some",
"objects",
"for",
"prettier",
"return"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/vmware_pillar.py#L520-L529 | train |
saltstack/salt | salt/modules/sqlite3.py | modify | def modify(db=None, sql=None):
'''
Issue an SQL query to sqlite3 (with no return data), usually used
to modify the database in some way (insert, delete, create, etc)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.modify /root/test.db 'CREATE TABLE test(id INT, testdata TEXT);'
'''
cur = _connect(db)
if not cur:
return False
cur.execute(sql)
return True | python | def modify(db=None, sql=None):
'''
Issue an SQL query to sqlite3 (with no return data), usually used
to modify the database in some way (insert, delete, create, etc)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.modify /root/test.db 'CREATE TABLE test(id INT, testdata TEXT);'
'''
cur = _connect(db)
if not cur:
return False
cur.execute(sql)
return True | [
"def",
"modify",
"(",
"db",
"=",
"None",
",",
"sql",
"=",
"None",
")",
":",
"cur",
"=",
"_connect",
"(",
"db",
")",
"if",
"not",
"cur",
":",
"return",
"False",
"cur",
".",
"execute",
"(",
"sql",
")",
"return",
"True"
] | Issue an SQL query to sqlite3 (with no return data), usually used
to modify the database in some way (insert, delete, create, etc)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.modify /root/test.db 'CREATE TABLE test(id INT, testdata TEXT);' | [
"Issue",
"an",
"SQL",
"query",
"to",
"sqlite3",
"(",
"with",
"no",
"return",
"data",
")",
"usually",
"used",
"to",
"modify",
"the",
"database",
"in",
"some",
"way",
"(",
"insert",
"delete",
"create",
"etc",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sqlite3.py#L57-L74 | train |
saltstack/salt | salt/modules/sqlite3.py | fetch | def fetch(db=None, sql=None):
'''
Retrieve data from an sqlite3 db (returns all rows, be careful!)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.fetch /root/test.db 'SELECT * FROM test;'
'''
cur = _connect(db)
if not cur:
return False
cur.execute(sql)
rows = cur.fetchall()
return rows | python | def fetch(db=None, sql=None):
'''
Retrieve data from an sqlite3 db (returns all rows, be careful!)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.fetch /root/test.db 'SELECT * FROM test;'
'''
cur = _connect(db)
if not cur:
return False
cur.execute(sql)
rows = cur.fetchall()
return rows | [
"def",
"fetch",
"(",
"db",
"=",
"None",
",",
"sql",
"=",
"None",
")",
":",
"cur",
"=",
"_connect",
"(",
"db",
")",
"if",
"not",
"cur",
":",
"return",
"False",
"cur",
".",
"execute",
"(",
"sql",
")",
"rows",
"=",
"cur",
".",
"fetchall",
"(",
")"... | Retrieve data from an sqlite3 db (returns all rows, be careful!)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.fetch /root/test.db 'SELECT * FROM test;' | [
"Retrieve",
"data",
"from",
"an",
"sqlite3",
"db",
"(",
"returns",
"all",
"rows",
"be",
"careful!",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sqlite3.py#L77-L94 | train |
saltstack/salt | salt/modules/sqlite3.py | tables | def tables(db=None):
'''
Show all tables in the database
CLI Example:
.. code-block:: bash
salt '*' sqlite3.tables /root/test.db
'''
cur = _connect(db)
if not cur:
return False
cur.execute(
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;"
)
rows = cur.fetchall()
return rows | python | def tables(db=None):
'''
Show all tables in the database
CLI Example:
.. code-block:: bash
salt '*' sqlite3.tables /root/test.db
'''
cur = _connect(db)
if not cur:
return False
cur.execute(
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;"
)
rows = cur.fetchall()
return rows | [
"def",
"tables",
"(",
"db",
"=",
"None",
")",
":",
"cur",
"=",
"_connect",
"(",
"db",
")",
"if",
"not",
"cur",
":",
"return",
"False",
"cur",
".",
"execute",
"(",
"\"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;\"",
")",
"rows",
"=",
"cur",
... | Show all tables in the database
CLI Example:
.. code-block:: bash
salt '*' sqlite3.tables /root/test.db | [
"Show",
"all",
"tables",
"in",
"the",
"database"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sqlite3.py#L97-L116 | train |
saltstack/salt | salt/modules/sqlite3.py | indices | def indices(db=None):
'''
Show all indices in the database
CLI Example:
.. code-block:: bash
salt '*' sqlite3.indices /root/test.db
'''
cur = _connect(db)
if not cur:
return False
cur.execute(
"SELECT name FROM sqlite_master WHERE type='index' ORDER BY name;"
)
rows = cur.fetchall()
return rows | python | def indices(db=None):
'''
Show all indices in the database
CLI Example:
.. code-block:: bash
salt '*' sqlite3.indices /root/test.db
'''
cur = _connect(db)
if not cur:
return False
cur.execute(
"SELECT name FROM sqlite_master WHERE type='index' ORDER BY name;"
)
rows = cur.fetchall()
return rows | [
"def",
"indices",
"(",
"db",
"=",
"None",
")",
":",
"cur",
"=",
"_connect",
"(",
"db",
")",
"if",
"not",
"cur",
":",
"return",
"False",
"cur",
".",
"execute",
"(",
"\"SELECT name FROM sqlite_master WHERE type='index' ORDER BY name;\"",
")",
"rows",
"=",
"cur",... | Show all indices in the database
CLI Example:
.. code-block:: bash
salt '*' sqlite3.indices /root/test.db | [
"Show",
"all",
"indices",
"in",
"the",
"database"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sqlite3.py#L119-L138 | train |
saltstack/salt | salt/roster/cache.py | targets | def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613
'''
Return the targets from the Salt Masters' minion cache.
All targets and matchers are supported.
The resulting roster can be configured using ``roster_order`` and ``roster_default``.
'''
minions = salt.utils.minions.CkMinions(__opts__)
_res = minions.check_minions(tgt, tgt_type)
minions = _res['minions']
ret = {}
if not minions:
return ret
# log.debug(minions)
cache = salt.cache.Cache(__opts__)
roster_order = __opts__.get('roster_order', {
'host': ('ipv6-private', 'ipv6-global', 'ipv4-private', 'ipv4-public')
})
ret = {}
for minion_id in minions:
try:
minion = _load_minion(minion_id, cache)
except LookupError:
continue
minion_res = copy.deepcopy(__opts__.get('roster_defaults', {}))
for param, order in roster_order.items():
if not isinstance(order, (list, tuple)):
order = [order]
for key in order:
kres = _minion_lookup(minion_id, key, minion)
if kres:
minion_res[param] = kres
break
if 'host' in minion_res:
ret[minion_id] = minion_res
else:
log.warning('Could not determine host information for minion %s', minion_id)
log.debug('Roster lookup result: %s', ret)
return ret | python | def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613
'''
Return the targets from the Salt Masters' minion cache.
All targets and matchers are supported.
The resulting roster can be configured using ``roster_order`` and ``roster_default``.
'''
minions = salt.utils.minions.CkMinions(__opts__)
_res = minions.check_minions(tgt, tgt_type)
minions = _res['minions']
ret = {}
if not minions:
return ret
# log.debug(minions)
cache = salt.cache.Cache(__opts__)
roster_order = __opts__.get('roster_order', {
'host': ('ipv6-private', 'ipv6-global', 'ipv4-private', 'ipv4-public')
})
ret = {}
for minion_id in minions:
try:
minion = _load_minion(minion_id, cache)
except LookupError:
continue
minion_res = copy.deepcopy(__opts__.get('roster_defaults', {}))
for param, order in roster_order.items():
if not isinstance(order, (list, tuple)):
order = [order]
for key in order:
kres = _minion_lookup(minion_id, key, minion)
if kres:
minion_res[param] = kres
break
if 'host' in minion_res:
ret[minion_id] = minion_res
else:
log.warning('Could not determine host information for minion %s', minion_id)
log.debug('Roster lookup result: %s', ret)
return ret | [
"def",
"targets",
"(",
"tgt",
",",
"tgt_type",
"=",
"'glob'",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=W0613",
"minions",
"=",
"salt",
".",
"utils",
".",
"minions",
".",
"CkMinions",
"(",
"__opts__",
")",
"_res",
"=",
"minions",
".",
"check_... | Return the targets from the Salt Masters' minion cache.
All targets and matchers are supported.
The resulting roster can be configured using ``roster_order`` and ``roster_default``. | [
"Return",
"the",
"targets",
"from",
"the",
"Salt",
"Masters",
"minion",
"cache",
".",
"All",
"targets",
"and",
"matchers",
"are",
"supported",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/cache.py#L113-L159 | train |
saltstack/salt | salt/renderers/gpg.py | _get_key_dir | def _get_key_dir():
'''
return the location of the GPG key directory
'''
gpg_keydir = None
if 'config.get' in __salt__:
gpg_keydir = __salt__['config.get']('gpg_keydir')
if not gpg_keydir:
gpg_keydir = __opts__.get(
'gpg_keydir',
os.path.join(
__opts__.get(
'config_dir',
os.path.dirname(__opts__['conf_file']),
),
'gpgkeys'
))
return gpg_keydir | python | def _get_key_dir():
'''
return the location of the GPG key directory
'''
gpg_keydir = None
if 'config.get' in __salt__:
gpg_keydir = __salt__['config.get']('gpg_keydir')
if not gpg_keydir:
gpg_keydir = __opts__.get(
'gpg_keydir',
os.path.join(
__opts__.get(
'config_dir',
os.path.dirname(__opts__['conf_file']),
),
'gpgkeys'
))
return gpg_keydir | [
"def",
"_get_key_dir",
"(",
")",
":",
"gpg_keydir",
"=",
"None",
"if",
"'config.get'",
"in",
"__salt__",
":",
"gpg_keydir",
"=",
"__salt__",
"[",
"'config.get'",
"]",
"(",
"'gpg_keydir'",
")",
"if",
"not",
"gpg_keydir",
":",
"gpg_keydir",
"=",
"__opts__",
".... | return the location of the GPG key directory | [
"return",
"the",
"location",
"of",
"the",
"GPG",
"key",
"directory"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/gpg.py#L307-L326 | train |
saltstack/salt | salt/renderers/gpg.py | _decrypt_ciphertext | def _decrypt_ciphertext(cipher):
'''
Given a block of ciphertext as a string, and a gpg object, try to decrypt
the cipher and return the decrypted string. If the cipher cannot be
decrypted, log the error, and return the ciphertext back out.
'''
try:
cipher = salt.utils.stringutils.to_unicode(cipher).replace(r'\n', '\n')
except UnicodeDecodeError:
# ciphertext is binary
pass
cipher = salt.utils.stringutils.to_bytes(cipher)
cmd = [_get_gpg_exec(), '--homedir', _get_key_dir(), '--status-fd', '2',
'--no-tty', '-d']
proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)
decrypted_data, decrypt_error = proc.communicate(input=cipher)
if not decrypted_data:
try:
cipher = salt.utils.stringutils.to_unicode(cipher)
except UnicodeDecodeError:
# decrypted data contains undecodable binary data
pass
log.warning(
'Could not decrypt cipher %s, received: %s',
cipher,
decrypt_error
)
return cipher
else:
try:
decrypted_data = salt.utils.stringutils.to_unicode(decrypted_data)
except UnicodeDecodeError:
# decrypted data contains undecodable binary data
pass
return decrypted_data | python | def _decrypt_ciphertext(cipher):
'''
Given a block of ciphertext as a string, and a gpg object, try to decrypt
the cipher and return the decrypted string. If the cipher cannot be
decrypted, log the error, and return the ciphertext back out.
'''
try:
cipher = salt.utils.stringutils.to_unicode(cipher).replace(r'\n', '\n')
except UnicodeDecodeError:
# ciphertext is binary
pass
cipher = salt.utils.stringutils.to_bytes(cipher)
cmd = [_get_gpg_exec(), '--homedir', _get_key_dir(), '--status-fd', '2',
'--no-tty', '-d']
proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)
decrypted_data, decrypt_error = proc.communicate(input=cipher)
if not decrypted_data:
try:
cipher = salt.utils.stringutils.to_unicode(cipher)
except UnicodeDecodeError:
# decrypted data contains undecodable binary data
pass
log.warning(
'Could not decrypt cipher %s, received: %s',
cipher,
decrypt_error
)
return cipher
else:
try:
decrypted_data = salt.utils.stringutils.to_unicode(decrypted_data)
except UnicodeDecodeError:
# decrypted data contains undecodable binary data
pass
return decrypted_data | [
"def",
"_decrypt_ciphertext",
"(",
"cipher",
")",
":",
"try",
":",
"cipher",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"cipher",
")",
".",
"replace",
"(",
"r'\\n'",
",",
"'\\n'",
")",
"except",
"UnicodeDecodeError",
":",
"# cip... | Given a block of ciphertext as a string, and a gpg object, try to decrypt
the cipher and return the decrypted string. If the cipher cannot be
decrypted, log the error, and return the ciphertext back out. | [
"Given",
"a",
"block",
"of",
"ciphertext",
"as",
"a",
"string",
"and",
"a",
"gpg",
"object",
"try",
"to",
"decrypt",
"the",
"cipher",
"and",
"return",
"the",
"decrypted",
"string",
".",
"If",
"the",
"cipher",
"cannot",
"be",
"decrypted",
"log",
"the",
"e... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/gpg.py#L329-L363 | train |
saltstack/salt | salt/renderers/gpg.py | _decrypt_object | def _decrypt_object(obj, translate_newlines=False):
'''
Recursively try to decrypt any object. If the object is a six.string_types
(string or unicode), and it contains a valid GPG header, decrypt it,
otherwise keep going until a string is found.
'''
if salt.utils.stringio.is_readable(obj):
return _decrypt_object(obj.getvalue(), translate_newlines)
if isinstance(obj, six.string_types):
return _decrypt_ciphertexts(obj, translate_newlines=translate_newlines)
elif isinstance(obj, dict):
for key, value in six.iteritems(obj):
obj[key] = _decrypt_object(value,
translate_newlines=translate_newlines)
return obj
elif isinstance(obj, list):
for key, value in enumerate(obj):
obj[key] = _decrypt_object(value,
translate_newlines=translate_newlines)
return obj
else:
return obj | python | def _decrypt_object(obj, translate_newlines=False):
'''
Recursively try to decrypt any object. If the object is a six.string_types
(string or unicode), and it contains a valid GPG header, decrypt it,
otherwise keep going until a string is found.
'''
if salt.utils.stringio.is_readable(obj):
return _decrypt_object(obj.getvalue(), translate_newlines)
if isinstance(obj, six.string_types):
return _decrypt_ciphertexts(obj, translate_newlines=translate_newlines)
elif isinstance(obj, dict):
for key, value in six.iteritems(obj):
obj[key] = _decrypt_object(value,
translate_newlines=translate_newlines)
return obj
elif isinstance(obj, list):
for key, value in enumerate(obj):
obj[key] = _decrypt_object(value,
translate_newlines=translate_newlines)
return obj
else:
return obj | [
"def",
"_decrypt_object",
"(",
"obj",
",",
"translate_newlines",
"=",
"False",
")",
":",
"if",
"salt",
".",
"utils",
".",
"stringio",
".",
"is_readable",
"(",
"obj",
")",
":",
"return",
"_decrypt_object",
"(",
"obj",
".",
"getvalue",
"(",
")",
",",
"tran... | Recursively try to decrypt any object. If the object is a six.string_types
(string or unicode), and it contains a valid GPG header, decrypt it,
otherwise keep going until a string is found. | [
"Recursively",
"try",
"to",
"decrypt",
"any",
"object",
".",
"If",
"the",
"object",
"is",
"a",
"six",
".",
"string_types",
"(",
"string",
"or",
"unicode",
")",
"and",
"it",
"contains",
"a",
"valid",
"GPG",
"header",
"decrypt",
"it",
"otherwise",
"keep",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/gpg.py#L378-L399 | train |
saltstack/salt | salt/renderers/gpg.py | render | def render(gpg_data, saltenv='base', sls='', argline='', **kwargs):
'''
Create a gpg object given a gpg_keydir, and then use it to try to decrypt
the data to be rendered.
'''
if not _get_gpg_exec():
raise SaltRenderError('GPG unavailable')
log.debug('Reading GPG keys from: %s', _get_key_dir())
translate_newlines = kwargs.get('translate_newlines', False)
return _decrypt_object(gpg_data, translate_newlines=translate_newlines) | python | def render(gpg_data, saltenv='base', sls='', argline='', **kwargs):
'''
Create a gpg object given a gpg_keydir, and then use it to try to decrypt
the data to be rendered.
'''
if not _get_gpg_exec():
raise SaltRenderError('GPG unavailable')
log.debug('Reading GPG keys from: %s', _get_key_dir())
translate_newlines = kwargs.get('translate_newlines', False)
return _decrypt_object(gpg_data, translate_newlines=translate_newlines) | [
"def",
"render",
"(",
"gpg_data",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"argline",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"_get_gpg_exec",
"(",
")",
":",
"raise",
"SaltRenderError",
"(",
"'GPG unavailable'",
")"... | Create a gpg object given a gpg_keydir, and then use it to try to decrypt
the data to be rendered. | [
"Create",
"a",
"gpg",
"object",
"given",
"a",
"gpg_keydir",
"and",
"then",
"use",
"it",
"to",
"try",
"to",
"decrypt",
"the",
"data",
"to",
"be",
"rendered",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/gpg.py#L402-L412 | train |
saltstack/salt | salt/beacons/telegram_bot_msg.py | validate | def validate(config):
'''
Validate the beacon configuration
'''
if not isinstance(config, list):
return False, ('Configuration for telegram_bot_msg '
'beacon must be a list.')
_config = {}
list(map(_config.update, config))
if not all(_config.get(required_config)
for required_config in ['token', 'accept_from']):
return False, ('Not all required configuration for '
'telegram_bot_msg are set.')
if not isinstance(_config.get('accept_from'), list):
return False, ('Configuration for telegram_bot_msg, '
'accept_from must be a list of usernames.')
return True, 'Valid beacon configuration.' | python | def validate(config):
'''
Validate the beacon configuration
'''
if not isinstance(config, list):
return False, ('Configuration for telegram_bot_msg '
'beacon must be a list.')
_config = {}
list(map(_config.update, config))
if not all(_config.get(required_config)
for required_config in ['token', 'accept_from']):
return False, ('Not all required configuration for '
'telegram_bot_msg are set.')
if not isinstance(_config.get('accept_from'), list):
return False, ('Configuration for telegram_bot_msg, '
'accept_from must be a list of usernames.')
return True, 'Valid beacon configuration.' | [
"def",
"validate",
"(",
"config",
")",
":",
"if",
"not",
"isinstance",
"(",
"config",
",",
"list",
")",
":",
"return",
"False",
",",
"(",
"'Configuration for telegram_bot_msg '",
"'beacon must be a list.'",
")",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
... | Validate the beacon configuration | [
"Validate",
"the",
"beacon",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/telegram_bot_msg.py#L35-L55 | train |
saltstack/salt | salt/beacons/telegram_bot_msg.py | beacon | def beacon(config):
'''
Emit a dict with a key "msgs" whose value is a list of messages
sent to the configured bot by one of the allowed usernames.
.. code-block:: yaml
beacons:
telegram_bot_msg:
- token: "<bot access token>"
- accept_from:
- "<valid username>"
- interval: 10
'''
_config = {}
list(map(_config.update, config))
log.debug('telegram_bot_msg beacon starting')
ret = []
output = {}
output['msgs'] = []
bot = telegram.Bot(_config['token'])
updates = bot.get_updates(limit=100, timeout=0, network_delay=10)
log.debug('Num updates: %d', len(updates))
if not updates:
log.debug('Telegram Bot beacon has no new messages')
return ret
latest_update_id = 0
for update in updates:
if update.message:
message = update.message
else:
message = update.edited_message
if update.update_id > latest_update_id:
latest_update_id = update.update_id
if message.chat.username in _config['accept_from']:
output['msgs'].append(message.to_dict())
# mark in the server that previous messages are processed
bot.get_updates(offset=latest_update_id + 1)
log.debug('Emitting %d messages.', len(output['msgs']))
if output['msgs']:
ret.append(output)
return ret | python | def beacon(config):
'''
Emit a dict with a key "msgs" whose value is a list of messages
sent to the configured bot by one of the allowed usernames.
.. code-block:: yaml
beacons:
telegram_bot_msg:
- token: "<bot access token>"
- accept_from:
- "<valid username>"
- interval: 10
'''
_config = {}
list(map(_config.update, config))
log.debug('telegram_bot_msg beacon starting')
ret = []
output = {}
output['msgs'] = []
bot = telegram.Bot(_config['token'])
updates = bot.get_updates(limit=100, timeout=0, network_delay=10)
log.debug('Num updates: %d', len(updates))
if not updates:
log.debug('Telegram Bot beacon has no new messages')
return ret
latest_update_id = 0
for update in updates:
if update.message:
message = update.message
else:
message = update.edited_message
if update.update_id > latest_update_id:
latest_update_id = update.update_id
if message.chat.username in _config['accept_from']:
output['msgs'].append(message.to_dict())
# mark in the server that previous messages are processed
bot.get_updates(offset=latest_update_id + 1)
log.debug('Emitting %d messages.', len(output['msgs']))
if output['msgs']:
ret.append(output)
return ret | [
"def",
"beacon",
"(",
"config",
")",
":",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config",
".",
"update",
",",
"config",
")",
")",
"log",
".",
"debug",
"(",
"'telegram_bot_msg beacon starting'",
")",
"ret",
"=",
"[",
"]",
"output",
"=",
... | Emit a dict with a key "msgs" whose value is a list of messages
sent to the configured bot by one of the allowed usernames.
.. code-block:: yaml
beacons:
telegram_bot_msg:
- token: "<bot access token>"
- accept_from:
- "<valid username>"
- interval: 10 | [
"Emit",
"a",
"dict",
"with",
"a",
"key",
"msgs",
"whose",
"value",
"is",
"a",
"list",
"of",
"messages",
"sent",
"to",
"the",
"configured",
"bot",
"by",
"one",
"of",
"the",
"allowed",
"usernames",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/telegram_bot_msg.py#L58-L110 | train |
saltstack/salt | salt/tops/cobbler.py | top | def top(**kwargs):
'''
Look up top data in Cobbler for a minion.
'''
url = __opts__['cobbler.url']
user = __opts__['cobbler.user']
password = __opts__['cobbler.password']
minion_id = kwargs['opts']['id']
log.info("Querying cobbler for information for %r", minion_id)
try:
server = salt.ext.six.moves.xmlrpc_client.Server(url, allow_none=True)
if user:
server.login(user, password)
data = server.get_blended_data(None, minion_id)
except Exception:
log.exception(
'Could not connect to cobbler.'
)
return {}
return {data['status']: data['mgmt_classes']} | python | def top(**kwargs):
'''
Look up top data in Cobbler for a minion.
'''
url = __opts__['cobbler.url']
user = __opts__['cobbler.user']
password = __opts__['cobbler.password']
minion_id = kwargs['opts']['id']
log.info("Querying cobbler for information for %r", minion_id)
try:
server = salt.ext.six.moves.xmlrpc_client.Server(url, allow_none=True)
if user:
server.login(user, password)
data = server.get_blended_data(None, minion_id)
except Exception:
log.exception(
'Could not connect to cobbler.'
)
return {}
return {data['status']: data['mgmt_classes']} | [
"def",
"top",
"(",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"__opts__",
"[",
"'cobbler.url'",
"]",
"user",
"=",
"__opts__",
"[",
"'cobbler.user'",
"]",
"password",
"=",
"__opts__",
"[",
"'cobbler.password'",
"]",
"minion_id",
"=",
"kwargs",
"[",
"'opts'",... | Look up top data in Cobbler for a minion. | [
"Look",
"up",
"top",
"data",
"in",
"Cobbler",
"for",
"a",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tops/cobbler.py#L39-L61 | train |
saltstack/salt | salt/modules/locate.py | stats | def stats():
'''
Returns statistics about the locate database
CLI Example:
.. code-block:: bash
salt '*' locate.stats
'''
ret = {}
cmd = 'locate -S'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
comps = line.strip().split()
if line.startswith('Database'):
ret['database'] = comps[1].replace(':', '')
continue
ret[' '.join(comps[1:])] = comps[0]
return ret | python | def stats():
'''
Returns statistics about the locate database
CLI Example:
.. code-block:: bash
salt '*' locate.stats
'''
ret = {}
cmd = 'locate -S'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
comps = line.strip().split()
if line.startswith('Database'):
ret['database'] = comps[1].replace(':', '')
continue
ret[' '.join(comps[1:])] = comps[0]
return ret | [
"def",
"stats",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"'locate -S'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"out",
":",
"comps",
"=",
"line",
".",
"strip",
"(",... | Returns statistics about the locate database
CLI Example:
.. code-block:: bash
salt '*' locate.stats | [
"Returns",
"statistics",
"about",
"the",
"locate",
"database"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/locate.py#L44-L63 | train |
saltstack/salt | salt/modules/locate.py | locate | def locate(pattern, database='', limit=0, **kwargs):
'''
Performs a file lookup. Valid options (and their defaults) are::
basename=False
count=False
existing=False
follow=True
ignore=False
nofollow=False
wholename=True
regex=False
database=<locate's default database>
limit=<integer, not set by default>
See the manpage for ``locate(1)`` for further explanation of these options.
CLI Example:
.. code-block:: bash
salt '*' locate.locate
'''
options = ''
toggles = {
'basename': 'b',
'count': 'c',
'existing': 'e',
'follow': 'L',
'ignore': 'i',
'nofollow': 'P',
'wholename': 'w',
}
for option in kwargs:
if bool(kwargs[option]) is True and option in toggles:
options += toggles[option]
if options:
options = '-{0}'.format(options)
if database:
options += ' -d {0}'.format(database)
if limit > 0:
options += ' -l {0}'.format(limit)
if 'regex' in kwargs and bool(kwargs['regex']) is True:
options += ' --regex'
cmd = 'locate {0} {1}'.format(options, pattern)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return out | python | def locate(pattern, database='', limit=0, **kwargs):
'''
Performs a file lookup. Valid options (and their defaults) are::
basename=False
count=False
existing=False
follow=True
ignore=False
nofollow=False
wholename=True
regex=False
database=<locate's default database>
limit=<integer, not set by default>
See the manpage for ``locate(1)`` for further explanation of these options.
CLI Example:
.. code-block:: bash
salt '*' locate.locate
'''
options = ''
toggles = {
'basename': 'b',
'count': 'c',
'existing': 'e',
'follow': 'L',
'ignore': 'i',
'nofollow': 'P',
'wholename': 'w',
}
for option in kwargs:
if bool(kwargs[option]) is True and option in toggles:
options += toggles[option]
if options:
options = '-{0}'.format(options)
if database:
options += ' -d {0}'.format(database)
if limit > 0:
options += ' -l {0}'.format(limit)
if 'regex' in kwargs and bool(kwargs['regex']) is True:
options += ' --regex'
cmd = 'locate {0} {1}'.format(options, pattern)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return out | [
"def",
"locate",
"(",
"pattern",
",",
"database",
"=",
"''",
",",
"limit",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"''",
"toggles",
"=",
"{",
"'basename'",
":",
"'b'",
",",
"'count'",
":",
"'c'",
",",
"'existing'",
":",
"'e'",
... | Performs a file lookup. Valid options (and their defaults) are::
basename=False
count=False
existing=False
follow=True
ignore=False
nofollow=False
wholename=True
regex=False
database=<locate's default database>
limit=<integer, not set by default>
See the manpage for ``locate(1)`` for further explanation of these options.
CLI Example:
.. code-block:: bash
salt '*' locate.locate | [
"Performs",
"a",
"file",
"lookup",
".",
"Valid",
"options",
"(",
"and",
"their",
"defaults",
")",
"are",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/locate.py#L81-L127 | train |
saltstack/salt | salt/states/lxd.py | init | def init(name, storage_backend='dir', trust_password=None,
network_address=None, network_port=None, storage_create_device=None,
storage_create_loop=None, storage_pool=None,
done_file='%SALT_CONFIG_DIR%/lxd_initialized'):
'''
Initalizes the LXD Daemon, as LXD doesn't tell if its initialized
we touch the the done_file and check if it exist.
This can only be called once per host unless you remove the done_file.
name :
Ignore this. This is just here for salt.
storage_backend :
Storage backend to use (zfs or dir, default: dir)
trust_password :
Password required to add new clients
network_address : None
Address to bind LXD to (default: none)
network_port : None
Port to bind LXD to (Default: 8443)
storage_create_device : None
Setup device based storage using this DEVICE
storage_create_loop : None
Setup loop based storage with this SIZE in GB
storage_pool : None
Storage pool to use or create
done_file :
Path where we check that this method has been called,
as it can run only once and theres currently no way
to ask LXD if init has been called.
'''
ret = {
'name': name,
'storage_backend': storage_backend,
'trust_password': True if trust_password is not None else False,
'network_address': network_address,
'network_port': network_port,
'storage_create_device': storage_create_device,
'storage_create_loop': storage_create_loop,
'storage_pool': storage_pool,
'done_file': done_file,
}
# TODO: Get a better path and don't hardcode '/etc/salt'
done_file = done_file.replace('%SALT_CONFIG_DIR%', '/etc/salt')
if os.path.exists(done_file):
# Success we already did that.
return _success(ret, 'LXD is already initialized')
if __opts__['test']:
return _success(ret, 'Would initialize LXD')
# We always touch the done_file, so when LXD is already initialized
# we don't run this over and over.
__salt__['file.touch'](done_file)
try:
__salt__['lxd.init'](
storage_backend if storage_backend else None,
trust_password if trust_password else None,
network_address if network_address else None,
network_port if network_port else None,
storage_create_device if storage_create_device else None,
storage_create_loop if storage_create_loop else None,
storage_pool if storage_pool else None
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
return _success(ret, 'Initialized the LXD Daemon') | python | def init(name, storage_backend='dir', trust_password=None,
network_address=None, network_port=None, storage_create_device=None,
storage_create_loop=None, storage_pool=None,
done_file='%SALT_CONFIG_DIR%/lxd_initialized'):
'''
Initalizes the LXD Daemon, as LXD doesn't tell if its initialized
we touch the the done_file and check if it exist.
This can only be called once per host unless you remove the done_file.
name :
Ignore this. This is just here for salt.
storage_backend :
Storage backend to use (zfs or dir, default: dir)
trust_password :
Password required to add new clients
network_address : None
Address to bind LXD to (default: none)
network_port : None
Port to bind LXD to (Default: 8443)
storage_create_device : None
Setup device based storage using this DEVICE
storage_create_loop : None
Setup loop based storage with this SIZE in GB
storage_pool : None
Storage pool to use or create
done_file :
Path where we check that this method has been called,
as it can run only once and theres currently no way
to ask LXD if init has been called.
'''
ret = {
'name': name,
'storage_backend': storage_backend,
'trust_password': True if trust_password is not None else False,
'network_address': network_address,
'network_port': network_port,
'storage_create_device': storage_create_device,
'storage_create_loop': storage_create_loop,
'storage_pool': storage_pool,
'done_file': done_file,
}
# TODO: Get a better path and don't hardcode '/etc/salt'
done_file = done_file.replace('%SALT_CONFIG_DIR%', '/etc/salt')
if os.path.exists(done_file):
# Success we already did that.
return _success(ret, 'LXD is already initialized')
if __opts__['test']:
return _success(ret, 'Would initialize LXD')
# We always touch the done_file, so when LXD is already initialized
# we don't run this over and over.
__salt__['file.touch'](done_file)
try:
__salt__['lxd.init'](
storage_backend if storage_backend else None,
trust_password if trust_password else None,
network_address if network_address else None,
network_port if network_port else None,
storage_create_device if storage_create_device else None,
storage_create_loop if storage_create_loop else None,
storage_pool if storage_pool else None
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
return _success(ret, 'Initialized the LXD Daemon') | [
"def",
"init",
"(",
"name",
",",
"storage_backend",
"=",
"'dir'",
",",
"trust_password",
"=",
"None",
",",
"network_address",
"=",
"None",
",",
"network_port",
"=",
"None",
",",
"storage_create_device",
"=",
"None",
",",
"storage_create_loop",
"=",
"None",
","... | Initalizes the LXD Daemon, as LXD doesn't tell if its initialized
we touch the the done_file and check if it exist.
This can only be called once per host unless you remove the done_file.
name :
Ignore this. This is just here for salt.
storage_backend :
Storage backend to use (zfs or dir, default: dir)
trust_password :
Password required to add new clients
network_address : None
Address to bind LXD to (default: none)
network_port : None
Port to bind LXD to (Default: 8443)
storage_create_device : None
Setup device based storage using this DEVICE
storage_create_loop : None
Setup loop based storage with this SIZE in GB
storage_pool : None
Storage pool to use or create
done_file :
Path where we check that this method has been called,
as it can run only once and theres currently no way
to ask LXD if init has been called. | [
"Initalizes",
"the",
"LXD",
"Daemon",
"as",
"LXD",
"doesn",
"t",
"tell",
"if",
"its",
"initialized",
"we",
"touch",
"the",
"the",
"done_file",
"and",
"check",
"if",
"it",
"exist",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd.py#L54-L132 | train |
saltstack/salt | salt/states/lxd.py | config_managed | def config_managed(name, value, force_password=False):
'''
Manage a LXD Server config setting.
name :
The name of the config key.
value :
Its value.
force_password : False
Set this to True if you want to set the password on every run.
As we can't retrieve the password from LXD we can't check
if the current one is the same as the given one.
'''
ret = {
'name': name,
'value': value if name != 'core.trust_password' else True,
'force_password': force_password
}
try:
current_value = __salt__['lxd.config_get'](name)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
if (name == _password_config_key and
(not force_password or not current_value)):
msg = (
('"{0}" is already set '
'(we don\'t known if the password is correct)').format(name)
)
return _success(ret, msg)
elif six.text_type(value) == current_value:
msg = ('"{0}" is already set to "{1}"'.format(name, value))
return _success(ret, msg)
if __opts__['test']:
if name == _password_config_key:
msg = 'Would set the LXD password'
ret['changes'] = {'password': msg}
return _unchanged(ret, msg)
else:
msg = 'Would set the "{0}" to "{1}"'.format(name, value)
ret['changes'] = {name: msg}
return _unchanged(ret, msg)
result_msg = ''
try:
result_msg = __salt__['lxd.config_set'](name, value)[0]
if name == _password_config_key:
ret['changes'] = {
name: 'Changed the password'
}
else:
ret['changes'] = {
name: 'Changed from "{0}" to {1}"'.format(
current_value, value
)
}
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
return _success(ret, result_msg) | python | def config_managed(name, value, force_password=False):
'''
Manage a LXD Server config setting.
name :
The name of the config key.
value :
Its value.
force_password : False
Set this to True if you want to set the password on every run.
As we can't retrieve the password from LXD we can't check
if the current one is the same as the given one.
'''
ret = {
'name': name,
'value': value if name != 'core.trust_password' else True,
'force_password': force_password
}
try:
current_value = __salt__['lxd.config_get'](name)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
if (name == _password_config_key and
(not force_password or not current_value)):
msg = (
('"{0}" is already set '
'(we don\'t known if the password is correct)').format(name)
)
return _success(ret, msg)
elif six.text_type(value) == current_value:
msg = ('"{0}" is already set to "{1}"'.format(name, value))
return _success(ret, msg)
if __opts__['test']:
if name == _password_config_key:
msg = 'Would set the LXD password'
ret['changes'] = {'password': msg}
return _unchanged(ret, msg)
else:
msg = 'Would set the "{0}" to "{1}"'.format(name, value)
ret['changes'] = {name: msg}
return _unchanged(ret, msg)
result_msg = ''
try:
result_msg = __salt__['lxd.config_set'](name, value)[0]
if name == _password_config_key:
ret['changes'] = {
name: 'Changed the password'
}
else:
ret['changes'] = {
name: 'Changed from "{0}" to {1}"'.format(
current_value, value
)
}
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
return _success(ret, result_msg) | [
"def",
"config_managed",
"(",
"name",
",",
"value",
",",
"force_password",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'value'",
":",
"value",
"if",
"name",
"!=",
"'core.trust_password'",
"else",
"True",
",",
"'force_password'",
"... | Manage a LXD Server config setting.
name :
The name of the config key.
value :
Its value.
force_password : False
Set this to True if you want to set the password on every run.
As we can't retrieve the password from LXD we can't check
if the current one is the same as the given one. | [
"Manage",
"a",
"LXD",
"Server",
"config",
"setting",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd.py#L135-L201 | train |
saltstack/salt | salt/states/lxd.py | authenticate | def authenticate(name, remote_addr, password, cert, key, verify_cert=True):
'''
Authenticate with a remote peer.
.. notes:
This function makes every time you run this a connection
to remote_addr, you better call this only once.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
password :
The PaSsW0rD
cert :
PEM Formatted SSL Zertifikate.
Examples:
/root/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
/root/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
name:
Ignore this. This is just here for salt.
'''
ret = {
'name': name,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert
}
try:
client = __salt__['lxd.pylxd_client_get'](
remote_addr, cert, key, verify_cert
)
except SaltInvocationError as e:
return _error(ret, six.text_type(e))
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
if client.trusted:
return _success(ret, "Already authenticated.")
try:
result = __salt__['lxd.authenticate'](
remote_addr, password, cert, key, verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
if result is not True:
return _error(
ret,
"Failed to authenticate with peer: {0}".format(remote_addr)
)
msg = "Successfully authenticated with peer: {0}".format(remote_addr)
ret['changes'] = msg
return _success(
ret,
msg
) | python | def authenticate(name, remote_addr, password, cert, key, verify_cert=True):
'''
Authenticate with a remote peer.
.. notes:
This function makes every time you run this a connection
to remote_addr, you better call this only once.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
password :
The PaSsW0rD
cert :
PEM Formatted SSL Zertifikate.
Examples:
/root/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
/root/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
name:
Ignore this. This is just here for salt.
'''
ret = {
'name': name,
'remote_addr': remote_addr,
'cert': cert,
'key': key,
'verify_cert': verify_cert
}
try:
client = __salt__['lxd.pylxd_client_get'](
remote_addr, cert, key, verify_cert
)
except SaltInvocationError as e:
return _error(ret, six.text_type(e))
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
if client.trusted:
return _success(ret, "Already authenticated.")
try:
result = __salt__['lxd.authenticate'](
remote_addr, password, cert, key, verify_cert
)
except CommandExecutionError as e:
return _error(ret, six.text_type(e))
if result is not True:
return _error(
ret,
"Failed to authenticate with peer: {0}".format(remote_addr)
)
msg = "Successfully authenticated with peer: {0}".format(remote_addr)
ret['changes'] = msg
return _success(
ret,
msg
) | [
"def",
"authenticate",
"(",
"name",
",",
"remote_addr",
",",
"password",
",",
"cert",
",",
"key",
",",
"verify_cert",
"=",
"True",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'remote_addr'",
":",
"remote_addr",
",",
"'cert'",
":",
"cert",
"... | Authenticate with a remote peer.
.. notes:
This function makes every time you run this a connection
to remote_addr, you better call this only once.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
password :
The PaSsW0rD
cert :
PEM Formatted SSL Zertifikate.
Examples:
/root/.config/lxc/client.crt
key :
PEM Formatted SSL Key.
Examples:
/root/.config/lxc/client.key
verify_cert : True
Wherever to verify the cert, this is by default True
but in the most cases you want to set it off as LXD
normaly uses self-signed certificates.
name:
Ignore this. This is just here for salt. | [
"Authenticate",
"with",
"a",
"remote",
"peer",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxd.py#L204-L282 | train |
saltstack/salt | salt/states/ipmi.py | boot_device | def boot_device(name='default', **kwargs):
'''
Request power state change
name = ``default``
* network -- Request network boot
* hd -- Boot from hard drive
* safe -- Boot from hard drive, requesting 'safe mode'
* optical -- boot from CD/DVD/BD drive
* setup -- Boot into setup utility
* default -- remove any IPMI directed boot device request
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
org = __salt__['ipmi.get_bootdev'](**kwargs)
if 'bootdev' in org:
org = org['bootdev']
if org == name:
ret['result'] = True
ret['comment'] = 'system already in this state'
return ret
if __opts__['test']:
ret['comment'] = 'would change boot device'
ret['result'] = None
ret['changes'] = {'old': org, 'new': name}
return ret
outdddd = __salt__['ipmi.set_bootdev'](bootdev=name, **kwargs)
ret['comment'] = 'changed boot device'
ret['result'] = True
ret['changes'] = {'old': org, 'new': name}
return ret | python | def boot_device(name='default', **kwargs):
'''
Request power state change
name = ``default``
* network -- Request network boot
* hd -- Boot from hard drive
* safe -- Boot from hard drive, requesting 'safe mode'
* optical -- boot from CD/DVD/BD drive
* setup -- Boot into setup utility
* default -- remove any IPMI directed boot device request
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
org = __salt__['ipmi.get_bootdev'](**kwargs)
if 'bootdev' in org:
org = org['bootdev']
if org == name:
ret['result'] = True
ret['comment'] = 'system already in this state'
return ret
if __opts__['test']:
ret['comment'] = 'would change boot device'
ret['result'] = None
ret['changes'] = {'old': org, 'new': name}
return ret
outdddd = __salt__['ipmi.set_bootdev'](bootdev=name, **kwargs)
ret['comment'] = 'changed boot device'
ret['result'] = True
ret['changes'] = {'old': org, 'new': name}
return ret | [
"def",
"boot_device",
"(",
"name",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"org",
"=",
"__salt__"... | Request power state change
name = ``default``
* network -- Request network boot
* hd -- Boot from hard drive
* safe -- Boot from hard drive, requesting 'safe mode'
* optical -- boot from CD/DVD/BD drive
* setup -- Boot into setup utility
* default -- remove any IPMI directed boot device request
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None | [
"Request",
"power",
"state",
"change"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ipmi.py#L54-L93 | train |
saltstack/salt | salt/states/ipmi.py | power | def power(name='power_on', wait=300, **kwargs):
'''
Request power state change
name
Ensure power state one of:
* power_on -- system turn on
* power_off -- system turn off (without waiting for OS)
* shutdown -- request OS proper shutdown
* reset -- reset (without waiting for OS)
* boot -- If system is off, then 'on', else 'reset'
wait
wait X seconds for the job to complete before forcing.
(defaults to 300 seconds)
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
org = __salt__['ipmi.get_power'](**kwargs)
state_map = {
'off': 'off',
'on': 'on',
'power_off': 'off',
'power_on': 'on',
'shutdown': 'off',
'reset': 'na',
'boot': 'na'
}
if org == state_map[name]:
ret['result'] = True
ret['comment'] = 'system already in this state'
return ret
if __opts__['test']:
ret['comment'] = 'would power: {0} system'.format(name)
ret['result'] = None
ret['changes'] = {'old': org, 'new': name}
return ret
outdddd = __salt__['ipmi.set_power'](name, wait=wait, **kwargs)
ret['comment'] = 'changed system power'
ret['result'] = True
ret['changes'] = {'old': org, 'new': name}
return ret | python | def power(name='power_on', wait=300, **kwargs):
'''
Request power state change
name
Ensure power state one of:
* power_on -- system turn on
* power_off -- system turn off (without waiting for OS)
* shutdown -- request OS proper shutdown
* reset -- reset (without waiting for OS)
* boot -- If system is off, then 'on', else 'reset'
wait
wait X seconds for the job to complete before forcing.
(defaults to 300 seconds)
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
org = __salt__['ipmi.get_power'](**kwargs)
state_map = {
'off': 'off',
'on': 'on',
'power_off': 'off',
'power_on': 'on',
'shutdown': 'off',
'reset': 'na',
'boot': 'na'
}
if org == state_map[name]:
ret['result'] = True
ret['comment'] = 'system already in this state'
return ret
if __opts__['test']:
ret['comment'] = 'would power: {0} system'.format(name)
ret['result'] = None
ret['changes'] = {'old': org, 'new': name}
return ret
outdddd = __salt__['ipmi.set_power'](name, wait=wait, **kwargs)
ret['comment'] = 'changed system power'
ret['result'] = True
ret['changes'] = {'old': org, 'new': name}
return ret | [
"def",
"power",
"(",
"name",
"=",
"'power_on'",
",",
"wait",
"=",
"300",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
... | Request power state change
name
Ensure power state one of:
* power_on -- system turn on
* power_off -- system turn off (without waiting for OS)
* shutdown -- request OS proper shutdown
* reset -- reset (without waiting for OS)
* boot -- If system is off, then 'on', else 'reset'
wait
wait X seconds for the job to complete before forcing.
(defaults to 300 seconds)
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None | [
"Request",
"power",
"state",
"change"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ipmi.py#L96-L147 | train |
saltstack/salt | salt/states/ipmi.py | user_present | def user_present(name, uid, password, channel=14, callback=False,
link_auth=True, ipmi_msg=True, privilege_level='administrator', **kwargs):
'''
Ensure IPMI user and user privileges.
name
name of user (limit 16 bytes)
uid
user id number (1 to 7)
password
user password (limit 16 bytes)
channel
ipmi channel defaults to 14 for auto
callback
User Restricted to Callback
False = User Privilege Limit is determined by the User Privilege Limit
parameter privilege_level, for both callback and non-callback connections.
True = User Privilege Limit is determined by the privilege_level
parameter for callback connections, but is restricted to Callback
level for non-callback connections. Thus, a user can only initiate
a Callback when they 'call in' to the BMC, but once the callback
connection has been made, the user could potentially establish a
session as an Operator.
link_auth
User Link authentication
True/False
user name and password information will be used for link
authentication, e.g. PPP CHAP) for the given channel. Link
authentication itself is a global setting for the channel and is
enabled/disabled via the serial/modem configuration parameters.
ipmi_msg
User IPMI Messaging
True/False
user name and password information will be used for IPMI
Messaging. In this case, 'IPMI Messaging' refers to the ability to
execute generic IPMI commands that are not associated with a
particular payload type. For example, if IPMI Messaging is disabled for
a user, but that user is enabled for activating the SOL
payload type, then IPMI commands associated with SOL and session
management, such as Get SOL Configuration Parameters and Close Session
are available, but generic IPMI commands such as Get SEL Time are
unavailable.)
ipmi_msg
privilege_level
* callback
* user
* operator
* administrator
* proprietary
* no_access
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
org_user = __salt__['ipmi.get_user'](uid=uid, channel=channel, **kwargs)
change = False
if org_user['access']['callback'] != callback:
change = True
if org_user['access']['link_auth'] != link_auth:
change = True
if org_user['access']['ipmi_msg'] != ipmi_msg:
change = True
if org_user['access']['privilege_level'] != privilege_level:
change = True
if __salt__['ipmi.set_user_password'](uid, mode='test_password',
password=password, **kwargs) is False:
change = True
if change is False:
ret['result'] = True
ret['comment'] = 'user already present'
return ret
if __opts__['test']:
ret['comment'] = 'would (re)create user'
ret['result'] = None
ret['changes'] = {'old': org_user, 'new': name}
return ret
__salt__['ipmi.ensure_user'](uid,
name,
password,
channel,
callback,
link_auth,
ipmi_msg,
privilege_level,
**kwargs)
current_user = __salt__['ipmi.get_user'](uid=uid, channel=channel, **kwargs)
ret['comment'] = '(re)created user'
ret['result'] = True
ret['changes'] = {'old': org_user, 'new': current_user}
return ret | python | def user_present(name, uid, password, channel=14, callback=False,
link_auth=True, ipmi_msg=True, privilege_level='administrator', **kwargs):
'''
Ensure IPMI user and user privileges.
name
name of user (limit 16 bytes)
uid
user id number (1 to 7)
password
user password (limit 16 bytes)
channel
ipmi channel defaults to 14 for auto
callback
User Restricted to Callback
False = User Privilege Limit is determined by the User Privilege Limit
parameter privilege_level, for both callback and non-callback connections.
True = User Privilege Limit is determined by the privilege_level
parameter for callback connections, but is restricted to Callback
level for non-callback connections. Thus, a user can only initiate
a Callback when they 'call in' to the BMC, but once the callback
connection has been made, the user could potentially establish a
session as an Operator.
link_auth
User Link authentication
True/False
user name and password information will be used for link
authentication, e.g. PPP CHAP) for the given channel. Link
authentication itself is a global setting for the channel and is
enabled/disabled via the serial/modem configuration parameters.
ipmi_msg
User IPMI Messaging
True/False
user name and password information will be used for IPMI
Messaging. In this case, 'IPMI Messaging' refers to the ability to
execute generic IPMI commands that are not associated with a
particular payload type. For example, if IPMI Messaging is disabled for
a user, but that user is enabled for activating the SOL
payload type, then IPMI commands associated with SOL and session
management, such as Get SOL Configuration Parameters and Close Session
are available, but generic IPMI commands such as Get SEL Time are
unavailable.)
ipmi_msg
privilege_level
* callback
* user
* operator
* administrator
* proprietary
* no_access
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
org_user = __salt__['ipmi.get_user'](uid=uid, channel=channel, **kwargs)
change = False
if org_user['access']['callback'] != callback:
change = True
if org_user['access']['link_auth'] != link_auth:
change = True
if org_user['access']['ipmi_msg'] != ipmi_msg:
change = True
if org_user['access']['privilege_level'] != privilege_level:
change = True
if __salt__['ipmi.set_user_password'](uid, mode='test_password',
password=password, **kwargs) is False:
change = True
if change is False:
ret['result'] = True
ret['comment'] = 'user already present'
return ret
if __opts__['test']:
ret['comment'] = 'would (re)create user'
ret['result'] = None
ret['changes'] = {'old': org_user, 'new': name}
return ret
__salt__['ipmi.ensure_user'](uid,
name,
password,
channel,
callback,
link_auth,
ipmi_msg,
privilege_level,
**kwargs)
current_user = __salt__['ipmi.get_user'](uid=uid, channel=channel, **kwargs)
ret['comment'] = '(re)created user'
ret['result'] = True
ret['changes'] = {'old': org_user, 'new': current_user}
return ret | [
"def",
"user_present",
"(",
"name",
",",
"uid",
",",
"password",
",",
"channel",
"=",
"14",
",",
"callback",
"=",
"False",
",",
"link_auth",
"=",
"True",
",",
"ipmi_msg",
"=",
"True",
",",
"privilege_level",
"=",
"'administrator'",
",",
"*",
"*",
"kwargs... | Ensure IPMI user and user privileges.
name
name of user (limit 16 bytes)
uid
user id number (1 to 7)
password
user password (limit 16 bytes)
channel
ipmi channel defaults to 14 for auto
callback
User Restricted to Callback
False = User Privilege Limit is determined by the User Privilege Limit
parameter privilege_level, for both callback and non-callback connections.
True = User Privilege Limit is determined by the privilege_level
parameter for callback connections, but is restricted to Callback
level for non-callback connections. Thus, a user can only initiate
a Callback when they 'call in' to the BMC, but once the callback
connection has been made, the user could potentially establish a
session as an Operator.
link_auth
User Link authentication
True/False
user name and password information will be used for link
authentication, e.g. PPP CHAP) for the given channel. Link
authentication itself is a global setting for the channel and is
enabled/disabled via the serial/modem configuration parameters.
ipmi_msg
User IPMI Messaging
True/False
user name and password information will be used for IPMI
Messaging. In this case, 'IPMI Messaging' refers to the ability to
execute generic IPMI commands that are not associated with a
particular payload type. For example, if IPMI Messaging is disabled for
a user, but that user is enabled for activating the SOL
payload type, then IPMI commands associated with SOL and session
management, such as Get SOL Configuration Parameters and Close Session
are available, but generic IPMI commands such as Get SEL Time are
unavailable.)
ipmi_msg
privilege_level
* callback
* user
* operator
* administrator
* proprietary
* no_access
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None | [
"Ensure",
"IPMI",
"user",
"and",
"user",
"privileges",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ipmi.py#L150-L257 | train |
saltstack/salt | salt/states/ipmi.py | user_absent | def user_absent(name, channel=14, **kwargs):
'''
Remove user
Delete all user (uid) records having the matching name.
name
string name of user to delete
channel
channel to remove user access from defaults to 14 for auto.
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
user_id_list = __salt__['ipmi.get_name_uids'](name, channel, **kwargs)
if not user_id_list:
ret['result'] = True
ret['comment'] = 'user already absent'
return ret
if __opts__['test']:
ret['comment'] = 'would delete user(s)'
ret['result'] = None
ret['changes'] = {'delete': user_id_list}
return ret
for uid in user_id_list:
__salt__['ipmi.delete_user'](uid, channel, **kwargs)
ret['comment'] = 'user(s) removed'
ret['changes'] = {'old': user_id_list, 'new': 'None'}
return ret | python | def user_absent(name, channel=14, **kwargs):
'''
Remove user
Delete all user (uid) records having the matching name.
name
string name of user to delete
channel
channel to remove user access from defaults to 14 for auto.
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
user_id_list = __salt__['ipmi.get_name_uids'](name, channel, **kwargs)
if not user_id_list:
ret['result'] = True
ret['comment'] = 'user already absent'
return ret
if __opts__['test']:
ret['comment'] = 'would delete user(s)'
ret['result'] = None
ret['changes'] = {'delete': user_id_list}
return ret
for uid in user_id_list:
__salt__['ipmi.delete_user'](uid, channel, **kwargs)
ret['comment'] = 'user(s) removed'
ret['changes'] = {'old': user_id_list, 'new': 'None'}
return ret | [
"def",
"user_absent",
"(",
"name",
",",
"channel",
"=",
"14",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"user_id_list... | Remove user
Delete all user (uid) records having the matching name.
name
string name of user to delete
channel
channel to remove user access from defaults to 14 for auto.
kwargs
- api_host=localhost
- api_user=admin
- api_pass=
- api_port=623
- api_kg=None | [
"Remove",
"user",
"Delete",
"all",
"user",
"(",
"uid",
")",
"records",
"having",
"the",
"matching",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ipmi.py#L260-L297 | train |
saltstack/salt | salt/matchers/cache_match.py | mmatch | def mmatch(expr,
delimiter,
greedy,
search_type,
regex_match=False,
exact_match=False,
opts=None):
'''
Helper function to search for minions in master caches
If 'greedy' return accepted minions that matched by the condition or absent in the cache.
If not 'greedy' return the only minions have cache data and matched by the condition.
'''
if not opts:
opts = __opts__
ckminions = salt.utils.minions.CkMinions(opts)
return ckminions._check_cache_minions(expr, delimiter, greedy,
search_type, regex_match=regex_match,
exact_match=exact_match) | python | def mmatch(expr,
delimiter,
greedy,
search_type,
regex_match=False,
exact_match=False,
opts=None):
'''
Helper function to search for minions in master caches
If 'greedy' return accepted minions that matched by the condition or absent in the cache.
If not 'greedy' return the only minions have cache data and matched by the condition.
'''
if not opts:
opts = __opts__
ckminions = salt.utils.minions.CkMinions(opts)
return ckminions._check_cache_minions(expr, delimiter, greedy,
search_type, regex_match=regex_match,
exact_match=exact_match) | [
"def",
"mmatch",
"(",
"expr",
",",
"delimiter",
",",
"greedy",
",",
"search_type",
",",
"regex_match",
"=",
"False",
",",
"exact_match",
"=",
"False",
",",
"opts",
"=",
"None",
")",
":",
"if",
"not",
"opts",
":",
"opts",
"=",
"__opts__",
"ckminions",
"... | Helper function to search for minions in master caches
If 'greedy' return accepted minions that matched by the condition or absent in the cache.
If not 'greedy' return the only minions have cache data and matched by the condition. | [
"Helper",
"function",
"to",
"search",
"for",
"minions",
"in",
"master",
"caches",
"If",
"greedy",
"return",
"accepted",
"minions",
"that",
"matched",
"by",
"the",
"condition",
"or",
"absent",
"in",
"the",
"cache",
".",
"If",
"not",
"greedy",
"return",
"the",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/cache_match.py#L15-L34 | train |
saltstack/salt | salt/states/boto_lc.py | present | def present(
name,
image_id,
key_name=None,
vpc_id=None,
vpc_name=None,
security_groups=None,
user_data=None,
cloud_init=None,
instance_type='m1.small',
kernel_id=None,
ramdisk_id=None,
block_device_mappings=None,
delete_on_termination=None,
instance_monitoring=False,
spot_price=None,
instance_profile_name=None,
ebs_optimized=False,
associate_public_ip_address=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure the launch configuration exists.
name
Name of the launch configuration.
image_id
AMI to use for instances. AMI must exist or creation of the launch
configuration will fail.
key_name
Name of the EC2 key pair to use for instances. Key must exist or
creation of the launch configuration will fail.
vpc_id
The VPC id where the security groups are defined. Only necessary when
using named security groups that exist outside of the default VPC.
Mutually exclusive with vpc_name.
vpc_name
Name of the VPC where the security groups are defined. Only Necessary
when using named security groups that exist outside of the default VPC.
Mutually exclusive with vpc_id.
security_groups
List of Names or security group id’s of the security groups with which
to associate the EC2 instances or VPC instances, respectively. Security
groups must exist, or creation of the launch configuration will fail.
user_data
The user data available to launched EC2 instances.
cloud_init
A dict of cloud_init configuration. Currently supported keys:
boothooks, scripts and cloud-config.
Mutually exclusive with user_data.
instance_type
The instance type. ex: m1.small.
kernel_id
The kernel id for the instance.
ramdisk_id
The RAM disk ID for the instance.
block_device_mappings
A dict of block device mappings that contains a dict
with volume_type, delete_on_termination, iops, size, encrypted,
snapshot_id.
volume_type
Indicates what volume type to use. Valid values are standard, io1, gp2.
Default is standard.
delete_on_termination
Whether the volume should be explicitly marked for deletion when its instance is
terminated (True), or left around (False). If not provided, or None is explicitly passed,
the default AWS behaviour is used, which is True for ROOT volumes of instances, and
False for all others.
iops
For Provisioned IOPS (SSD) volumes only. The number of I/O operations per
second (IOPS) to provision for the volume.
size
Desired volume size (in GiB).
encrypted
Indicates whether the volume should be encrypted. Encrypted EBS volumes must
be attached to instances that support Amazon EBS encryption. Volumes that are
created from encrypted snapshots are automatically encrypted. There is no way
to create an encrypted volume from an unencrypted snapshot or an unencrypted
volume from an encrypted snapshot.
instance_monitoring
Whether instances in group are launched with detailed monitoring.
spot_price
The spot price you are bidding. Only applies if you are building an
autoscaling group with spot instances.
instance_profile_name
The name or the Amazon Resource Name (ARN) of the instance profile
associated with the IAM role for the instance. Instance profile must
exist or the creation of the launch configuration will fail.
ebs_optimized
Specifies whether the instance is optimized for EBS I/O (true) or not
(false).
associate_public_ip_address
Used for Auto Scaling groups that launch instances into an Amazon
Virtual Private Cloud. Specifies whether to assign a public IP address
to each instance launched in a Amazon VPC.
region
The region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
if user_data and cloud_init:
raise SaltInvocationError('user_data and cloud_init are mutually'
' exclusive options.')
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_asg.launch_configuration_exists'](name,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not exists:
if __opts__['test']:
msg = 'Launch configuration set to be created.'
ret['comment'] = msg
ret['result'] = None
return ret
if cloud_init:
user_data = __salt__['boto_asg.get_cloud_init_mime'](cloud_init)
# TODO: Ensure image_id, key_name, security_groups and instance_profile
# exist, or throw an invocation error.
created = __salt__['boto_asg.create_launch_configuration'](
name,
image_id,
key_name=key_name,
vpc_id=vpc_id,
vpc_name=vpc_name,
security_groups=security_groups,
user_data=user_data,
instance_type=instance_type,
kernel_id=kernel_id,
ramdisk_id=ramdisk_id,
block_device_mappings=block_device_mappings,
delete_on_termination=delete_on_termination,
instance_monitoring=instance_monitoring,
spot_price=spot_price,
instance_profile_name=instance_profile_name,
ebs_optimized=ebs_optimized,
associate_public_ip_address=associate_public_ip_address,
region=region,
key=key,
keyid=keyid,
profile=profile)
if created:
ret['changes']['old'] = None
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to create launch configuration.'
else:
ret['comment'] = 'Launch configuration present.'
return ret | python | def present(
name,
image_id,
key_name=None,
vpc_id=None,
vpc_name=None,
security_groups=None,
user_data=None,
cloud_init=None,
instance_type='m1.small',
kernel_id=None,
ramdisk_id=None,
block_device_mappings=None,
delete_on_termination=None,
instance_monitoring=False,
spot_price=None,
instance_profile_name=None,
ebs_optimized=False,
associate_public_ip_address=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure the launch configuration exists.
name
Name of the launch configuration.
image_id
AMI to use for instances. AMI must exist or creation of the launch
configuration will fail.
key_name
Name of the EC2 key pair to use for instances. Key must exist or
creation of the launch configuration will fail.
vpc_id
The VPC id where the security groups are defined. Only necessary when
using named security groups that exist outside of the default VPC.
Mutually exclusive with vpc_name.
vpc_name
Name of the VPC where the security groups are defined. Only Necessary
when using named security groups that exist outside of the default VPC.
Mutually exclusive with vpc_id.
security_groups
List of Names or security group id’s of the security groups with which
to associate the EC2 instances or VPC instances, respectively. Security
groups must exist, or creation of the launch configuration will fail.
user_data
The user data available to launched EC2 instances.
cloud_init
A dict of cloud_init configuration. Currently supported keys:
boothooks, scripts and cloud-config.
Mutually exclusive with user_data.
instance_type
The instance type. ex: m1.small.
kernel_id
The kernel id for the instance.
ramdisk_id
The RAM disk ID for the instance.
block_device_mappings
A dict of block device mappings that contains a dict
with volume_type, delete_on_termination, iops, size, encrypted,
snapshot_id.
volume_type
Indicates what volume type to use. Valid values are standard, io1, gp2.
Default is standard.
delete_on_termination
Whether the volume should be explicitly marked for deletion when its instance is
terminated (True), or left around (False). If not provided, or None is explicitly passed,
the default AWS behaviour is used, which is True for ROOT volumes of instances, and
False for all others.
iops
For Provisioned IOPS (SSD) volumes only. The number of I/O operations per
second (IOPS) to provision for the volume.
size
Desired volume size (in GiB).
encrypted
Indicates whether the volume should be encrypted. Encrypted EBS volumes must
be attached to instances that support Amazon EBS encryption. Volumes that are
created from encrypted snapshots are automatically encrypted. There is no way
to create an encrypted volume from an unencrypted snapshot or an unencrypted
volume from an encrypted snapshot.
instance_monitoring
Whether instances in group are launched with detailed monitoring.
spot_price
The spot price you are bidding. Only applies if you are building an
autoscaling group with spot instances.
instance_profile_name
The name or the Amazon Resource Name (ARN) of the instance profile
associated with the IAM role for the instance. Instance profile must
exist or the creation of the launch configuration will fail.
ebs_optimized
Specifies whether the instance is optimized for EBS I/O (true) or not
(false).
associate_public_ip_address
Used for Auto Scaling groups that launch instances into an Amazon
Virtual Private Cloud. Specifies whether to assign a public IP address
to each instance launched in a Amazon VPC.
region
The region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
if user_data and cloud_init:
raise SaltInvocationError('user_data and cloud_init are mutually'
' exclusive options.')
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_asg.launch_configuration_exists'](name,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not exists:
if __opts__['test']:
msg = 'Launch configuration set to be created.'
ret['comment'] = msg
ret['result'] = None
return ret
if cloud_init:
user_data = __salt__['boto_asg.get_cloud_init_mime'](cloud_init)
# TODO: Ensure image_id, key_name, security_groups and instance_profile
# exist, or throw an invocation error.
created = __salt__['boto_asg.create_launch_configuration'](
name,
image_id,
key_name=key_name,
vpc_id=vpc_id,
vpc_name=vpc_name,
security_groups=security_groups,
user_data=user_data,
instance_type=instance_type,
kernel_id=kernel_id,
ramdisk_id=ramdisk_id,
block_device_mappings=block_device_mappings,
delete_on_termination=delete_on_termination,
instance_monitoring=instance_monitoring,
spot_price=spot_price,
instance_profile_name=instance_profile_name,
ebs_optimized=ebs_optimized,
associate_public_ip_address=associate_public_ip_address,
region=region,
key=key,
keyid=keyid,
profile=profile)
if created:
ret['changes']['old'] = None
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to create launch configuration.'
else:
ret['comment'] = 'Launch configuration present.'
return ret | [
"def",
"present",
"(",
"name",
",",
"image_id",
",",
"key_name",
"=",
"None",
",",
"vpc_id",
"=",
"None",
",",
"vpc_name",
"=",
"None",
",",
"security_groups",
"=",
"None",
",",
"user_data",
"=",
"None",
",",
"cloud_init",
"=",
"None",
",",
"instance_typ... | Ensure the launch configuration exists.
name
Name of the launch configuration.
image_id
AMI to use for instances. AMI must exist or creation of the launch
configuration will fail.
key_name
Name of the EC2 key pair to use for instances. Key must exist or
creation of the launch configuration will fail.
vpc_id
The VPC id where the security groups are defined. Only necessary when
using named security groups that exist outside of the default VPC.
Mutually exclusive with vpc_name.
vpc_name
Name of the VPC where the security groups are defined. Only Necessary
when using named security groups that exist outside of the default VPC.
Mutually exclusive with vpc_id.
security_groups
List of Names or security group id’s of the security groups with which
to associate the EC2 instances or VPC instances, respectively. Security
groups must exist, or creation of the launch configuration will fail.
user_data
The user data available to launched EC2 instances.
cloud_init
A dict of cloud_init configuration. Currently supported keys:
boothooks, scripts and cloud-config.
Mutually exclusive with user_data.
instance_type
The instance type. ex: m1.small.
kernel_id
The kernel id for the instance.
ramdisk_id
The RAM disk ID for the instance.
block_device_mappings
A dict of block device mappings that contains a dict
with volume_type, delete_on_termination, iops, size, encrypted,
snapshot_id.
volume_type
Indicates what volume type to use. Valid values are standard, io1, gp2.
Default is standard.
delete_on_termination
Whether the volume should be explicitly marked for deletion when its instance is
terminated (True), or left around (False). If not provided, or None is explicitly passed,
the default AWS behaviour is used, which is True for ROOT volumes of instances, and
False for all others.
iops
For Provisioned IOPS (SSD) volumes only. The number of I/O operations per
second (IOPS) to provision for the volume.
size
Desired volume size (in GiB).
encrypted
Indicates whether the volume should be encrypted. Encrypted EBS volumes must
be attached to instances that support Amazon EBS encryption. Volumes that are
created from encrypted snapshots are automatically encrypted. There is no way
to create an encrypted volume from an unencrypted snapshot or an unencrypted
volume from an encrypted snapshot.
instance_monitoring
Whether instances in group are launched with detailed monitoring.
spot_price
The spot price you are bidding. Only applies if you are building an
autoscaling group with spot instances.
instance_profile_name
The name or the Amazon Resource Name (ARN) of the instance profile
associated with the IAM role for the instance. Instance profile must
exist or the creation of the launch configuration will fail.
ebs_optimized
Specifies whether the instance is optimized for EBS I/O (true) or not
(false).
associate_public_ip_address
Used for Auto Scaling groups that launch instances into an Amazon
Virtual Private Cloud. Specifies whether to assign a public IP address
to each instance launched in a Amazon VPC.
region
The region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid. | [
"Ensure",
"the",
"launch",
"configuration",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_lc.py#L112-L293 | train |
saltstack/salt | salt/runners/spacewalk.py | _get_spacewalk_configuration | def _get_spacewalk_configuration(spacewalk_url=''):
'''
Return the configuration read from the master configuration
file or directory
'''
spacewalk_config = __opts__['spacewalk'] if 'spacewalk' in __opts__ else None
if spacewalk_config:
try:
for spacewalk_server, service_config in six.iteritems(spacewalk_config):
username = service_config.get('username', None)
password = service_config.get('password', None)
protocol = service_config.get('protocol', 'https')
if not username or not password:
log.error(
'Username or Password has not been specified in the master '
'configuration for %s', spacewalk_server
)
return False
ret = {
'api_url': '{0}://{1}/rpc/api'.format(protocol, spacewalk_server),
'username': username,
'password': password
}
if (not spacewalk_url) or (spacewalk_url == spacewalk_server):
return ret
except Exception as exc:
log.error('Exception encountered: %s', exc)
return False
if spacewalk_url:
log.error(
'Configuration for %s has not been specified in the master '
'configuration', spacewalk_url
)
return False
return False | python | def _get_spacewalk_configuration(spacewalk_url=''):
'''
Return the configuration read from the master configuration
file or directory
'''
spacewalk_config = __opts__['spacewalk'] if 'spacewalk' in __opts__ else None
if spacewalk_config:
try:
for spacewalk_server, service_config in six.iteritems(spacewalk_config):
username = service_config.get('username', None)
password = service_config.get('password', None)
protocol = service_config.get('protocol', 'https')
if not username or not password:
log.error(
'Username or Password has not been specified in the master '
'configuration for %s', spacewalk_server
)
return False
ret = {
'api_url': '{0}://{1}/rpc/api'.format(protocol, spacewalk_server),
'username': username,
'password': password
}
if (not spacewalk_url) or (spacewalk_url == spacewalk_server):
return ret
except Exception as exc:
log.error('Exception encountered: %s', exc)
return False
if spacewalk_url:
log.error(
'Configuration for %s has not been specified in the master '
'configuration', spacewalk_url
)
return False
return False | [
"def",
"_get_spacewalk_configuration",
"(",
"spacewalk_url",
"=",
"''",
")",
":",
"spacewalk_config",
"=",
"__opts__",
"[",
"'spacewalk'",
"]",
"if",
"'spacewalk'",
"in",
"__opts__",
"else",
"None",
"if",
"spacewalk_config",
":",
"try",
":",
"for",
"spacewalk_serv... | Return the configuration read from the master configuration
file or directory | [
"Return",
"the",
"configuration",
"read",
"from",
"the",
"master",
"configuration",
"file",
"or",
"directory"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/spacewalk.py#L56-L96 | train |
saltstack/salt | salt/runners/spacewalk.py | _get_client_and_key | def _get_client_and_key(url, user, password, verbose=0):
'''
Return the client object and session key for the client
'''
session = {}
session['client'] = six.moves.xmlrpc_client.Server(url, verbose=verbose, use_datetime=True)
session['key'] = session['client'].auth.login(user, password)
return session | python | def _get_client_and_key(url, user, password, verbose=0):
'''
Return the client object and session key for the client
'''
session = {}
session['client'] = six.moves.xmlrpc_client.Server(url, verbose=verbose, use_datetime=True)
session['key'] = session['client'].auth.login(user, password)
return session | [
"def",
"_get_client_and_key",
"(",
"url",
",",
"user",
",",
"password",
",",
"verbose",
"=",
"0",
")",
":",
"session",
"=",
"{",
"}",
"session",
"[",
"'client'",
"]",
"=",
"six",
".",
"moves",
".",
"xmlrpc_client",
".",
"Server",
"(",
"url",
",",
"ve... | Return the client object and session key for the client | [
"Return",
"the",
"client",
"object",
"and",
"session",
"key",
"for",
"the",
"client"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/spacewalk.py#L99-L107 | train |
saltstack/salt | salt/runners/spacewalk.py | _get_session | def _get_session(server):
'''
Get session and key
'''
if server in _sessions:
return _sessions[server]
config = _get_spacewalk_configuration(server)
if not config:
raise Exception('No config for \'{0}\' found on master'.format(server))
session = _get_client_and_key(config['api_url'], config['username'], config['password'])
atexit.register(_disconnect_session, session)
client = session['client']
key = session['key']
_sessions[server] = (client, key)
return client, key | python | def _get_session(server):
'''
Get session and key
'''
if server in _sessions:
return _sessions[server]
config = _get_spacewalk_configuration(server)
if not config:
raise Exception('No config for \'{0}\' found on master'.format(server))
session = _get_client_and_key(config['api_url'], config['username'], config['password'])
atexit.register(_disconnect_session, session)
client = session['client']
key = session['key']
_sessions[server] = (client, key)
return client, key | [
"def",
"_get_session",
"(",
"server",
")",
":",
"if",
"server",
"in",
"_sessions",
":",
"return",
"_sessions",
"[",
"server",
"]",
"config",
"=",
"_get_spacewalk_configuration",
"(",
"server",
")",
"if",
"not",
"config",
":",
"raise",
"Exception",
"(",
"'No ... | Get session and key | [
"Get",
"session",
"and",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/spacewalk.py#L117-L135 | train |
saltstack/salt | salt/runners/spacewalk.py | api | def api(server, command, *args, **kwargs):
'''
Call the Spacewalk xmlrpc api.
CLI Example:
.. code-block:: bash
salt-run spacewalk.api spacewalk01.domain.com systemgroup.create MyGroup Description
salt-run spacewalk.api spacewalk01.domain.com systemgroup.create arguments='["MyGroup", "Description"]'
State Example:
.. code-block:: yaml
create_group:
salt.runner:
- name: spacewalk.api
- server: spacewalk01.domain.com
- command: systemgroup.create
- arguments:
- MyGroup
- Description
'''
if 'arguments' in kwargs:
arguments = kwargs['arguments']
else:
arguments = args
call = '{0} {1}'.format(command, arguments)
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
log.error(err_msg)
return {call: err_msg}
namespace, method = command.split('.')
endpoint = getattr(getattr(client, namespace), method)
try:
output = endpoint(key, *arguments)
except Exception as e:
output = 'API call failed: {0}'.format(e)
return {call: output} | python | def api(server, command, *args, **kwargs):
'''
Call the Spacewalk xmlrpc api.
CLI Example:
.. code-block:: bash
salt-run spacewalk.api spacewalk01.domain.com systemgroup.create MyGroup Description
salt-run spacewalk.api spacewalk01.domain.com systemgroup.create arguments='["MyGroup", "Description"]'
State Example:
.. code-block:: yaml
create_group:
salt.runner:
- name: spacewalk.api
- server: spacewalk01.domain.com
- command: systemgroup.create
- arguments:
- MyGroup
- Description
'''
if 'arguments' in kwargs:
arguments = kwargs['arguments']
else:
arguments = args
call = '{0} {1}'.format(command, arguments)
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
log.error(err_msg)
return {call: err_msg}
namespace, method = command.split('.')
endpoint = getattr(getattr(client, namespace), method)
try:
output = endpoint(key, *arguments)
except Exception as e:
output = 'API call failed: {0}'.format(e)
return {call: output} | [
"def",
"api",
"(",
"server",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'arguments'",
"in",
"kwargs",
":",
"arguments",
"=",
"kwargs",
"[",
"'arguments'",
"]",
"else",
":",
"arguments",
"=",
"args",
"call",
"=",
"'{0}... | Call the Spacewalk xmlrpc api.
CLI Example:
.. code-block:: bash
salt-run spacewalk.api spacewalk01.domain.com systemgroup.create MyGroup Description
salt-run spacewalk.api spacewalk01.domain.com systemgroup.create arguments='["MyGroup", "Description"]'
State Example:
.. code-block:: yaml
create_group:
salt.runner:
- name: spacewalk.api
- server: spacewalk01.domain.com
- command: systemgroup.create
- arguments:
- MyGroup
- Description | [
"Call",
"the",
"Spacewalk",
"xmlrpc",
"api",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/spacewalk.py#L138-L183 | train |
saltstack/salt | salt/runners/spacewalk.py | addGroupsToKey | def addGroupsToKey(server, activation_key, groups):
'''
Add server groups to a activation key
CLI Example:
.. code-block:: bash
salt-run spacewalk.addGroupsToKey spacewalk01.domain.com 1-my-key '[group1, group2]'
'''
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
log.error(err_msg)
return {'Error': err_msg}
all_groups = client.systemgroup.listAllGroups(key)
groupIds = []
for group in all_groups:
if group['name'] in groups:
groupIds.append(group['id'])
if client.activationkey.addServerGroups(key, activation_key, groupIds) == 1:
return {activation_key: groups}
else:
return {activation_key: 'Failed to add groups to activation key'} | python | def addGroupsToKey(server, activation_key, groups):
'''
Add server groups to a activation key
CLI Example:
.. code-block:: bash
salt-run spacewalk.addGroupsToKey spacewalk01.domain.com 1-my-key '[group1, group2]'
'''
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
log.error(err_msg)
return {'Error': err_msg}
all_groups = client.systemgroup.listAllGroups(key)
groupIds = []
for group in all_groups:
if group['name'] in groups:
groupIds.append(group['id'])
if client.activationkey.addServerGroups(key, activation_key, groupIds) == 1:
return {activation_key: groups}
else:
return {activation_key: 'Failed to add groups to activation key'} | [
"def",
"addGroupsToKey",
"(",
"server",
",",
"activation_key",
",",
"groups",
")",
":",
"try",
":",
"client",
",",
"key",
"=",
"_get_session",
"(",
"server",
")",
"except",
"Exception",
"as",
"exc",
":",
"err_msg",
"=",
"'Exception raised when connecting to spac... | Add server groups to a activation key
CLI Example:
.. code-block:: bash
salt-run spacewalk.addGroupsToKey spacewalk01.domain.com 1-my-key '[group1, group2]' | [
"Add",
"server",
"groups",
"to",
"a",
"activation",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/spacewalk.py#L186-L213 | train |
saltstack/salt | salt/runners/spacewalk.py | deleteAllGroups | def deleteAllGroups(server):
'''
Delete all server groups from Spacewalk
'''
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
log.error(err_msg)
return {'Error': err_msg}
groups = client.systemgroup.listAllGroups(key)
deleted_groups = []
failed_groups = []
for group in groups:
if client.systemgroup.delete(key, group['name']) == 1:
deleted_groups.append(group['name'])
else:
failed_groups.append(group['name'])
ret = {'deleted': deleted_groups}
if failed_groups:
ret['failed'] = failed_groups
return ret | python | def deleteAllGroups(server):
'''
Delete all server groups from Spacewalk
'''
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
log.error(err_msg)
return {'Error': err_msg}
groups = client.systemgroup.listAllGroups(key)
deleted_groups = []
failed_groups = []
for group in groups:
if client.systemgroup.delete(key, group['name']) == 1:
deleted_groups.append(group['name'])
else:
failed_groups.append(group['name'])
ret = {'deleted': deleted_groups}
if failed_groups:
ret['failed'] = failed_groups
return ret | [
"def",
"deleteAllGroups",
"(",
"server",
")",
":",
"try",
":",
"client",
",",
"key",
"=",
"_get_session",
"(",
"server",
")",
"except",
"Exception",
"as",
"exc",
":",
"err_msg",
"=",
"'Exception raised when connecting to spacewalk server ({0}): {1}'",
".",
"format",... | Delete all server groups from Spacewalk | [
"Delete",
"all",
"server",
"groups",
"from",
"Spacewalk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/spacewalk.py#L216-L242 | train |
saltstack/salt | salt/runners/spacewalk.py | deleteAllSystems | def deleteAllSystems(server):
'''
Delete all systems from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.deleteAllSystems spacewalk01.domain.com
'''
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
log.error(err_msg)
return {'Error': err_msg}
systems = client.system.listSystems(key)
ids = []
names = []
for system in systems:
ids.append(system['id'])
names.append(system['name'])
if client.system.deleteSystems(key, ids) == 1:
return {'deleted': names}
else:
return {'Error': 'Failed to delete all systems'} | python | def deleteAllSystems(server):
'''
Delete all systems from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.deleteAllSystems spacewalk01.domain.com
'''
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
log.error(err_msg)
return {'Error': err_msg}
systems = client.system.listSystems(key)
ids = []
names = []
for system in systems:
ids.append(system['id'])
names.append(system['name'])
if client.system.deleteSystems(key, ids) == 1:
return {'deleted': names}
else:
return {'Error': 'Failed to delete all systems'} | [
"def",
"deleteAllSystems",
"(",
"server",
")",
":",
"try",
":",
"client",
",",
"key",
"=",
"_get_session",
"(",
"server",
")",
"except",
"Exception",
"as",
"exc",
":",
"err_msg",
"=",
"'Exception raised when connecting to spacewalk server ({0}): {1}'",
".",
"format"... | Delete all systems from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.deleteAllSystems spacewalk01.domain.com | [
"Delete",
"all",
"systems",
"from",
"Spacewalk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/spacewalk.py#L245-L274 | train |
saltstack/salt | salt/runners/spacewalk.py | deleteAllActivationKeys | def deleteAllActivationKeys(server):
'''
Delete all activation keys from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.deleteAllActivationKeys spacewalk01.domain.com
'''
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
log.error(err_msg)
return {'Error': err_msg}
activation_keys = client.activationkey.listActivationKeys(key)
deleted_keys = []
failed_keys = []
for aKey in activation_keys:
if client.activationkey.delete(key, aKey['key']) == 1:
deleted_keys.append(aKey['key'])
else:
failed_keys.append(aKey['key'])
ret = {'deleted': deleted_keys}
if failed_keys:
ret['failed'] = failed_keys
return ret | python | def deleteAllActivationKeys(server):
'''
Delete all activation keys from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.deleteAllActivationKeys spacewalk01.domain.com
'''
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
log.error(err_msg)
return {'Error': err_msg}
activation_keys = client.activationkey.listActivationKeys(key)
deleted_keys = []
failed_keys = []
for aKey in activation_keys:
if client.activationkey.delete(key, aKey['key']) == 1:
deleted_keys.append(aKey['key'])
else:
failed_keys.append(aKey['key'])
ret = {'deleted': deleted_keys}
if failed_keys:
ret['failed'] = failed_keys
return ret | [
"def",
"deleteAllActivationKeys",
"(",
"server",
")",
":",
"try",
":",
"client",
",",
"key",
"=",
"_get_session",
"(",
"server",
")",
"except",
"Exception",
"as",
"exc",
":",
"err_msg",
"=",
"'Exception raised when connecting to spacewalk server ({0}): {1}'",
".",
"... | Delete all activation keys from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.deleteAllActivationKeys spacewalk01.domain.com | [
"Delete",
"all",
"activation",
"keys",
"from",
"Spacewalk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/spacewalk.py#L277-L309 | train |
saltstack/salt | salt/runners/spacewalk.py | unregister | def unregister(name, server_url):
'''
Unregister specified server from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.unregister my-test-vm spacewalk01.domain.com
'''
try:
client, key = _get_session(server_url)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server_url, exc)
log.error(err_msg)
return {name: err_msg}
systems_list = client.system.getId(key, name)
if systems_list:
for system in systems_list:
out = client.system.deleteSystem(key, system['id'])
if out == 1:
return {name: 'Successfully unregistered from {0}'.format(server_url)}
else:
return {name: 'Failed to unregister from {0}'.format(server_url)}
else:
return {name: 'System does not exist in spacewalk server ({0})'.format(server_url)} | python | def unregister(name, server_url):
'''
Unregister specified server from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.unregister my-test-vm spacewalk01.domain.com
'''
try:
client, key = _get_session(server_url)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server_url, exc)
log.error(err_msg)
return {name: err_msg}
systems_list = client.system.getId(key, name)
if systems_list:
for system in systems_list:
out = client.system.deleteSystem(key, system['id'])
if out == 1:
return {name: 'Successfully unregistered from {0}'.format(server_url)}
else:
return {name: 'Failed to unregister from {0}'.format(server_url)}
else:
return {name: 'System does not exist in spacewalk server ({0})'.format(server_url)} | [
"def",
"unregister",
"(",
"name",
",",
"server_url",
")",
":",
"try",
":",
"client",
",",
"key",
"=",
"_get_session",
"(",
"server_url",
")",
"except",
"Exception",
"as",
"exc",
":",
"err_msg",
"=",
"'Exception raised when connecting to spacewalk server ({0}): {1}'"... | Unregister specified server from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.unregister my-test-vm spacewalk01.domain.com | [
"Unregister",
"specified",
"server",
"from",
"Spacewalk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/spacewalk.py#L312-L340 | train |
saltstack/salt | salt/states/boto3_elasticache.py | _diff_cache_cluster | def _diff_cache_cluster(current, desired):
'''
If you need to enhance what modify_cache_cluster() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_cache_cluster() to that in describe_cache_clusters(). Any data fiddlery that
needs to be done to make the mappings meaningful should be done in the munging section
below as well.
This function will ONLY touch settings that are explicitly called out in 'desired' - any
settings which might have previously been changed from their 'default' values will not be
changed back simply by leaving them out of 'desired'. This is both intentional, and
much, much easier to code :)
'''
### The data formats are annoyingly (and as far as I can can tell, unnecessarily)
### different - we have to munge to a common format to compare...
if current.get('SecurityGroups') is not None:
current['SecurityGroupIds'] = [s['SecurityGroupId'] for s in current['SecurityGroups']]
if current.get('CacheSecurityGroups') is not None:
current['CacheSecurityGroupNames'] = [c['CacheSecurityGroupName'] for c in current['CacheSecurityGroups']]
if current.get('NotificationConfiguration') is not None:
current['NotificationTopicArn'] = current['NotificationConfiguration']['TopicArn']
current['NotificationTopicStatus'] = current['NotificationConfiguration']['TopicStatus']
if current.get('CacheParameterGroup') is not None:
current['CacheParameterGroupName'] = current['CacheParameterGroup']['CacheParameterGroupName']
modifiable = {
'AutoMinorVersionUpgrade': 'AutoMinorVersionUpgrade',
'AZMode': 'AZMode',
'CacheNodeType': 'CacheNodeType',
'CacheNodeIdsToRemove': None,
'CacheParameterGroupName': 'CacheParameterGroupName',
'CacheSecurityGroupNames': 'CacheSecurityGroupNames',
'EngineVersion': 'EngineVersion',
'NewAvailabilityZones': None,
'NotificationTopicArn': 'NotificationTopicArn',
'NotificationTopicStatus': 'NotificationTopicStatus',
'NumCacheNodes': 'NumCacheNodes',
'PreferredMaintenanceWindow': 'PreferredMaintenanceWindow',
'SecurityGroupIds': 'SecurityGroupIds',
'SnapshotRetentionLimit': 'SnapshotRetentionLimit',
'SnapshotWindow': 'SnapshotWindow'
}
need_update = {}
for m, o in modifiable.items():
if m in desired:
if not o:
# Always pass these through - let AWS do the math...
need_update[m] = desired[m]
else:
if m in current:
# Equivalence testing works fine for current simple type comparisons
# This might need enhancement if more complex structures enter the picture
if current[m] != desired[m]:
need_update[m] = desired[m]
return need_update | python | def _diff_cache_cluster(current, desired):
'''
If you need to enhance what modify_cache_cluster() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_cache_cluster() to that in describe_cache_clusters(). Any data fiddlery that
needs to be done to make the mappings meaningful should be done in the munging section
below as well.
This function will ONLY touch settings that are explicitly called out in 'desired' - any
settings which might have previously been changed from their 'default' values will not be
changed back simply by leaving them out of 'desired'. This is both intentional, and
much, much easier to code :)
'''
### The data formats are annoyingly (and as far as I can can tell, unnecessarily)
### different - we have to munge to a common format to compare...
if current.get('SecurityGroups') is not None:
current['SecurityGroupIds'] = [s['SecurityGroupId'] for s in current['SecurityGroups']]
if current.get('CacheSecurityGroups') is not None:
current['CacheSecurityGroupNames'] = [c['CacheSecurityGroupName'] for c in current['CacheSecurityGroups']]
if current.get('NotificationConfiguration') is not None:
current['NotificationTopicArn'] = current['NotificationConfiguration']['TopicArn']
current['NotificationTopicStatus'] = current['NotificationConfiguration']['TopicStatus']
if current.get('CacheParameterGroup') is not None:
current['CacheParameterGroupName'] = current['CacheParameterGroup']['CacheParameterGroupName']
modifiable = {
'AutoMinorVersionUpgrade': 'AutoMinorVersionUpgrade',
'AZMode': 'AZMode',
'CacheNodeType': 'CacheNodeType',
'CacheNodeIdsToRemove': None,
'CacheParameterGroupName': 'CacheParameterGroupName',
'CacheSecurityGroupNames': 'CacheSecurityGroupNames',
'EngineVersion': 'EngineVersion',
'NewAvailabilityZones': None,
'NotificationTopicArn': 'NotificationTopicArn',
'NotificationTopicStatus': 'NotificationTopicStatus',
'NumCacheNodes': 'NumCacheNodes',
'PreferredMaintenanceWindow': 'PreferredMaintenanceWindow',
'SecurityGroupIds': 'SecurityGroupIds',
'SnapshotRetentionLimit': 'SnapshotRetentionLimit',
'SnapshotWindow': 'SnapshotWindow'
}
need_update = {}
for m, o in modifiable.items():
if m in desired:
if not o:
# Always pass these through - let AWS do the math...
need_update[m] = desired[m]
else:
if m in current:
# Equivalence testing works fine for current simple type comparisons
# This might need enhancement if more complex structures enter the picture
if current[m] != desired[m]:
need_update[m] = desired[m]
return need_update | [
"def",
"_diff_cache_cluster",
"(",
"current",
",",
"desired",
")",
":",
"### The data formats are annoyingly (and as far as I can can tell, unnecessarily)",
"### different - we have to munge to a common format to compare...",
"if",
"current",
".",
"get",
"(",
"'SecurityGroups'",
")",... | If you need to enhance what modify_cache_cluster() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_cache_cluster() to that in describe_cache_clusters(). Any data fiddlery that
needs to be done to make the mappings meaningful should be done in the munging section
below as well.
This function will ONLY touch settings that are explicitly called out in 'desired' - any
settings which might have previously been changed from their 'default' values will not be
changed back simply by leaving them out of 'desired'. This is both intentional, and
much, much easier to code :) | [
"If",
"you",
"need",
"to",
"enhance",
"what",
"modify_cache_cluster",
"()",
"considers",
"when",
"deciding",
"what",
"is",
"to",
"be",
"(",
"or",
"can",
"be",
")",
"updated",
"add",
"it",
"to",
"modifiable",
"below",
".",
"It",
"s",
"a",
"dict",
"mapping... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto3_elasticache.py#L106-L161 | train |
saltstack/salt | salt/states/boto3_elasticache.py | cache_cluster_present | def cache_cluster_present(name, wait=900, security_groups=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Ensure a given cache cluster exists.
name
Name of the cache cluster (cache cluster id).
wait
Integer describing how long, in seconds, to wait for confirmation from AWS that the
resource is in the desired state. Zero meaning to return success or failure immediately
of course. Note that waiting for the cluster to become available is generally the
better course, as failure to do so will often lead to subsequent failures when managing
dependent resources.
security_groups
One or more VPC security groups (names and/or IDs) associated with the cache cluster.
.. note::
This is additive with any sec groups provided via the
SecurityGroupIds parameter below. Use this parameter ONLY when you
are creating a cluster in a VPC.
CacheClusterId
The node group (shard) identifier. This parameter is stored as a lowercase string.
Constraints:
- A name must contain from 1 to 20 alphanumeric characters or hyphens.
- The first character must be a letter.
- A name cannot end with a hyphen or contain two consecutive hyphens.
.. note::
In general this parameter is not needed, as 'name' is used if it's
not provided.
ReplicationGroupId
The ID of the replication group to which this cache cluster should belong. If this
parameter is specified, the cache cluster is added to the specified replication
group as a read replica; otherwise, the cache cluster is a standalone primary that
is not part of any replication group. If the specified replication group is
Multi-AZ enabled and the Availability Zone is not specified, the cache cluster is
created in Availability Zones that provide the best spread of read replicas across
Availability Zones.
.. note:
This parameter is ONLY valid if the Engine parameter is redis. Due
to current limitations on Redis (cluster mode disabled), this
parameter is not supported on Redis (cluster mode enabled)
replication groups.
AZMode
Specifies whether the nodes in this Memcached cluster are created in a single
Availability Zone or created across multiple Availability Zones in the cluster's
region. If the AZMode and PreferredAvailabilityZones are not specified,
ElastiCache assumes single-az mode.
.. note::
This parameter is ONLY supported for Memcached cache clusters.
PreferredAvailabilityZone
The EC2 Availability Zone in which the cache cluster is created. All nodes
belonging to this Memcached cache cluster are placed in the preferred Availability
Zone. If you want to create your nodes across multiple Availability Zones, use
PreferredAvailabilityZones.
Default: System chosen Availability Zone.
PreferredAvailabilityZones
A list of the Availability Zones in which cache nodes are created. The order of
the zones in the list is not important. The number of Availability Zones listed
must equal the value of NumCacheNodes. If you want all the nodes in the same
Availability Zone, use PreferredAvailabilityZone instead, or repeat the
Availability Zone multiple times in the list.
Default: System chosen Availability Zones.
.. note::
This option is ONLY supported on Memcached.
If you are creating your cache cluster in an Amazon VPC
(recommended) you can only locate nodes in Availability Zones that
are associated with the subnets in the selected subnet group.
NumCacheNodes
The initial (integer) number of cache nodes that the cache cluster has.
.. note::
For clusters running Redis, this value must be 1.
For clusters running Memcached, this value must be between 1 and 20.
CacheNodeType
The compute and memory capacity of the nodes in the node group (shard).
Valid node types (and pricing for them) are exhaustively described at
https://aws.amazon.com/elasticache/pricing/
.. note::
All T2 instances must be created in a VPC
Redis backup/restore is not supported for Redis (cluster mode
disabled) T1 and T2 instances. Backup/restore is supported on Redis
(cluster mode enabled) T2 instances.
Redis Append-only files (AOF) functionality is not supported for T1
or T2 instances.
Engine
The name of the cache engine to be used for this cache cluster. Valid values for
this parameter are: memcached | redis
EngineVersion
The version number of the cache engine to be used for this cache cluster. To view
the supported cache engine versions, use the DescribeCacheEngineVersions operation.
.. note::
You can upgrade to a newer engine version but you cannot downgrade
to an earlier engine version. If you want to use an earlier engine
version, you must delete the existing cache cluster or replication
group and create it anew with the earlier engine version.
CacheParameterGroupName
The name of the parameter group to associate with this cache cluster. If this
argument is omitted, the default parameter group for the specified engine is used.
You cannot use any parameter group which has cluster-enabled='yes' when creating
a cluster.
CacheSubnetGroupName
The name of the Cache Subnet Group to be used for the cache cluster. Use this
parameter ONLY when you are creating a cache cluster within a VPC.
.. note::
If you're going to launch your cluster in an Amazon VPC, you need
to create a subnet group before you start creating a cluster.
CacheSecurityGroupNames
A list of Cache Security Group names to associate with this cache cluster. Use
this parameter ONLY when you are creating a cache cluster outside of a VPC.
SecurityGroupIds
One or more VPC security groups associated with the cache cluster. Use this
parameter ONLY when you are creating a cache cluster within a VPC.
Tags
A list of tags to be added to this resource. Note that due to shortcomings in the
AWS API for Elasticache, these can only be set during resource creation - later
modification is not (currently) supported.
SnapshotArns
A single-element string list containing an Amazon Resource Name (ARN) that
uniquely identifies a Redis RDB snapshot file stored in Amazon S3. The snapshot
file is used to populate the node group (shard). The Amazon S3 object name in
the ARN cannot contain any commas.
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
SnapshotName
The name of a Redis snapshot from which to restore data into the new node group
(shard). The snapshot status changes to restoring while the new node group (shard)
is being created.
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
PreferredMaintenanceWindow
Specifies the weekly time range during which maintenance on the cache cluster is
permitted. It is specified as a range in the format ddd:hh24:mi-ddd:hh24:mi
(24H Clock UTC). The minimum maintenance window is a 60 minute period.
Valid values for ddd are: sun, mon, tue, wed, thu, fri, sat
Example: sun:23:00-mon:01:30
Port
The port number on which each of the cache nodes accepts connections.
Default: 6379
NotificationTopicArn
The Amazon Resource Name (ARN) of the Amazon Simple Notification Service (SNS)
topic to which notifications are sent.
.. note::
The Amazon SNS topic owner must be the same as the cache cluster
owner.
AutoMinorVersionUpgrade
This (boolean) parameter is currently disabled.
SnapshotRetentionLimit
The number of days for which ElastiCache retains automatic snapshots before
deleting them.
Default: 0 (i.e., automatic backups are disabled for this cache cluster).
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
SnapshotWindow
The daily time range (in UTC) during which ElastiCache begins taking a daily
snapshot of your node group (shard). If you do not specify this parameter,
ElastiCache automatically chooses an appropriate time range.
Example: 05:00-09:00
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
AuthToken
The password used to access a password protected server.
Password constraints:
- Must be only printable ASCII characters.
- Must be at least 16 characters and no more than 128 characters in length.
- Cannot contain any of the following characters: '/', '"', or "@".
CacheNodeIdsToRemove
A list of cache node IDs to be removed. A node ID is a numeric identifier (0001, 0002,
etc.). This parameter is only valid when NumCacheNodes is less than the existing number of
cache nodes. The number of cache node IDs supplied in this parameter must match the
difference between the existing number of cache nodes in the cluster or pending cache nodes,
whichever is greater, and the value of NumCacheNodes in the request.
NewAvailabilityZones
The list of Availability Zones where the new Memcached cache nodes are created.
This parameter is only valid when NumCacheNodes in the request is greater than the sum of
the number of active cache nodes and the number of cache nodes pending creation (which may
be zero). The number of Availability Zones supplied in this list must match the cache nodes
being added in this request.
Note: This option is only supported on Memcached clusters.
NotificationTopicStatus
The status of the SNS notification topic. Notifications are sent only if the status is active.
Valid values: active | inactive
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
current = __salt__['boto3_elasticache.'
'describe_cache_clusters'](name, region=region, key=key,
keyid=keyid, profile=profile)
if current:
check_update = True
else:
check_update = False
only_on_modify = [
'CacheNodeIdsToRemove',
'NewAvailabilityZones',
'NotificationTopicStatus'
]
create_args = {}
for k, v in args.items():
if k in only_on_modify:
check_update = True
else:
create_args[k] = v
if __opts__['test']:
ret['comment'] = 'Cache cluster {0} would be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto3_elasticache.'
'create_cache_cluster'](name, wait=wait, security_groups=security_groups,
region=region, key=key, keyid=keyid,
profile=profile, **create_args)
if created:
new = __salt__['boto3_elasticache.'
'describe_cache_clusters'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['comment'] = 'Cache cluster {0} was created.'.format(name)
ret['changes']['old'] = None
ret['changes']['new'] = new[0]
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} cache cluster.'.format(name)
if check_update:
# Refresh this in case we're updating from 'only_on_modify' above...
updated = __salt__['boto3_elasticache.'
'describe_cache_clusters'](name, region=region, key=key,
keyid=keyid, profile=profile)
need_update = _diff_cache_cluster(updated['CacheClusters'][0], args)
if need_update:
if __opts__['test']:
ret['comment'] = 'Cache cluster {0} would be modified.'.format(name)
ret['result'] = None
return ret
modified = __salt__['boto3_elasticache.'
'modify_cache_cluster'](name, wait=wait,
security_groups=security_groups,
region=region, key=key, keyid=keyid,
profile=profile, **need_update)
if modified:
new = __salt__['boto3_elasticache.'
'describe_cache_clusters'](name, region=region, key=key,
keyid=keyid, profile=profile)
if ret['comment']: # 'create' just ran...
ret['comment'] += ' ... and then immediately modified.'
else:
ret['comment'] = 'Cache cluster {0} was modified.'.format(name)
ret['changes']['old'] = current
ret['changes']['new'] = new[0]
else:
ret['result'] = False
ret['comment'] = 'Failed to modify cache cluster {0}.'.format(name)
else:
ret['comment'] = 'Cache cluster {0} is in the desired state.'.format(name)
return ret | python | def cache_cluster_present(name, wait=900, security_groups=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Ensure a given cache cluster exists.
name
Name of the cache cluster (cache cluster id).
wait
Integer describing how long, in seconds, to wait for confirmation from AWS that the
resource is in the desired state. Zero meaning to return success or failure immediately
of course. Note that waiting for the cluster to become available is generally the
better course, as failure to do so will often lead to subsequent failures when managing
dependent resources.
security_groups
One or more VPC security groups (names and/or IDs) associated with the cache cluster.
.. note::
This is additive with any sec groups provided via the
SecurityGroupIds parameter below. Use this parameter ONLY when you
are creating a cluster in a VPC.
CacheClusterId
The node group (shard) identifier. This parameter is stored as a lowercase string.
Constraints:
- A name must contain from 1 to 20 alphanumeric characters or hyphens.
- The first character must be a letter.
- A name cannot end with a hyphen or contain two consecutive hyphens.
.. note::
In general this parameter is not needed, as 'name' is used if it's
not provided.
ReplicationGroupId
The ID of the replication group to which this cache cluster should belong. If this
parameter is specified, the cache cluster is added to the specified replication
group as a read replica; otherwise, the cache cluster is a standalone primary that
is not part of any replication group. If the specified replication group is
Multi-AZ enabled and the Availability Zone is not specified, the cache cluster is
created in Availability Zones that provide the best spread of read replicas across
Availability Zones.
.. note:
This parameter is ONLY valid if the Engine parameter is redis. Due
to current limitations on Redis (cluster mode disabled), this
parameter is not supported on Redis (cluster mode enabled)
replication groups.
AZMode
Specifies whether the nodes in this Memcached cluster are created in a single
Availability Zone or created across multiple Availability Zones in the cluster's
region. If the AZMode and PreferredAvailabilityZones are not specified,
ElastiCache assumes single-az mode.
.. note::
This parameter is ONLY supported for Memcached cache clusters.
PreferredAvailabilityZone
The EC2 Availability Zone in which the cache cluster is created. All nodes
belonging to this Memcached cache cluster are placed in the preferred Availability
Zone. If you want to create your nodes across multiple Availability Zones, use
PreferredAvailabilityZones.
Default: System chosen Availability Zone.
PreferredAvailabilityZones
A list of the Availability Zones in which cache nodes are created. The order of
the zones in the list is not important. The number of Availability Zones listed
must equal the value of NumCacheNodes. If you want all the nodes in the same
Availability Zone, use PreferredAvailabilityZone instead, or repeat the
Availability Zone multiple times in the list.
Default: System chosen Availability Zones.
.. note::
This option is ONLY supported on Memcached.
If you are creating your cache cluster in an Amazon VPC
(recommended) you can only locate nodes in Availability Zones that
are associated with the subnets in the selected subnet group.
NumCacheNodes
The initial (integer) number of cache nodes that the cache cluster has.
.. note::
For clusters running Redis, this value must be 1.
For clusters running Memcached, this value must be between 1 and 20.
CacheNodeType
The compute and memory capacity of the nodes in the node group (shard).
Valid node types (and pricing for them) are exhaustively described at
https://aws.amazon.com/elasticache/pricing/
.. note::
All T2 instances must be created in a VPC
Redis backup/restore is not supported for Redis (cluster mode
disabled) T1 and T2 instances. Backup/restore is supported on Redis
(cluster mode enabled) T2 instances.
Redis Append-only files (AOF) functionality is not supported for T1
or T2 instances.
Engine
The name of the cache engine to be used for this cache cluster. Valid values for
this parameter are: memcached | redis
EngineVersion
The version number of the cache engine to be used for this cache cluster. To view
the supported cache engine versions, use the DescribeCacheEngineVersions operation.
.. note::
You can upgrade to a newer engine version but you cannot downgrade
to an earlier engine version. If you want to use an earlier engine
version, you must delete the existing cache cluster or replication
group and create it anew with the earlier engine version.
CacheParameterGroupName
The name of the parameter group to associate with this cache cluster. If this
argument is omitted, the default parameter group for the specified engine is used.
You cannot use any parameter group which has cluster-enabled='yes' when creating
a cluster.
CacheSubnetGroupName
The name of the Cache Subnet Group to be used for the cache cluster. Use this
parameter ONLY when you are creating a cache cluster within a VPC.
.. note::
If you're going to launch your cluster in an Amazon VPC, you need
to create a subnet group before you start creating a cluster.
CacheSecurityGroupNames
A list of Cache Security Group names to associate with this cache cluster. Use
this parameter ONLY when you are creating a cache cluster outside of a VPC.
SecurityGroupIds
One or more VPC security groups associated with the cache cluster. Use this
parameter ONLY when you are creating a cache cluster within a VPC.
Tags
A list of tags to be added to this resource. Note that due to shortcomings in the
AWS API for Elasticache, these can only be set during resource creation - later
modification is not (currently) supported.
SnapshotArns
A single-element string list containing an Amazon Resource Name (ARN) that
uniquely identifies a Redis RDB snapshot file stored in Amazon S3. The snapshot
file is used to populate the node group (shard). The Amazon S3 object name in
the ARN cannot contain any commas.
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
SnapshotName
The name of a Redis snapshot from which to restore data into the new node group
(shard). The snapshot status changes to restoring while the new node group (shard)
is being created.
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
PreferredMaintenanceWindow
Specifies the weekly time range during which maintenance on the cache cluster is
permitted. It is specified as a range in the format ddd:hh24:mi-ddd:hh24:mi
(24H Clock UTC). The minimum maintenance window is a 60 minute period.
Valid values for ddd are: sun, mon, tue, wed, thu, fri, sat
Example: sun:23:00-mon:01:30
Port
The port number on which each of the cache nodes accepts connections.
Default: 6379
NotificationTopicArn
The Amazon Resource Name (ARN) of the Amazon Simple Notification Service (SNS)
topic to which notifications are sent.
.. note::
The Amazon SNS topic owner must be the same as the cache cluster
owner.
AutoMinorVersionUpgrade
This (boolean) parameter is currently disabled.
SnapshotRetentionLimit
The number of days for which ElastiCache retains automatic snapshots before
deleting them.
Default: 0 (i.e., automatic backups are disabled for this cache cluster).
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
SnapshotWindow
The daily time range (in UTC) during which ElastiCache begins taking a daily
snapshot of your node group (shard). If you do not specify this parameter,
ElastiCache automatically chooses an appropriate time range.
Example: 05:00-09:00
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
AuthToken
The password used to access a password protected server.
Password constraints:
- Must be only printable ASCII characters.
- Must be at least 16 characters and no more than 128 characters in length.
- Cannot contain any of the following characters: '/', '"', or "@".
CacheNodeIdsToRemove
A list of cache node IDs to be removed. A node ID is a numeric identifier (0001, 0002,
etc.). This parameter is only valid when NumCacheNodes is less than the existing number of
cache nodes. The number of cache node IDs supplied in this parameter must match the
difference between the existing number of cache nodes in the cluster or pending cache nodes,
whichever is greater, and the value of NumCacheNodes in the request.
NewAvailabilityZones
The list of Availability Zones where the new Memcached cache nodes are created.
This parameter is only valid when NumCacheNodes in the request is greater than the sum of
the number of active cache nodes and the number of cache nodes pending creation (which may
be zero). The number of Availability Zones supplied in this list must match the cache nodes
being added in this request.
Note: This option is only supported on Memcached clusters.
NotificationTopicStatus
The status of the SNS notification topic. Notifications are sent only if the status is active.
Valid values: active | inactive
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
current = __salt__['boto3_elasticache.'
'describe_cache_clusters'](name, region=region, key=key,
keyid=keyid, profile=profile)
if current:
check_update = True
else:
check_update = False
only_on_modify = [
'CacheNodeIdsToRemove',
'NewAvailabilityZones',
'NotificationTopicStatus'
]
create_args = {}
for k, v in args.items():
if k in only_on_modify:
check_update = True
else:
create_args[k] = v
if __opts__['test']:
ret['comment'] = 'Cache cluster {0} would be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto3_elasticache.'
'create_cache_cluster'](name, wait=wait, security_groups=security_groups,
region=region, key=key, keyid=keyid,
profile=profile, **create_args)
if created:
new = __salt__['boto3_elasticache.'
'describe_cache_clusters'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['comment'] = 'Cache cluster {0} was created.'.format(name)
ret['changes']['old'] = None
ret['changes']['new'] = new[0]
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} cache cluster.'.format(name)
if check_update:
# Refresh this in case we're updating from 'only_on_modify' above...
updated = __salt__['boto3_elasticache.'
'describe_cache_clusters'](name, region=region, key=key,
keyid=keyid, profile=profile)
need_update = _diff_cache_cluster(updated['CacheClusters'][0], args)
if need_update:
if __opts__['test']:
ret['comment'] = 'Cache cluster {0} would be modified.'.format(name)
ret['result'] = None
return ret
modified = __salt__['boto3_elasticache.'
'modify_cache_cluster'](name, wait=wait,
security_groups=security_groups,
region=region, key=key, keyid=keyid,
profile=profile, **need_update)
if modified:
new = __salt__['boto3_elasticache.'
'describe_cache_clusters'](name, region=region, key=key,
keyid=keyid, profile=profile)
if ret['comment']: # 'create' just ran...
ret['comment'] += ' ... and then immediately modified.'
else:
ret['comment'] = 'Cache cluster {0} was modified.'.format(name)
ret['changes']['old'] = current
ret['changes']['new'] = new[0]
else:
ret['result'] = False
ret['comment'] = 'Failed to modify cache cluster {0}.'.format(name)
else:
ret['comment'] = 'Cache cluster {0} is in the desired state.'.format(name)
return ret | [
"def",
"cache_cluster_present",
"(",
"name",
",",
"wait",
"=",
"900",
",",
"security_groups",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
... | Ensure a given cache cluster exists.
name
Name of the cache cluster (cache cluster id).
wait
Integer describing how long, in seconds, to wait for confirmation from AWS that the
resource is in the desired state. Zero meaning to return success or failure immediately
of course. Note that waiting for the cluster to become available is generally the
better course, as failure to do so will often lead to subsequent failures when managing
dependent resources.
security_groups
One or more VPC security groups (names and/or IDs) associated with the cache cluster.
.. note::
This is additive with any sec groups provided via the
SecurityGroupIds parameter below. Use this parameter ONLY when you
are creating a cluster in a VPC.
CacheClusterId
The node group (shard) identifier. This parameter is stored as a lowercase string.
Constraints:
- A name must contain from 1 to 20 alphanumeric characters or hyphens.
- The first character must be a letter.
- A name cannot end with a hyphen or contain two consecutive hyphens.
.. note::
In general this parameter is not needed, as 'name' is used if it's
not provided.
ReplicationGroupId
The ID of the replication group to which this cache cluster should belong. If this
parameter is specified, the cache cluster is added to the specified replication
group as a read replica; otherwise, the cache cluster is a standalone primary that
is not part of any replication group. If the specified replication group is
Multi-AZ enabled and the Availability Zone is not specified, the cache cluster is
created in Availability Zones that provide the best spread of read replicas across
Availability Zones.
.. note:
This parameter is ONLY valid if the Engine parameter is redis. Due
to current limitations on Redis (cluster mode disabled), this
parameter is not supported on Redis (cluster mode enabled)
replication groups.
AZMode
Specifies whether the nodes in this Memcached cluster are created in a single
Availability Zone or created across multiple Availability Zones in the cluster's
region. If the AZMode and PreferredAvailabilityZones are not specified,
ElastiCache assumes single-az mode.
.. note::
This parameter is ONLY supported for Memcached cache clusters.
PreferredAvailabilityZone
The EC2 Availability Zone in which the cache cluster is created. All nodes
belonging to this Memcached cache cluster are placed in the preferred Availability
Zone. If you want to create your nodes across multiple Availability Zones, use
PreferredAvailabilityZones.
Default: System chosen Availability Zone.
PreferredAvailabilityZones
A list of the Availability Zones in which cache nodes are created. The order of
the zones in the list is not important. The number of Availability Zones listed
must equal the value of NumCacheNodes. If you want all the nodes in the same
Availability Zone, use PreferredAvailabilityZone instead, or repeat the
Availability Zone multiple times in the list.
Default: System chosen Availability Zones.
.. note::
This option is ONLY supported on Memcached.
If you are creating your cache cluster in an Amazon VPC
(recommended) you can only locate nodes in Availability Zones that
are associated with the subnets in the selected subnet group.
NumCacheNodes
The initial (integer) number of cache nodes that the cache cluster has.
.. note::
For clusters running Redis, this value must be 1.
For clusters running Memcached, this value must be between 1 and 20.
CacheNodeType
The compute and memory capacity of the nodes in the node group (shard).
Valid node types (and pricing for them) are exhaustively described at
https://aws.amazon.com/elasticache/pricing/
.. note::
All T2 instances must be created in a VPC
Redis backup/restore is not supported for Redis (cluster mode
disabled) T1 and T2 instances. Backup/restore is supported on Redis
(cluster mode enabled) T2 instances.
Redis Append-only files (AOF) functionality is not supported for T1
or T2 instances.
Engine
The name of the cache engine to be used for this cache cluster. Valid values for
this parameter are: memcached | redis
EngineVersion
The version number of the cache engine to be used for this cache cluster. To view
the supported cache engine versions, use the DescribeCacheEngineVersions operation.
.. note::
You can upgrade to a newer engine version but you cannot downgrade
to an earlier engine version. If you want to use an earlier engine
version, you must delete the existing cache cluster or replication
group and create it anew with the earlier engine version.
CacheParameterGroupName
The name of the parameter group to associate with this cache cluster. If this
argument is omitted, the default parameter group for the specified engine is used.
You cannot use any parameter group which has cluster-enabled='yes' when creating
a cluster.
CacheSubnetGroupName
The name of the Cache Subnet Group to be used for the cache cluster. Use this
parameter ONLY when you are creating a cache cluster within a VPC.
.. note::
If you're going to launch your cluster in an Amazon VPC, you need
to create a subnet group before you start creating a cluster.
CacheSecurityGroupNames
A list of Cache Security Group names to associate with this cache cluster. Use
this parameter ONLY when you are creating a cache cluster outside of a VPC.
SecurityGroupIds
One or more VPC security groups associated with the cache cluster. Use this
parameter ONLY when you are creating a cache cluster within a VPC.
Tags
A list of tags to be added to this resource. Note that due to shortcomings in the
AWS API for Elasticache, these can only be set during resource creation - later
modification is not (currently) supported.
SnapshotArns
A single-element string list containing an Amazon Resource Name (ARN) that
uniquely identifies a Redis RDB snapshot file stored in Amazon S3. The snapshot
file is used to populate the node group (shard). The Amazon S3 object name in
the ARN cannot contain any commas.
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
SnapshotName
The name of a Redis snapshot from which to restore data into the new node group
(shard). The snapshot status changes to restoring while the new node group (shard)
is being created.
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
PreferredMaintenanceWindow
Specifies the weekly time range during which maintenance on the cache cluster is
permitted. It is specified as a range in the format ddd:hh24:mi-ddd:hh24:mi
(24H Clock UTC). The minimum maintenance window is a 60 minute period.
Valid values for ddd are: sun, mon, tue, wed, thu, fri, sat
Example: sun:23:00-mon:01:30
Port
The port number on which each of the cache nodes accepts connections.
Default: 6379
NotificationTopicArn
The Amazon Resource Name (ARN) of the Amazon Simple Notification Service (SNS)
topic to which notifications are sent.
.. note::
The Amazon SNS topic owner must be the same as the cache cluster
owner.
AutoMinorVersionUpgrade
This (boolean) parameter is currently disabled.
SnapshotRetentionLimit
The number of days for which ElastiCache retains automatic snapshots before
deleting them.
Default: 0 (i.e., automatic backups are disabled for this cache cluster).
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
SnapshotWindow
The daily time range (in UTC) during which ElastiCache begins taking a daily
snapshot of your node group (shard). If you do not specify this parameter,
ElastiCache automatically chooses an appropriate time range.
Example: 05:00-09:00
.. note::
This parameter is ONLY valid if the Engine parameter is redis.
AuthToken
The password used to access a password protected server.
Password constraints:
- Must be only printable ASCII characters.
- Must be at least 16 characters and no more than 128 characters in length.
- Cannot contain any of the following characters: '/', '"', or "@".
CacheNodeIdsToRemove
A list of cache node IDs to be removed. A node ID is a numeric identifier (0001, 0002,
etc.). This parameter is only valid when NumCacheNodes is less than the existing number of
cache nodes. The number of cache node IDs supplied in this parameter must match the
difference between the existing number of cache nodes in the cluster or pending cache nodes,
whichever is greater, and the value of NumCacheNodes in the request.
NewAvailabilityZones
The list of Availability Zones where the new Memcached cache nodes are created.
This parameter is only valid when NumCacheNodes in the request is greater than the sum of
the number of active cache nodes and the number of cache nodes pending creation (which may
be zero). The number of Availability Zones supplied in this list must match the cache nodes
being added in this request.
Note: This option is only supported on Memcached clusters.
NotificationTopicStatus
The status of the SNS notification topic. Notifications are sent only if the status is active.
Valid values: active | inactive
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"a",
"given",
"cache",
"cluster",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto3_elasticache.py#L164-L484 | train |
saltstack/salt | salt/states/boto3_elasticache.py | _diff_replication_group | def _diff_replication_group(current, desired):
'''
If you need to enhance what modify_replication_group() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_replication_group() to that in describe_replication_groups(). Any data fiddlery
that needs to be done to make the mappings meaningful should be done in the munging section
below as well.
This function will ONLY touch settings that are explicitly called out in 'desired' - any
settings which might have previously been changed from their 'default' values will not be
changed back simply by leaving them out of 'desired'. This is both intentional, and
much, much easier to code :)
'''
if current.get('AutomaticFailover') is not None:
current['AutomaticFailoverEnabled'] = True if current['AutomaticFailover'] in ('enabled',
'enabling') else False
modifiable = {
# Amazingly, the AWS API provides NO WAY to query the current state of most repl group
# settings! All we can do is send a modify op with the desired value, just in case it's
# different. And THEN, we can't determine if it's been changed! Stupid? YOU BET!
'AutomaticFailoverEnabled': 'AutomaticFailoverEnabled',
'AutoMinorVersionUpgrade': None,
'CacheNodeType': None,
'CacheParameterGroupName': None,
'CacheSecurityGroupNames': None,
'EngineVersion': None,
'NotificationTopicArn': None,
'NotificationTopicStatus': None,
'PreferredMaintenanceWindow': None,
'PrimaryClusterId': None,
'ReplicationGroupDescription': 'Description',
'SecurityGroupIds': None,
'SnapshotRetentionLimit': 'SnapshotRetentionLimit',
'SnapshottingClusterId': 'SnapshottingClusterId',
'SnapshotWindow': 'SnapshotWindow'
}
need_update = {}
for m, o in modifiable.items():
if m in desired:
if not o:
# Always pass these through - let AWS do the math...
need_update[m] = desired[m]
else:
if m in current:
# Equivalence testing works fine for current simple type comparisons
# This might need enhancement if more complex structures enter the picture
if current[m] != desired[m]:
need_update[m] = desired[m]
return need_update | python | def _diff_replication_group(current, desired):
'''
If you need to enhance what modify_replication_group() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_replication_group() to that in describe_replication_groups(). Any data fiddlery
that needs to be done to make the mappings meaningful should be done in the munging section
below as well.
This function will ONLY touch settings that are explicitly called out in 'desired' - any
settings which might have previously been changed from their 'default' values will not be
changed back simply by leaving them out of 'desired'. This is both intentional, and
much, much easier to code :)
'''
if current.get('AutomaticFailover') is not None:
current['AutomaticFailoverEnabled'] = True if current['AutomaticFailover'] in ('enabled',
'enabling') else False
modifiable = {
# Amazingly, the AWS API provides NO WAY to query the current state of most repl group
# settings! All we can do is send a modify op with the desired value, just in case it's
# different. And THEN, we can't determine if it's been changed! Stupid? YOU BET!
'AutomaticFailoverEnabled': 'AutomaticFailoverEnabled',
'AutoMinorVersionUpgrade': None,
'CacheNodeType': None,
'CacheParameterGroupName': None,
'CacheSecurityGroupNames': None,
'EngineVersion': None,
'NotificationTopicArn': None,
'NotificationTopicStatus': None,
'PreferredMaintenanceWindow': None,
'PrimaryClusterId': None,
'ReplicationGroupDescription': 'Description',
'SecurityGroupIds': None,
'SnapshotRetentionLimit': 'SnapshotRetentionLimit',
'SnapshottingClusterId': 'SnapshottingClusterId',
'SnapshotWindow': 'SnapshotWindow'
}
need_update = {}
for m, o in modifiable.items():
if m in desired:
if not o:
# Always pass these through - let AWS do the math...
need_update[m] = desired[m]
else:
if m in current:
# Equivalence testing works fine for current simple type comparisons
# This might need enhancement if more complex structures enter the picture
if current[m] != desired[m]:
need_update[m] = desired[m]
return need_update | [
"def",
"_diff_replication_group",
"(",
"current",
",",
"desired",
")",
":",
"if",
"current",
".",
"get",
"(",
"'AutomaticFailover'",
")",
"is",
"not",
"None",
":",
"current",
"[",
"'AutomaticFailoverEnabled'",
"]",
"=",
"True",
"if",
"current",
"[",
"'Automati... | If you need to enhance what modify_replication_group() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_replication_group() to that in describe_replication_groups(). Any data fiddlery
that needs to be done to make the mappings meaningful should be done in the munging section
below as well.
This function will ONLY touch settings that are explicitly called out in 'desired' - any
settings which might have previously been changed from their 'default' values will not be
changed back simply by leaving them out of 'desired'. This is both intentional, and
much, much easier to code :) | [
"If",
"you",
"need",
"to",
"enhance",
"what",
"modify_replication_group",
"()",
"considers",
"when",
"deciding",
"what",
"is",
"to",
"be",
"(",
"or",
"can",
"be",
")",
"updated",
"add",
"it",
"to",
"modifiable",
"below",
".",
"It",
"s",
"a",
"dict",
"map... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto3_elasticache.py#L548-L598 | train |
saltstack/salt | salt/states/boto3_elasticache.py | _diff_cache_subnet_group | def _diff_cache_subnet_group(current, desired):
'''
If you need to enhance what modify_cache_subnet_group() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_cache_subnet_group() to that in describe_cache_subnet_group(). Any data fiddlery that
needs to be done to make the mappings meaningful should be done in the munging section
below as well.
This function will ONLY touch settings that are explicitly called out in 'desired' - any
settings which might have previously been changed from their 'default' values will not be
changed back simply by leaving them out of 'desired'. This is both intentional, and
much, much easier to code :)
'''
modifiable = {
'CacheSubnetGroupDescription': 'CacheSubnetGroupDescription',
'SubnetIds': 'SubnetIds'
}
need_update = {}
for m, o in modifiable.items():
if m in desired:
if not o:
# Always pass these through - let AWS do the math...
need_update[m] = desired[m]
else:
if m in current:
# Equivalence testing works fine for current simple type comparisons
# This might need enhancement if more complex structures enter the picture
if current[m] != desired[m]:
need_update[m] = desired[m]
return need_update | python | def _diff_cache_subnet_group(current, desired):
'''
If you need to enhance what modify_cache_subnet_group() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_cache_subnet_group() to that in describe_cache_subnet_group(). Any data fiddlery that
needs to be done to make the mappings meaningful should be done in the munging section
below as well.
This function will ONLY touch settings that are explicitly called out in 'desired' - any
settings which might have previously been changed from their 'default' values will not be
changed back simply by leaving them out of 'desired'. This is both intentional, and
much, much easier to code :)
'''
modifiable = {
'CacheSubnetGroupDescription': 'CacheSubnetGroupDescription',
'SubnetIds': 'SubnetIds'
}
need_update = {}
for m, o in modifiable.items():
if m in desired:
if not o:
# Always pass these through - let AWS do the math...
need_update[m] = desired[m]
else:
if m in current:
# Equivalence testing works fine for current simple type comparisons
# This might need enhancement if more complex structures enter the picture
if current[m] != desired[m]:
need_update[m] = desired[m]
return need_update | [
"def",
"_diff_cache_subnet_group",
"(",
"current",
",",
"desired",
")",
":",
"modifiable",
"=",
"{",
"'CacheSubnetGroupDescription'",
":",
"'CacheSubnetGroupDescription'",
",",
"'SubnetIds'",
":",
"'SubnetIds'",
"}",
"need_update",
"=",
"{",
"}",
"for",
"m",
",",
... | If you need to enhance what modify_cache_subnet_group() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_cache_subnet_group() to that in describe_cache_subnet_group(). Any data fiddlery that
needs to be done to make the mappings meaningful should be done in the munging section
below as well.
This function will ONLY touch settings that are explicitly called out in 'desired' - any
settings which might have previously been changed from their 'default' values will not be
changed back simply by leaving them out of 'desired'. This is both intentional, and
much, much easier to code :) | [
"If",
"you",
"need",
"to",
"enhance",
"what",
"modify_cache_subnet_group",
"()",
"considers",
"when",
"deciding",
"what",
"is",
"to",
"be",
"(",
"or",
"can",
"be",
")",
"updated",
"add",
"it",
"to",
"modifiable",
"below",
".",
"It",
"s",
"a",
"dict",
"ma... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto3_elasticache.py#L981-L1011 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.